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, ) belongs to the code, the noise and the decoder together. A worse decoder makes the same code look worse.

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 and any error that produces it. Every other error with syndrome has the form , with a stabilizer and a logical operator, so these errors fall into logical classes . One correction fixes a whole class; different classes need corrections that differ by a logical operator. The decoder’s real job is to pick a class, and picking the wrong one is a logical failure.

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 from syndromes to classes, and it succeeds with probability . Each term is largest when is the most probable class, which is what ML picks.

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 the two rules agree on every syndrome (both fail with probability at and at ). They never tie: stabilizers have even weight and the logical operator has odd weight , so the two classes have opposite weight parities. The gap matters most near threshold. For independent bit flips on the toric code, the threshold is about 10.3% under MW decoding (Wang, Harrington and Preskill 2003) and about 10.9% under ML decoding (Dennis et al. 2002).

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 at cost , approaching ML as grows. Too slow for real time, it is the standard reference decoder: it shows how much accuracy a fast decoder leaves on the table. Circuit noise makes the network three-dimensional and much harder to contract.

Matching on a decoding graph

Lecture 4 reduced circuit noise to independent mechanisms , each with a probability , the detectors it flips and the observables it flips. For the surface code, Stim’s decomposition splits every mechanism into pieces that flip at most two detectors. Detectors become nodes, plus one boundary node, and each piece becomes an edge between its two detectors (or its one detector and the boundary): the decoding graph.

The most probable set of mechanisms consistent with the fired detectors maximises . Divide by the constant and take minus the logarithm: the task becomes minimising with

A set of edges flips a node exactly when an odd number of its edges touch that node. So must have the fired detectors as its odd-degree nodes; the boundary node is exempt.

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.

detectors across, rounds down boundary space boundary time fired detector silent detector matched edge graph edge edge weight ln((1-p)/p)

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 , 7-round SI1000 circuit at in 0.83 µs per shot.

Matching is MW decoding on this graph, so it inherits MW’s blind spots. It ignores degeneracy. And decomposition discards correlations: a error flips both an -type and a -type detector, but the graph stores it as two independent edges with separate weights.

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.3374

Sixteen -type detectors (four per layer) plus the boundary give 17 nodes; the 55 edges remain after merging parallel pieces.

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 , with the inverse Ackermann function (Delfosse and Nickerson, Quantum 5, 595 (2021)). The price is accuracy. On the toric code with bit-flip noise, where all edges are equally likely, Delfosse and Nickerson reach 9.9% against 10.3% for matching, but only when the odd cluster with the smallest boundary grows first (their Weighted Growth, not the edge lengths below). Growing all odd clusters at once, as Notebook 5 does, gives about 9.2%. Deltakit 0.10.2 has no local Union–Find, so Notebook 5 writes one in plain Python on dec.decoding_graph and runs it on PyMatching’s seeded samples. “Unit” fills every edge in two half-steps; “weighted” uses half-steps, so unlikely edges fill later. (This “weighted” is about edge lengths, not Delfosse and Nickerson’s Weighted Growth.)

SI1000, rounds shotsmatchingUF, unitUF, weighted
, 100,000344434359
, 50,000388656433
, 20,0007721495

Weights recover most of the gap, and the gap grows with when they are missing.

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 , but BP-OSD decodes any code with a sparse check matrix, including the qLDPC codes of Lecture 7, where matching does not apply (Panteleev and Kalachev, Quantum 5, 585 (2021); Roffe et al., PRR 2, 043423 (2020)). Recent BP variants try to make BP accurate enough on its own for real-time qLDPC decoding, for example IBM’s Relay-BP (PREPRINT; arXiv 2506.01779).

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 PyMatchingDecoder runs locally. BeliefMatchingDecoder, BPOSDecoder, ACDecoder (ambiguity clustering), LCDecoder (local clustering), MWPMDecoder and CCDecoder run on Riverlane’s cloud service and need a token. They implement only decode_batch_to_logical_flip, so they work with run_decoding_on_circuit and 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 gates of Lecture 8) need the decoder’s answer to continue. Throughput must match the hardware, about one round per microsecond on superconducting qubits, or the backlog of undecoded rounds grows without bound. Latency, the delay from the last round a decision needs to the decision, stalls every step that waits.

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 .

commit buffer window 1 commit buffer window 2 commit buffer window 3 c rounds b rounds time (rounds) each window decodes commit + buffer and keeps only the commit part

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 , a chain long enough to be committed wrongly is about as unlikely as a logical failure. Sliding windows are sequential. Riverlane’s parallel window decoder decodes alternate windows at once and stitches them in a second pass, so throughput grows with the number of cores, with no noticeable loss of fidelity (PUBLISHED; Skoric et al., Nat. Commun. 14, 7040 (2023)).

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 shots

These 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: True

The 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 dets with a PyMatchingDecoder built 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).