Lecture 4 turned a noisy circuit into a detector error model: a list of independent error
mechanisms, each flipping a few detectors and perhaps the logical observable. A run of the
experiment shows you only which detectors fired. The decoder has to say, from that list alone,
whether the observable was flipped. Everything Lecture 6 measures (logical error rates,
thresholds,
This lecture covers what the best possible decoder would do and why nobody runs it, why
minimum-weight matching is the default for surface codes, and what the alternatives give up or
add. Along the way we open Deltakit’s PyMatchingDecoder and see what it returns.
Notebook and field map
Notebook 5: Decoding computes maximum-likelihood and minimum-weight decoding exactly by enumerating every error on small codes, opens PyMatching’s decoding graph, and races a hand-written Union–Find decoder against it on the same samples. Field map: ML versus minimum weight, Matching and PyMatching, Union–Find, BP and BP-OSD, Belief-matching, Windowed and real-time decoding.
The decoding problem
Start with code-capacity noise: independent Pauli errors on the data qubits, perfect check
measurements. Fix a syndrome
Definition 5.1 (Maximum-likelihood and minimum-weight decoding).Given a syndrome
, a maximum-likelihood (ML) decoder returns the logical class with the largest total probability, . A minimum-weight (MW) decoder returns the class of the single most probable error with syndrome . For independent noise of strength per qubit that error has minimum weight .
Theorem 5.1 (Maximum likelihood is optimal).Among all decoders that see only the syndrome, the ML decoder has the smallest probability of logical failure.
The proof takes one line. A decoder is a map
The two rules in Definition 5.1 differ because of degeneracy. An MW decoder looks at one error, while an ML decoder adds up every error in a class. A class with many slightly heavier errors can outweigh a class with one light error.
Example 5.1 (Where minimum weight and maximum likelihood disagree).Take the
rotated surface code with independent errors of probability on its 25 data qubits and 12 checks. Notebook 5 enumerates all errors. At the rules disagree on 181 of the syndromes. In one, three checks fire; one class holds a single weight-3 error, the other nothing lighter than weight 4 but twelve of those. To leading order ML prefers the heavier class when , that is when . With every weight included, the switch happens at . Summed over all syndromes, the exact failure probability at is for MW and for ML.
So Theorem 5.1 holds, but in Example 5.1 ML wins by only 0.4% at a high error rate, and
at
Why not always run ML? For a general stabilizer code it is #P-hard
(Iyer and Poulin 2015). For the surface code with
code-capacity noise, each class probability is the partition function of a two-dimensional
Ising-like model, and Bravyi, Suchara and Vargo (2014)
contract it as a tensor network with bond dimension
Matching on a decoding graph
Lecture 4 reduced circuit noise to independent mechanisms
The most probable set
A set of edges flips a node exactly when an odd number of its edges touch that node. So
Definition 5.2 (Matching decoder).Given the fired detectors on a decoding graph with weights
, a matching decoder finds the lightest set of edges whose odd-degree nodes are exactly the fired detectors (plus, possibly, the boundary). Equivalently, it pairs up the fired detectors, or sends some to the boundary, so that the sum of shortest-path distances is minimal: a minimum-weight perfect matching. Its prediction is the parity of observable flips along the chosen edges.
The figure shows the three kinds of pairing: neighbours in one round (a data-qubit error), the same place in consecutive rounds (a measurement error), and a detector near the edge paired with the boundary.
Edmonds’ blossom algorithm finds the matching of Definition 5.2 in polynomial time, but the
naive reduction builds a complete graph of shortest-path distances between fired detectors,
quadratic in their number. Sparse blossom, inside PyMatching 2, runs blossom directly on the
decoding graph, growing regions around fired detectors much like the Union–Find decoder below
while keeping the matching optimal. Its authors
report under a microsecond per round, for both bases of a distance-17 surface code at 0.1%
circuit noise, on one core (PUBLISHED; Higgott and Gidney,
Quantum 9, 1600 (2025)). On the laptop
that built this page, PyMatching decoded the
Matching is MW decoding on this graph, so it inherits MW’s blind spots. It ignores degeneracy.
And decomposition discards correlations: a
The playground below runs exact minimum-weight matching on code-capacity noise. Click qubits to place errors, then decode.
Here is Deltakit’s decoding graph for the three-round, distance-3 experiment of Lecture 0. The
decoder’s decoding_graph is NetworkX-backed; each edge carries its merged probability p_err
and its weight.
import numpy as np
from deltakit.circuit.gates import PauliBasis
from deltakit.decode import PyMatchingDecoder
from deltakit.explorer.codes import RotatedPlanarCode, css_code_memory_circuit
from deltakit.explorer.qpu import QPU, SI1000Noise
SEED = 2026
code = RotatedPlanarCode(width=3, height=3)
circ = css_code_memory_circuit(code, num_rounds=3, logical_basis=PauliBasis.Z)
qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=1e-3))
noisy = qpu.compile_and_add_noise_to_circuit(circ)
dec, dec_circ = PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy)
graph = dec.decoding_graph
print(type(graph).__name__, len(graph.nodes), "nodes,",
len(graph.edges), "edges")
print("boundary node:", set(graph.boundaries))
u, v = graph.edges[0]
attrs = graph.graph.edges[u, v]
p = attrs["p_err"]
print(f"edge ({u}, {v}): p_err = {p:.5f}, weight = {attrs['weight']:.4f}")
print(f"ln((1 - p) / p) = {np.log((1 - p) / p):.4f}")NXDecodingGraph 17 nodes, 55 edges
boundary node: {16}
edge (16, 0): p_err = 0.00479, weight = 5.3374
ln((1 - p) / p) = 5.3374Sixteen
Faster and more general decoders
Definition 5.3 (Union–Find decoder).Grow a cluster around each fired detector by half an edge per step. When two clusters touch, merge them; a union–find data structure tracks which cluster each node belongs to. A cluster stops growing once it holds an even number of fired detectors or touches the boundary. Then, inside each cluster, peeling a spanning tree from its leaves picks the edges whose odd-degree nodes are the cluster’s fired detectors.
Each merge costs almost constant time, so the decoder of Definition 5.3 runs in
dec.decoding_graph and runs it on PyMatching’s seeded samples. “Unit” fills every edge in two
half-steps; “weighted” uses
| SI1000, rounds | shots | matching | UF, unit | UF, weighted |
|---|---|---|---|---|
| 100,000 | 344 | 434 | 359 | |
| 50,000 | 388 | 656 | 433 | |
| 20,000 | 77 | 214 | 95 |
Weights recover most of the gap, and the gap grows with
Belief propagation (BP) passes messages on the Tanner graph of the detector error model (one node per mechanism, one per detector), each an estimate of the probability that a mechanism fired. On a tree it gives exact marginals in a few rounds. Surface codes are far from trees, and degeneracy confuses BP: with two equally likely corrections, each mechanism ends near one half and the hard decision matches neither. Alone, BP is a poor surface-code decoder, but it is fast, local, and handles mechanisms that flip three or more detectors, which matching cannot.
Ordered statistics decoding (OSD) repairs BP’s failures: sort mechanisms by BP marginal, take
the first linearly independent columns of the check matrix in that order, and solve the syndrome
equation on them by Gaussian elimination (OSD-0); higher orders also try flipping a few other
columns. The elimination costs
Belief-matching runs BP on the full detector error model, including the mechanisms that decomposition would split, then reweights the matching graph with the BP marginals and matches. That restores some lost correlations. Under circuit noise it raised the surface-code threshold from 0.82% to 0.94% (PUBLISHED; Higgott, Bohdanowicz, Kubica, Flammia and Campbell, PRX 13, 031007 (2023)).
Among neural decoders, AlphaQubit, a recurrent transformer trained on simulated and then experimental data, outperformed the best algorithmic decoders on data from Google’s Sycamore processor at distances 3 and 5, and kept its advantage on simulated data up to distance 11 (PUBLISHED; Bausch et al., Nature 635, 834 (2024)). It is not yet fast enough to keep up with a superconducting processor in real time.
Remark 5.1 (What runs locally in Deltakit).Only
PyMatchingDecoderruns locally.BeliefMatchingDecoder,BPOSDecoder,ACDecoder(ambiguity clustering),LCDecoder(local clustering),MWPMDecoderandCCDecoderrun on Riverlane’s cloud service and need a token. They implement onlydecode_batch_to_logical_flip, so they work withrun_decoding_on_circuitand nothing else.
Decoding in time: windows and real time
A memory experiment is decoded once, after the last round. A computation cannot wait: the
syndrome stream does not end, and some operations (the
Definition 5.4 (Sliding-window decoding).Decode rounds
to as one problem: a commit region of rounds followed by a buffer of rounds, typically . Keep the correction’s edges in the commit region, discard the rest, carry the effect of the committed edges on the next detectors forward, and start the next window at round .
The buffer in Definition 5.4 exists because a chain near the end of a window may continue into
rounds the window cannot see; with
Real-time decoding now works in experiments. On Google’s Willow processor a distance-5 surface code ran with a real-time decoder for up to a million cycles at 1.1 µs per cycle, with an average decoder latency of 63 µs, and stayed below threshold (PUBLISHED; Google Quantum AI and collaborators, Nature 638, 920 (2025)). Riverlane’s Local Clustering Decoder, a Union–Find-style clustering decoder on an FPGA, decodes in under a microsecond per round and adapts its graph at run time, for example to heralded leakage (PUBLISHED; Ziad et al., Nat. Commun. 16, 11048 (2025)).
Deltakit 0.10.2 has helpers in deltakit.core.decoding_graphs for cutting a decoding graph into
windows (annotate_edges_with_window_ids, induce_subhypergraph), but no decoder that runs
windows; LCDecoder is the cloud version of the Local Clustering Decoder.
In Deltakit
Continuing from the block above: sample the decoder’s circuit with a seed, decode, and count wrong predictions.
sampler = dec_circ.compile_detector_sampler(seed=SEED)
dets, obs = sampler.sample(100_000, separate_observables=True)
pred = dec.decode_batch_to_logical_flip(dets)
fails = int(np.any(pred != obs, axis=1).sum())
print(dets.shape, obs.shape, pred.shape, pred.dtype)
print(f"{fails} failures in {len(dets)} shots")(100000, 16) (100000, 1) (100000, 1) uint8
344 failures in 100000 shotsThese are the 344 failures of Lecture 0. The decoder can also return the matched edges, one
column per edge of graph.edges; the logical flip is their parity on the edges listed in
dec.logicals:
full = dec.decode_batch_to_full_correction(dets)
index = {frozenset(e): i for i, e in enumerate(graph.edges)}
crosses = np.zeros(len(graph.edges), dtype=np.uint8)
for e in dec.logicals[0]:
crosses[index[frozenset(e)]] = 1
print(full.shape, full.dtype, "|",
int(crosses.sum()), "edges cross the logical")
parity = (full.astype(np.int64) @ crosses) % 2
print("parity on those edges equals the logical flip:",
bool(np.array_equal(parity, pred[:, 0])))(100000, 55) uint8 | 8 edges cross the logical
parity on those edges equals the logical flip: TrueThe quick-start call runs the loop in one line, with no seed and a progress bar: fine for exploring, never for a number you will quote.
import contextlib
import io
from deltakit.decode.analysis import run_decoding_on_circuit
with contextlib.redirect_stderr(io.StringIO()): # hide the progress bar
result = run_decoding_on_circuit(dec_circ, 20_000, dec)
print(sorted(result))['fails', 'fails_log_0', 'shots']The cloud decoders of Remark 5.1 take the full noisy circuit (they do no trimming) and a client that holds your token. This block is not run on this page:
from deltakit.decode import BeliefMatchingDecoder, BPOSDecoder
from deltakit.explorer import Client
Client.set_token("<your Riverlane token>") # once per machine
client = Client.get_instance()
stim_circ = noisy.as_stim_circuit()
bm = BeliefMatchingDecoder(stim_circ, client=client)
bposd = BPOSDecoder(stim_circ, parameters={"max_bp_rounds": 20},
client=client)
result = run_decoding_on_circuit(stim_circ, 100_000, bm)Try this
- In the playground, set
and place three errors on a diagonal. Decode. Is the residual (error times correction) a stabilizer or a logical operator? Now try four errors. - In Notebook 5, rerun the exact enumeration at
and . How does the MW/ML gap for change, and why does it shrink at low ? - Decode the same
detswith aPyMatchingDecoderbuilt at(wrong weights). How sensitive is matching to its weights?
Readings
- E. Dennis, A. Kitaev, A. Landahl and J. Preskill, Topological quantum memory, J. Math. Phys. 43, 4452 (2002).
- O. Higgott and C. Gidney, Sparse Blossom: correcting a million errors per core second with minimum-weight matching, Quantum 9, 1600 (2025).
- N. Delfosse and N. H. Nickerson, Almost-linear time decoding algorithm for topological codes, Quantum 5, 595 (2021).
- J. Roffe, D. R. White, S. Burton and E. Campbell, Decoding across the quantum low-density parity-check code landscape, PRR 2, 043423 (2020).
- S. Bravyi, M. Suchara and A. Vargo, Efficient algorithms for maximum likelihood decoding in the surface code, PRA 90, 032326 (2014).