Module 10: Decoding I: Maximum Likelihood and Matching
A syndrome tells you where something went wrong, but not what went wrong. Many different errors share one syndrome. A decoder is the classical algorithm that looks at the syndrome, or at the detection events of Module 9, and picks a correction. This module asks two questions. What is the best possible choice? And how close can a fast algorithm get to it? For surface codes the answer to the second question is minimum-weight perfect matching (MWPM), the decoder used in most surface-code experiments to date.
Learning goals. After this module you should be able to
state the decoding problem for a stabilizer code and its success criterion, ;
distinguish minimum-weight (most-probable-error) decoding from degenerate maximum-likelihood (coset) decoding, and give a concrete syndrome where they disagree;
build a lookup-table decoder for a small code;
convert error probabilities into log-likelihood edge weights ;
build the matching graph of a repetition, toric or surface code, including boundary nodes;
explain why minimum-weight decoding of a graphlike error model is a minimum-weight perfect matching problem, and run it with PyMatching.
1. The decoding problem
Recall from Module 3 the setting. A stabilizer code with stabilizer group suffers a Pauli error , drawn from some noise model . We measure the generators and get the syndrome , whose bit is exactly when anticommutes with . We may then apply any Pauli we like.
The key point is that we do not need . The net operator on the code is . If is a stabilizer, it acts as the identity on every codeword, so the data is unharmed. If commutes with all of but is not in (up to phase), it is a nontrivial logical operator: the syndrome is back to zero, but the logical state has been changed silently.
Definition 10.1 (Decoding problem).
Given a syndrome and a noise model on , a decoder outputs a Pauli with . Decoding succeeds if (up to phase) and fails if , where is the normalizer. The logical error rate of a decoder is
Because , the product always has trivial syndrome, so it is always in . Only two outcomes are possible: success or a logical error. There is no third case where the decoder “leaves a syndrome behind”.
Cosets: the right way to group errors
Fix a syndrome and pick any one error with that syndrome. Every other error with the same syndrome has the form , with and a logical Pauli. Multiplying by does nothing to the code, so the errors with syndrome split into logical classes
one class for each of the logical Paulis (ignoring phases). Any two corrections in the same class are equally good. So the decoder’s real job is to pick a class, not a specific error. This is degeneracy at work: different errors with the same effect are interchangeable.
2. Three decoders: minimum weight, maximum likelihood, lookup table
With the problem of Definition 10.1 in hand, here are the three basic answers.
Definition 10.2 (Minimum-weight and maximum-likelihood decoders).
Let be the observed syndrome.
The minimum-weight (most-probable-error, MPE) decoder outputs a single most likely error, . For i.i.d. noise with this is the minimum-weight error with syndrome .
The maximum-likelihood (degenerate ML, or coset) decoder outputs any member of the most likely class:
The ML decoder sums over every error in a class. The MW decoder looks only at the single best element. They agree when one error dominates its class. They can disagree when one class has a lone light error and another has many slightly heavier errors.
Proposition 10.1 (ML decoding is optimal).
Among all decoders, the maximum-likelihood decoder minimizes the logical error rate for the given noise model.
Proof
Group the sum defining by syndrome. For a syndrome , the decoder’s output lies in exactly one class, say . Decoding succeeds exactly when the true error is in that same class. So the success probability is
Each term depends only on the class chosen for that syndrome, and the terms do not interact. The sum is therefore maximized by choosing, for every separately, the class with the largest probability. That is exactly the ML rule.
ML decoding is optimal but expensive. For general stabilizer codes, both minimum-weight and degenerate ML decoding are computationally hard in the worst case (Iyer and Poulin, arXiv:1310.3235). Practical decoders exploit the structure of a specific code family.
The lookup-table decoder
For a small code you can afford to precompute the answer for every syndrome. A lookup table stores, for each of the syndromes, one correction. If you store a minimum-weight error you get a MW decoder. If you store a representative of the most probable class you get an ML decoder.
Example 10.1 (Lookup table for the distance-3 rotated surface code).
Number the nine data qubits of the rotated code row by row, to . We use the checkerboard layout drawn below: Z-type checks , , , ; X-type checks , , , . The logical operators are (a row) and (a column). One can check all checks commute, each family has rank 4, and .
Relation to Module 8. This is the layout of Module 8 (Definition 8.2) mirrored left to right and numbered from 1. Module 8 qubit (0-indexed) becomes qubit here, so Module 8 qubits become , and so on. Under this relabeling Module 8’s Z checks , , , become , and its X checks become the four X checks above. The logicals also match up to stabilizers: Module 8’s top row becomes . The mirror only relabels qubits, so every syndrome table and failure probability below carries over.
Consider X errors only. They are seen by the four Z checks, so there are syndromes. For each one, a brute-force search over all X errors gives a minimum-weight correction:
MW correction
MW correction
0000
none
0001
1000
(or )
1001
(3 ties)
0100
(or )
0101
1100
1101
(3 ties)
0010
0011
1010
1011
0110
(3 ties)
0111
1110
(3 ties)
1111
Look at syndrome . Both and have weight 1. They differ by , which is a stabilizer. So they are in the same class, and it does not matter which one we store. The search confirms this for every syndrome: whenever there are ties, all tied errors lie in one class.
For this small code, the minimum-weight lookup table and the ML decoder make the same choice for all 16 syndromes, at every we tested. Summing exactly over all 512 errors gives the same logical failure probability for both: at and at . The difference between the two decoders only shows up at larger distance.
Example 10.2 (Where minimum weight and maximum likelihood disagree).
Take the distance-5 rotated surface code (the checkerboard convention of Example 10.1, with a Z check on the top-left square; 25 qubits, 12 Z checks) with i.i.d. X errors. Exhaustive enumeration over all X-stabilizers turns up syndromes where the two decoders disagree. The simplest has only three flagged checks: the top-left bulk Z check, the Z check whose top-left qubit is at row 2, column 2 (counting from 0), and the left-boundary check .
Class B contains one error of weight 3, , and no lighter ones.
Class A contains no error of weight 3 but twelve errors of weight 4.
To leading order the class probabilities are versus , times the common factor . Class A wins once , that is, for . The exact sums (including all heavier errors) give at . At the order flips: . A minimum-weight decoder always picks class B. ML picks class A at high noise.
Summed over all syndromes, the exact failure probability at is for MW and for ML. The gap is small here, but it grows with the code size. It is the reason the code-capacity threshold of the toric code is about with matching but about with ML decoding (Wang, Harrington, Preskill 2003).
The physics behind the gap is entropy. A heavier class can win because it contains many more configurations. In the statistical-mechanics mapping of Dennis, Kitaev, Landahl and Preskill, MW decoding corresponds to a random-bond Ising model at zero temperature. ML decoding corresponds to the same model at a finite temperature fixed by (the Nishimori line), where entropy counts.
3. From probabilities to weights
Most practical decoders minimize a sum of weights rather than maximize a product of probabilities. The conversion is a logarithm.
Suppose the noise consists of independent error mechanisms, where mechanism fires with probability . Here “mechanism” might mean “X error on qubit ” (code capacity) or a line of a detector error model (circuit noise, Module 9). An error configuration is a bit string . Its probability is
Taking turns the product into a sum:
So the most probable error is the one of minimum total weight. Here are some values:
0.001
6.907
6.908
0.01
4.595
4.605
0.02
3.892
3.912
0.1
2.197
2.303
Three remarks. First, likely mechanisms get small weights. Second, exactly when , which minimum-weight decoding needs (otherwise adding an error would lower the cost). Third, for small the weight is close to , which is the form used in some slides and papers. With uniform every weight is equal, so minimum weight reduces to minimum Hamming weight.
4. Matching graphs
Now we use the structure of the code. In the surface and toric codes, and in the repetition code, each single error flips at most two checks. A model with this property is called graphlike. Graphlike models are what make matching possible.
Definition 10.3 (Matching (decoding) graph).
For a graphlike error model, the matching graph has one node per check (or per detector, for circuit noise), plus one extra boundary node. Each error mechanism is an edge:
between the two nodes it flips, if it flips two;
between the one node it flips and , if it flips only one.
Edge carries the weight from Eq. . The flagged nodes of a syndrome are called defects (or detection events).
For a CSS code with independent X and Z noise, we build two separate graphs. Z errors are seen by the X checks, and X errors by the Z checks. Each graph is decoded on its own.
Here is the key translation. An error configuration is a set of edges . Its syndrome is the set of nodes touched by an odd number of edges of , ignoring . Write this as , the boundary of . A correction must therefore be an edge set whose boundary is exactly the defect set .
Example 10.3 (Distance-5 repetition code).
The bit-flip repetition code on five qubits has checks , , , . The matching graph is a path: , with qubit as the -th edge. Qubits and touch only one check each, so they are edges to the boundary node.
Error flips and . There are two candidate corrections: (i) pair with through (weight 2), or (ii) send to the boundary through and to the boundary through (weight 3). Option (i) is lighter. It equals the error, so decoding succeeds.
Error has weight . It flips only . The lighter way to explain a single defect at is (weight 2) rather than (weight 3). The net operator is , a logical error.
PyMatching, given the check matrix, returns exactly these corrections.
bc1c2c3c4bq1q2q3q4q5(i) pair c1 with c3: weight 2(ii) both to b: 1 + 2
Minimum-weight decoding is a matching problem
Let be the set of defects. We need an edge set with and minimum total weight. Classical graph theory turns this into a pairing problem.
Definition 10.4 (Perfect matching).
A perfect matching of a graph is a set of edges in which every node appears in exactly one edge. A minimum-weight perfect matching (MWPM) is one with the smallest total weight.
Starting from the matching graph of Definition 10.3, build the syndrome graph: a complete graph on the defects, where the edge has weight , the shortest-path distance between and in the matching graph. To allow defects to end at the boundary, add one boundary copy for each defect . Join to with weight , and join every pair of boundary copies with weight 0. The zero-weight edges let unused boundary copies pair among themselves, so a perfect matching always exists. This holds even when the number of defects is odd.
Theorem 10.1 (Minimum weight = MWPM).
For a graphlike error model with all , the minimum weight of an edge set with equals the weight of a minimum-weight perfect matching of the syndrome graph. A minimum-weight correction is obtained by taking, for each matched pair, a shortest path between them (or from the defect to the boundary), and adding these paths mod 2.
Proof
Lower bound. Take any edge set with . In the subgraph , the nodes of odd degree are exactly the defects, plus possibly . Start a walk at a defect and keep using unused edges of . Each time the walk enters a node of even degree, an unused edge is left to exit by. So the walk can only get stuck at another odd-degree node: another defect, or . Remove that path and repeat. This splits into edge-disjoint paths, each pairing two defects or a defect with , plus leftover cycles. Each path from to weighs at least , and the cycles weigh at least . So is at least the weight of the perfect matching that pairs defects as the paths do (with unused boundary copies paired at cost 0). That is at least the MWPM weight.
Achievability. Given a MWPM, take a shortest path for each matched pair and let be their sum mod 2. Each path flips the parity at exactly its two endpoints, so . Adding paths mod 2 can only cancel edges, and all weights are positive, so is at most the MWPM weight. Combined with the lower bound, is a minimum-weight correction.
So for the toric, planar and rotated surface codes under independent X/Z noise, MWPM solves the minimum-weight decoding problem exactly. It does not solve the ML problem, as §2 showed.
Example 10.4 (Matching four defects on a torus).
On an torus with uniform weights, put defects at vertices , , and . The distance is the Manhattan distance, taken the short way around each cycle. The pairwise distances are
Four nodes have three perfect matchings. Their weights are for , for , and for . MWPM picks . In general, defects have perfect matchings, so brute force is hopeless. With defects there are already .
Success and failure on the torus
On the toric code of Module 7, X checks sit on vertices and Z checks on plaquettes. A Z error on a string of edges flips the two vertex checks at its endpoints. MWPM reconnects the defects with a shortest string . The product is a closed loop. As Module 7 showed, the decoder succeeds exactly when this loop is contractible (a product of stabilizers), and fails when it wraps around the torus.
Example 10.5 (An L-shaped error and a wrap-around failure).
On the torus (so ):
An L-shaped weight-2 Z error from vertex to produces defects at diagonal corners of one plaquette. There are two shortest paths. PyMatching returns the other path, so is the boundary of that plaquette, which is a stabilizer. Decoding succeeds even though .
A straight weight-3 Z error along row 2, covering columns 0 to 2, has defects at and . Going the other way around the torus they are only 2 apart. MWPM chooses that weight-2 path, and is a weight-5 loop around the torus: a logical .
This is the general mechanism of logical failure. About errors in a row look exactly like the complementary errors to a minimum-weight decoder (Fowler et al., arXiv:1208.0928, Sec. VII).
C E is a plaquette: successC E wraps the torus: logical errorcolored line = error E; dark line with circles = correction Cfilled dots = defects; right: C exits right, re-enters left
Try the same failure mechanism on a planar patch. The playground below is the rotated surface code of Module 8, decoded by exact minimum-weight matching, with an edge of the patch acting as a boundary node. Place errors by clicking data qubits, or draw a random error at rate , then press Decode. A short chain is always fixed. A string of X errors running down one column from the top edge is matched the “wrong way” to the boundary and gives a logical error.
5. Edmonds’ blossom algorithm and sparse blossom
MWPM can be solved in polynomial time. This is Edmonds’ 1965 result (“Paths, trees, and flowers”, Canad. J. Math. 17, 449). The main ideas, without the full bookkeeping:
Augmenting paths. Start from an empty or partial matching. An augmenting path alternates between unmatched and matched edges and joins two unmatched nodes. Flipping which of its edges are matched grows the matching by one edge.
Blossoms. In a non-bipartite graph, a search for augmenting paths can run into an odd cycle. Edmonds’ insight was to shrink such a cycle (a blossom) into a single super-node, keep searching, and expand it afterwards.
Duals. For the weighted version, each node (and each blossom) carries a dual variable, a “radius”. An edge becomes usable (“tight”) when the radii of its two ends add up to its weight. The algorithm raises radii until new edges become tight. It stops when the matching is perfect and the duals certify that it is optimal.
The textbook running time is cubic in the number of nodes, here the number of defects . Kolmogorov’s Blossom V (2009) is a widely used implementation. Note that the cost depends on the number of defects, not qubits: the instance in Example 10.4 is a 4-node problem, whatever the size of the torus. Below threshold, defects are sparse.
The older pipeline first ran Dijkstra from every defect to fill in the complete syndrome graph, then called Blossom. Sparse blossom (Higgott and Gidney, arXiv:2303.15933, Quantum 9, 1600 (2025)) skips the all-pairs step. It runs the blossom dual updates directly on the sparse detector graph: each defect grows a region outward at unit speed, and regions that collide become tight edges. This resembles the cluster growth of the Union-Find decoder of Module 11, but it still returns an exact MWPM. It is the engine of PyMatching 2. The paper reports decoding a distance-17 surface code with 0.1% circuit-level noise in under per round on a single core, fast enough to keep up with superconducting hardware.
6. Space-time matching with Stim and PyMatching
With measurement errors and circuit noise, the nodes are detectors and the edges are the graphlike mechanisms of the detector error model (Module 9). A data error between rounds flips two detectors in the same round (a space-like edge). A measurement error flips the same check’s detectors in two consecutive rounds (a time-like edge). Some mid-circuit faults give diagonal edges. Each edge also records which logical observables it flips, so the decoder can output a prediction “did the logical observable flip?” instead of a physical correction.
Some mechanisms are not graphlike. In the surface code, a error flips both X-type and Z-type detectors, up to four in total: a hyperedge. Calling detector_error_model(decompose_errors=True) asks Stim to split each hyperedge into graphlike pieces, here an X part and a Z part, so the model can be matched. Information is lost in the split. Correlated matching (Fowler, arXiv:1310.0863) recovers some of it by re-weighting one graph based on the edges chosen in the other.
We ran this with physical error rate on every noise location, rounds = d, for :
detectors
DEM mechanisms
shots
logical errors
per shot
3
24
286
733
5
120
1953
531
7
336
6602
71
The logical error rate falls rapidly with distance. That is the signature of operating below threshold. Module 11 makes “threshold” precise and converts these per-shot numbers into per-round numbers.
7. How matching fails, and how fast
Two facts summarize the behavior of MWPM on surface codes.
Exponential suppression. A minimum-weight decoder corrects every error of weight at most . The cheapest way to fool it uses errors (that is, for odd ) placed along a line between opposite boundaries, as in the torus example. Counting such configurations gives
For circuit-level noise in their model, Fowler, Mariantoni, Martinis and Cleland (2012) fit and .
Threshold values depend on the noise model and the decoder. For the toric code with independent X and Z errors and perfect measurements, MWPM has threshold about and ML about . With depolarizing noise, matching X and Z separately ignores the correlation carried by errors. The gap then widens: Pesah’s survey quotes about for matching versus about for ML. With noisy measurements the matching threshold drops to about . With full circuit-level noise it is typically quoted between about and , depending on the noise model. Never quote “the threshold” without saying which model and which decoder.
Remark 10.1 (Real-time decoding).
A decoder that is accurate but slow still fails. If syndrome data arrives faster than it is processed, a backlog builds up. Every logical operation that has to wait for a decoder output (such as a T gate) then waits longer and longer (Terhal, Rev. Mod. Phys. 87, 307 (2015)). Google’s 2024 Willow experiment ran a matching-based real-time decoder at distance 5. It had an average latency of with a cycle, over up to a million cycles.
Summary
A decoder maps a syndrome to a correction. Success means , not . Errors with the same syndrome split into logical classes, and only the class matters.
ML (coset) decoding (Definition 10.2) chooses the most probable class and is optimal (Proposition 10.1). MW decoding chooses the single most probable error. They agree on the rotated code but disagree on the code (Example 10.2), because of entropy.
Lookup tables are exact and fine for tiny codes (Example 10.1) but grow as .
Independent mechanisms give additive log-likelihood weights, so the most probable error is the minimum-weight one.
For graphlike noise, minimum-weight decoding is MWPM (Definition 10.4) on the syndrome graph with boundary copies (Theorem 10.1). Edmonds’ blossom algorithm solves it in polynomial time, and sparse blossom (PyMatching 2) does so fast enough for real hardware.
MWPM fails when about errors look like (Example 10.3, Example 10.5). This gives exponential suppression , provided the decoder keeps up in real time (Remark 10.1).
Continue with Module 11 for faster and more general decoders, and for thresholds. Practice in Homework 10.
Further reading
E. Dennis, A. Kitaev, A. Landahl, J. Preskill, “Topological quantum memory”, J. Math. Phys. 43, 4452 (2002), arXiv:quant-ph/0110143. Matching decoder, ML decoding and the random-bond Ising model.
C. Wang, J. Harrington, J. Preskill, “Confinement-Higgs transition in a disordered gauge theory and the accuracy threshold for quantum memory”, Ann. Phys. 303, 31 (2003), arXiv:quant-ph/0207088. The 10.3% and 10.9% thresholds.
A. G. Fowler, M. Mariantoni, J. M. Martinis, A. N. Cleland, “Surface codes: Towards practical large-scale quantum computation”, PRA 86, 032324 (2012), arXiv:1208.0928. Sec. VII on logical error rates.
J. Edmonds, “Paths, trees, and flowers”, Canad. J. Math. 17, 449 (1965); V. Kolmogorov, “Blossom V”, Math. Prog. Comp. 1, 43 (2009).
O. Higgott, “PyMatching: A Python package for decoding quantum codes with minimum-weight perfect matching”, ACM TQC 3, 16 (2022), arXiv:2105.13082.
O. Higgott, C. Gidney, “Sparse Blossom: correcting a million errors per core second with minimum-weight matching”, Quantum 9, 1600 (2025), arXiv:2303.15933.
P. Iyer, D. Poulin, “Hardness of decoding quantum stabilizer codes”, IEEE TIT 61, 5209 (2015), arXiv:1310.3235.
A. G. Fowler, “Optimal complexity correction of correlated errors in the surface code”, arXiv:1310.0863.
A. Pesah, “An interactive introduction to the surface code” (2023), decoding and threshold sections.