The decoding problem
After a memory experiment we hold, for each shot, a bit string of detection events and, in simulation, the true flip of the logical observable. The decoder sees only the detection events and must predict the observable flip. If its prediction is wrong the shot is a logical failure. Everything in the previous lesson (circuits, noise, detectors) exists to set up this inference problem; the decoder is where the code's protection is realised or lost.
The ideal decoder would compute, for each syndrome, which logical class of errors is most probable, summing over all errors in each class. That is intractable in general. Minimum-weight perfect matching (MWPM) solves a simpler problem exactly and fast: find the single most probable error consistent with the detection events, under the assumption that every error mechanism is independent and flips at most two detectors. For the surface code under independent and noise this approximation is excellent, and it is the standard baseline against which other decoders are measured (Dennis et al. 2002).
From error model to graph
A detector error model (DEM) lists independent mechanisms , each occurring with probability and flipping a set of detectors and observables. Suppose every mechanism flips at most two detectors (after Stim's decomposition). Build a graph:
- one node per detector, plus one boundary node;
- one edge per mechanism, between the two detectors it flips, or between its single detector and the boundary;
- each edge remembers which observables the mechanism flips.
A set of mechanisms produces the detection events : a detector fires when an odd number of chosen edges touch it. (The boundary node absorbs any parity.) Its probability is
so
Maximising the probability of the error is minimising the total weight. For every weight is positive, and rarer mechanisms are heavier. Two mechanisms with identical effects are merged before this step, combining as independent events: .
Worked example. Take the 5-qubit bit-flip code under code-capacity noise with flip probability and syndrome : checks 0 and 3 fired. The graph is a path: boundary, check 0, check 1, check 2, check 3, boundary, with one edge per data qubit, each of weight . Two explanations exist: connect check 0 to check 3 (data qubits 1, 2, 3; weight ), or connect each fired check to its nearest boundary (data qubits 0 and 4; weight ). Matching chooses the second, , exactly the minimum-weight correction of the repetition-code lesson. Its probability ratio to the alternative is .
From graph to matching
The minimum-weight with equal to the observed detection events can be found in two steps.
- Shortest paths. For every pair of fired detectors compute the shortest-path distance in the graph, and for every fired detector its distance to the boundary node.
- Matching. Build a complete graph on the fired detectors, plus one boundary twin for each fired . Give edge – weight , edge – weight , and every twin–twin edge weight 0. A minimum-weight perfect matching of this graph (every node in exactly one pair) pairs each defect either with another defect or with the boundary; the twins left over pair among themselves for free.
The union of the shortest paths of matched pairs is a minimum-weight error with the right boundary. Its effect on the logical observable is the XOR of the observable flags along those paths; that is the decoder's prediction. Minimum-weight perfect matching on general graphs is solvable in polynomial time by Edmonds' blossom algorithm (Edmonds 1965).
This two-step construction is how the exercise's reference decoder works, using NetworkX for Dijkstra and for the blossom algorithm. It is clear and slow. PyMatching (Higgott 2022) solves the same problem directly on the sparse detector graph; version 2 implements the sparse blossom algorithm (Higgott and Gidney 2025), which avoids the all-pairs shortest-path step entirely and is many orders of magnitude faster on large circuits. The exercise checks, shot by shot, that the two find matchings of the same total weight.
Why matching works for the surface code
In a -memory experiment the detectors are built from -check outcomes, and an error on a data qubit in the bulk flips exactly two checks (two detectors in the same round), or one if it sits next to a boundary that carries only checks. A measurement error flips the same check in two consecutive rounds. Each elementary fault is therefore an edge in a three-dimensional space-time graph, and the matching picture of the toric-code lesson applies directly: error strings are detected at their endpoints, and the decoder joins endpoints by the cheapest strings. errors are invisible to a memory's detectors and are handled by the -type detectors of an memory, independently.
A space-time example
Return to the hand-written distance-3, two-round repetition memory of the Stim lesson (uniform noise, ). Its detectors D0 and D1 are the two checks in round 1, D2 and D3 the same checks in round 2, and D4 and D5 the checks recomputed from the final readout. Suppose a shot fires exactly D0 and D2: check 0 in rounds 1 and 2. Reading the matching graph that PyMatching builds from the decomposed model (after merging parallel pieces):
| Edge | Probability | Weight | Physical meaning |
|---|---|---|---|
| D0–D2 | 0.02237 | 3.778 | check 0 misread in round 1 (or an equivalent fault) |
| D0–boundary | 0.02169 | 3.809 | data qubit 0 flipped during round 1 |
| D2–boundary | 0.01713 | 4.049 | data qubit 0 flipped during round 2 |
The table can be read off with a few lines (Stim's generated circuit has the same detector error model as the hand-written one, as the Stim exercise proves):
import numpy as np
import pymatching
import stim
p = 0.01
circuit = stim.Circuit.generated(
"repetition_code:memory", distance=3, rounds=2,
after_clifford_depolarization=p, before_round_data_depolarization=p,
before_measure_flip_probability=p, after_reset_flip_probability=p,
)
matching = pymatching.Matching.from_detector_error_model(circuit.detector_error_model(decompose_errors=True))
for u, v, data in matching.edges():
if (u, v) in ((0, 2), (0, None), (2, None)):
print(u, v, round(data["error_probability"], 5), round(data["weight"], 3))
events = np.zeros(6, dtype=np.uint8)
events[[0, 2]] = 1
print(matching.decode(events, return_weight=True))
Two explanations are consistent with the events: one time-like edge (weight
3.778) or two edges to the boundary (total 7.858). The matching picks the
time-like edge, a measurement error, and predicts no logical flip; calling
matching.decode(events, return_weight=True) returns exactly this prediction
and weight 3.7775. A decoder that trusted the raw syndrome of round 1 would
instead have applied , turning a misread check into a real data error. The
time dimension is what lets the decoder tell a misread check from a real
error.
MWPM is not optimal, and it is worth being precise about why.
- Correlations between and . A error is an and a error on the same qubit. Under depolarizing noise and errors are therefore correlated, and a decoder that matches them separately throws that information away. In the DEM these are the mechanisms Stim must decompose.
- Hyperedges. Mechanisms that flip more than two detectors are split into graphlike pieces with the original probability, an approximation.
- Degeneracy. MWPM picks the most likely error, not the most likely logical class. When many errors of similar weight fall into the same class, the class can be more probable than its single best member suggests.
These are approximations, not bugs; improving on them is an active research area (correlated matching, belief propagation combined with matching, tensor-network and neural decoders, among others). In this course MWPM via PyMatching is the reference decoder, and every logical error rate is quoted together with it.
Decoding with PyMatching
A complete decoding pipeline for a repetition-code memory, comparing MWPM with a syndrome-blind baseline that takes a majority vote of the final data readout, on the same shots:
import numpy as np
import pymatching
import stim
d, rounds, p = 5, 5, 0.03
circuit = stim.Circuit.generated(
"repetition_code:memory", distance=d, rounds=rounds,
after_clifford_depolarization=p, before_round_data_depolarization=p,
before_measure_flip_probability=p, after_reset_flip_probability=p,
)
dem = circuit.detector_error_model(decompose_errors=True)
matching = pymatching.Matching.from_detector_error_model(dem)
print(matching.num_detectors, matching.num_edges)
# Sample measurements once, derive detection events from the same shots.
measurements = circuit.compile_sampler(seed=7).sample(3000)
det, obs = circuit.compile_m2d_converter().convert(measurements=measurements, separate_observables=True)
predictions = matching.decode_batch(det)
mwpm_failures = int(np.sum(np.any(predictions != obs, axis=1)))
majority_failures = int(np.sum(measurements[:, -d:].sum(axis=1) > d // 2))
print(mwpm_failures, majority_failures)
It prints a graph of 24 detectors and 65 edges, then 113 failures for MWPM and 253 for the majority vote out of 3,000 shots (uniform circuit-level noise, , five rounds, seed 7). The majority vote never looks at the syndrome, so every error that accumulates over five rounds reaches the final readout uncorrected; matching removes most of them. Note what this comparison does and does not show: one seed, one parameter point, a statement about these 3,000 shots. Statistical statements need the uncertainty estimates of the next lesson.
Two habits from this snippet matter in every benchmark.
- Decode identical samples with every decoder. Sampling once and decoding many times turns a comparison of decoders into a paired comparison: differences reflect the decoders, not sampling luck.
- Count failures per shot, for all observables. A shot fails if any predicted observable differs from the actual flip.
Reproducing a published-by-software result
The KetQat SDK's surface-code-memory product runs a rotated surface-code
memory with Stim and PyMatching and reports the logical failure count with a
95% Wilson interval. Its record states the noise model and the coordinate
seed it actually sampled with (derived from the user seed and the parameters).
That makes it possible to reproduce the run independently:
import numpy as np
import pymatching
import stim
from ketqat_runner import catalog
d, rounds, p, shots = 3, 3, 0.005, 20_000
result = catalog.run(
"[email protected]", seed=7, distance=d, rounds=rounds,
physical_error_rate=p, basis="z", shots=shots,
).result
print(result["noise_model"])
print(result["logical_failures"], result["confidence_interval"])
circuit = stim.Circuit.generated(
"surface_code:rotated_memory_z", distance=d, rounds=rounds, after_clifford_depolarization=p
)
matching = pymatching.Matching.from_detector_error_model(circuit.detector_error_model(decompose_errors=True))
det, obs = circuit.compile_detector_sampler(seed=result["coordinate_seed"]).sample(shots, separate_observables=True)
ours = int(np.sum(np.any(matching.decode_batch(det) != obs, axis=1)))
print(ours)
Both counts are 103 failures in 20,000 shots (rate 0.00515, Wilson interval ), for depolarizing noise after every Clifford gate only, , 3 rounds, . Exact agreement is expected, not lucky: same circuit, same sampler seed, same decoder version. If your number differs, something in the pipeline differs, and finding out what is a valuable exercise. Note that this model has no measurement or reset noise, so its rates are not comparable with the uniform model used elsewhere in the course.
The exercise
You implement the decoder above from scratch:
matching_graph(dem): nodes, boundary, merged parallel edges, weights, observable flags; checked edge by edge against PyMatching's own graph.mwpm_decode(graph, events, num_observables): Dijkstra, boundary twins, NetworkX blossom, observable parity; checked by requiring the same total matching weight as PyMatching on every one of 1,500 to 2,000 shots of a repetition code and a distance-3 surface code. Failure counts may differ by a few shots, because equally heavy matchings can predict different logical outcomes; equal weights prove both found an optimum.- A syndrome-blind majority-vote baseline, and the SDK reproduction above for two parameter sets, which must match exactly.
Common mistakes
- Using probabilities as weights. Weights are ; with raw probabilities the "minimum" would prefer likely-looking paths for the wrong reason, and parallel mechanisms would combine incorrectly.
- Forgetting the boundary. Without a boundary node an odd number of defects has no perfect matching, and defects near the edge would be paired across the patch.
- Matching only the detection events of the last round. Measurement errors look like data errors unless the time dimension is included; decode the full space-time graph.
- Comparing decoders on different samples. Unpaired comparisons need far more shots to resolve the same difference.
- Claiming MWPM is optimal. It finds a most likely error under independence and graphlike assumptions. For depolarizing noise it is measurably suboptimal; quote the decoder with every result.
- Ignoring ties. Two matchings of equal weight can disagree on the observable. Check optimality by weights, not by identical predictions.
Summary
- Independent mechanisms with probabilities give edge weights ; the minimum-weight explanation is the most likely error.
- Decoding reduces to minimum-weight perfect matching on fired detectors, with boundary twins, solvable by the blossom algorithm.
- PyMatching's sparse blossom solves the same problem very quickly; your own NetworkX decoder must agree with it in matching weight on every shot.
- MWPM ignores – correlations, hyperedges and degeneracy.
- Decode identical samples with every decoder, and reproduce a known result before trusting a pipeline.
Next, logical error rates and thresholds turns failure counts into rates with honest uncertainty and sweeps them across code distances.