About this notebook
Companion to Lecture 5: Decoding. Every cell below was executed headless with the course’s pinned Deltakit (deltakit 0.10.2, deltakit-stim 0.2.7, pymatching 2.4.0, Python 3.12.12); each output is exactly what the code printed. Download the notebook (.ipynb)
Lecture 5 compared decoders on paper. This notebook compares them on numbers. You will:
- compute the exact failure probability of maximum-likelihood (ML) and minimum-weight (MW) decoding on the distance-3 and distance-5 surface codes, by enumerating every error, and find a syndrome where the two rules disagree;
- open the decoding graph that PyMatching builds from a noisy circuit and read its weights;
- write a Union–Find decoder in plain Python on that graph and race it against PyMatching on the same samples;
- meet
run_decoding_on_circuit, the one-line quick start.
Every sampled number uses SEED, and the counts match the tables in Lecture 5.
import contextlib
import io
from collections import deque
import deltakit
import matplotlib.pyplot as plt
import numpy as np
from matplotlib_inline.backend_inline import set_matplotlib_formats
from deltakit.circuit import PauliZ
from deltakit.circuit.gates import PauliBasis
from deltakit.decode import PyMatchingDecoder
from deltakit.decode.analysis import run_decoding_on_circuit
from deltakit.explorer.codes import RotatedPlanarCode, css_code_memory_circuit
from deltakit.explorer.qpu import QPU, SI1000Noise
set_matplotlib_formats("svg")
SEED = 2026
print("deltakit", deltakit.__version__)deltakit 0.10.2
1. Maximum likelihood versus minimum weight, exactly
Take code-capacity noise: independent
For counts[s, c, w], the number of errors with syndrome
- the probability of class
given syndrome is ; - ML picks the larger
, so it fails with probability ; - MW picks the class holding the lightest error, and fails with the other class’s probability.
First, read
def z_checks_and_logical(d):
"""Rows of H_Z and the Z-logical support; columns = data qubits sorted by (y, x)."""
code = RotatedPlanarCode(width=d, height=d)
qubits = sorted(code.data_qubits,
key=lambda q: (int(q.unique_identifier.y), int(q.unique_identifier.x)))
col = {q: i for i, q in enumerate(qubits)}
rows = []
for group in code.stabilisers:
for stab in group:
paulis = [p for p in stab.paulis if p is not None]
if isinstance(paulis[0], PauliZ):
rows.append(sorted(col[p.qubit] for p in paulis))
rows.sort()
z_logical = sorted(col[p.qubit] for p in code.z_logical_operators[0])
return len(qubits), rows, z_logical
n3, rows3, zl3 = z_checks_and_logical(3)
print("d = 3:", n3, "data qubits")
print("Z checks (data-qubit indices):", rows3)
print("Z logical:", zl3)d = 3: 9 data qubits Z checks (data-qubit indices): [[0, 1, 3, 4], [1, 2], [4, 5, 7, 8], [6, 7]] Z logical: [0, 3, 6]
Now the enumeration. Each integer
def enumerate_classes(n, rows, z_logical):
"""counts[s, c, w]: number of X errors with syndrome s, logical class c and weight w."""
masks = [sum(1 << j for j in row) for row in rows]
zmask = sum(1 << j for j in z_logical)
counts = np.zeros((2 ** len(rows)) * 2 * (n + 1), dtype=np.int64)
chunk = 1 << 20
for start in range(0, 1 << n, chunk):
e = np.arange(start, min(start + chunk, 1 << n), dtype=np.uint32)
w = np.bitwise_count(e).astype(np.int64)
s = np.zeros(e.shape, dtype=np.int64)
for k, m in enumerate(masks):
s |= (np.bitwise_count(e & np.uint32(m)).astype(np.int64) & 1) << k
c = np.bitwise_count(e & np.uint32(zmask)).astype(np.int64) & 1
counts += np.bincount((s * 2 + c) * (n + 1) + w, minlength=counts.size)
return counts.reshape(2 ** len(rows), 2, n + 1)
def min_weights(counts):
"""Lightest error in each (syndrome, class); n + 1 if the class is empty."""
n = counts.shape[2] - 1
return np.where(counts > 0, np.arange(n + 1), n + 1).min(axis=2)
def exact_failure(counts, p):
"""Exact failure probabilities (MW, ML) at bit-flip probability p."""
n = counts.shape[2] - 1
w = np.arange(n + 1)
P = counts @ (p ** w * (1 - p) ** (n - w)) # P[s, c]
wmin = min_weights(counts)
mw = np.where(wmin[:, 0] < wmin[:, 1], P[:, 1],
np.where(wmin[:, 1] < wmin[:, 0], P[:, 0], 0.5 * P.sum(axis=1)))
return float(mw.sum()), float(P.min(axis=1).sum())
codes = {}
for d in (3, 5):
n, rows, zl = z_checks_and_logical(d)
counts = enumerate_classes(n, rows, zl)
codes[d] = (rows, counts)
wmin = min_weights(counts)
ties = int(np.sum(wmin[:, 0] == wmin[:, 1]))
print(f"d = {d}: {2 ** n:,} errors, {2 ** len(rows):,} syndromes, "
f"{ties} with tied lightest classes")
for p in (0.01, 0.1):
mw, ml = exact_failure(counts, p)
print(f" p = {p:<4}: MW fails {mw:.6f}, ML fails {ml:.6f}")d = 3: 512 errors, 16 syndromes, 0 with tied lightest classes p = 0.01: MW fails 0.001731, ML fails 0.001731 p = 0.1 : MW fails 0.119695, ML fails 0.119695 d = 5: 33,554,432 errors, 4,096 syndromes, 0 with tied lightest classes p = 0.01: MW fails 0.000271, ML fails 0.000271 p = 0.1 : MW fails 0.124416, ML fails 0.123897
At
How big is ML’s advantage across noise strengths? The figure plots how many more failures MW makes than ML, in percent.
ps = np.geomspace(0.01, 0.2, 40)
fig, ax = plt.subplots()
for d, marker in ((3, "s"), (5, "o")):
excess = []
for p in ps:
mw, ml = exact_failure(codes[d][1], p)
excess.append(100 * (mw / ml - 1))
ax.plot(ps, excess, marker=marker, markevery=4, label=f"d = {d}")
ax.set_xscale("log")
ax.set_xlabel("bit-flip probability p")
ax.set_ylabel("extra failures of MW over ML (%)")
ax.legend()
plt.show()Exact excess failure probability of minimum-weight over maximum-likelihood decoding, 100 × (P_MW / P_ML − 1), for independent bit flips on the rotated surface code (code capacity). At d = 3 the two rules agree on every syndrome; at d = 5 ML's advantage grows with p, to about 1% at p = 0.15.
A syndrome where the rules disagree
Where does the gap come from? List the
rows5, counts5 = codes[5]
n5 = counts5.shape[2] - 1
w = np.arange(n5 + 1)
P = counts5 @ (0.1 ** w * 0.9 ** (n5 - w))
wmin5 = min_weights(counts5)
disagree = np.nonzero(np.argmax(P, axis=1) != np.argmin(wmin5, axis=1))[0]
print("syndromes where ML and MW disagree at p = 0.1:", len(disagree))
fired = [bin(s).count("1") for s in disagree]
s0 = int(disagree[int(np.argmin(fired))])
fired_checks = [rows5[k] for k in range(len(rows5)) if s0 >> k & 1]
print("example syndrome", s0, "fires checks", fired_checks)
for c in (0, 1):
nonzero = {int(k): int(v) for k, v in enumerate(counts5[s0, c]) if v}
lightest = dict(list(nonzero.items())[:4])
print(f"class {c}: number of errors by weight (lightest four)", lightest)syndromes where ML and MW disagree at p = 0.1: 181
example syndrome 137 fires checks [[0, 1, 5, 6], [3, 4], [12, 13, 17, 18]]
class 0: number of errors by weight (lightest four) {3: 1, 5: 28, 7: 151, 9: 534}
class 1: number of errors by weight (lightest four) {4: 12, 6: 68, 8: 278, 10: 801}
Class 0 holds one error of weight 3; class 1 has nothing lighter than weight 4, but twelve of
those. MW always picks class 0. ML compares the sums, and to leading order prefers class 1
once
def class_ratio(p):
"""P(class 1) / P(class 0) for the example syndrome."""
pw = p ** w * (1 - p) ** (n5 - w)
return float(counts5[s0, 1] @ pw / (counts5[s0, 0] @ pw))
lo, hi = 0.05, 0.15
for _ in range(50):
mid = 0.5 * (lo + hi)
lo, hi = (mid, hi) if class_ratio(mid) < 1 else (lo, mid)
p_switch = 0.5 * (lo + hi)
print(f"ML switches to class 1 at p = {p_switch:.4f} (leading order: {1 / 13:.4f})")ML switches to class 1 at p = 0.0935 (leading order: 0.0769)
pp = np.linspace(0.02, 0.15, 200)
fig, ax = plt.subplots()
ax.plot(pp, [class_ratio(p) for p in pp], label="exact, all weights")
ax.plot(pp, 12 * pp / (1 - pp), "--", label="leading order 12p/(1-p)")
ax.axhline(1, color="0.4", lw=0.8)
ax.axvline(p_switch, color="0.4", lw=0.8, ls=":")
ax.set_xlabel("bit-flip probability p")
ax.set_ylabel("P(class 1) / P(class 0)")
ax.legend()
plt.show()For the example d = 5 syndrome, the probability of class 1 (twelve weight-4 errors and more) relative to class 0 (one weight-3 error and more). MW always picks class 0. ML switches to class 1 where the solid curve crosses 1; the dashed line is the leading-order estimate 12p/(1 − p), which crosses at p = 1/13.
Why nobody runs this
The enumeration visits
errors, which is hopeless beyond . ML decoding of a general stabilizer code is #P-hard; for the surface code, tensor-network contraction approximates it well enough to serve as a reference decoder, but not in real time.
2. The decoding graph PyMatching uses
Circuit noise is a different world: errors happen on every gate, reset and measurement, and
the decoder sees detectors instead of checks. PyMatching works on a graph with one node
per detector, one boundary node, and one edge per group of error mechanisms that flip the
same pair of detectors (or one detector and the boundary). Each edge carries the merged
probability p_err and the weight
Build the three-round distance-3 memory of Lecture 0 and open the graph.
def build(d, p, rounds=None):
"""Noisy SI1000 Z-memory, plus PyMatching's decoder and the circuit it wants sampled."""
code = RotatedPlanarCode(width=d, height=d)
circ = css_code_memory_circuit(code, num_rounds=rounds or d, logical_basis=PauliBasis.Z)
qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=p))
noisy = qpu.compile_and_add_noise_to_circuit(circ)
return PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy)
dec, dcirc = build(3, 1e-3)
graph = dec.decoding_graph
print(type(graph).__name__, "with", len(graph.nodes), "nodes and",
len(graph.edges), "edges")
print("boundary node:", set(graph.boundaries))
print("detectors in the decoder's circuit:", dcirc.num_detectors)NXDecodingGraph with 17 nodes and 55 edges
boundary node: {16}
detectors in the decoder's circuit: 16
The detector coordinates
- space-like: two detectors in the same round, a data-qubit error between checks;
- time-like: the same check in consecutive rounds, a measurement error;
- space-time: different check and different round, an error in the middle of the check circuit (for example on an ancilla between two CNOTs);
- boundary: one detector and the boundary node.
coords = dcirc.get_detector_coordinates()
kinds = {}
for u, v in graph.edges:
weight = graph.graph.edges[(u, v)]["weight"]
if u in graph.boundaries or v in graph.boundaries:
kind = "boundary"
elif coords[u][:2] == coords[v][:2]:
kind = "time-like"
elif coords[u][2] == coords[v][2]:
kind = "space-like"
else:
kind = "space-time"
kinds.setdefault(kind, []).append(weight)
for kind, ws in kinds.items():
print(f"{kind:<11} {len(ws):>2} edges, weight {min(ws):.2f} to {max(ws):.2f}")boundary 16 edges, weight 4.41 to 6.03 space-like 12 edges, weight 5.09 to 6.06 time-like 12 edges, weight 4.80 to 4.85 space-time 15 edges, weight 7.05 to 7.54
fig, ax = plt.subplots(figsize=(6.4, 2.8))
order = ["time-like", "space-like", "boundary", "space-time"]
for i, kind in enumerate(order):
ax.plot(kinds[kind], [i] * len(kinds[kind]), "o", alpha=0.55)
ax.set_yticks(range(len(order)), order)
ax.set_ylim(-0.6, len(order) - 0.4)
ax.set_xlabel("edge weight ln((1 - p) / p)")
plt.show()Edge weights ln((1 − p)/p) of the decoding graph for the 3-round, d = 3 SI1000 memory at p = 10⁻³, one dot per edge, grouped by the kind of fault the edge stands for. Lower weight means a more likely edge. Time-like edges are uniformly cheap (4.80 to 4.85) because SI1000 flips measurements with probability 5p, though the lightest single edge is a boundary edge; diagonal space-time edges are the most expensive.
A decoder’s answer is a set of edges. decode_batch_to_full_correction returns one row per
shot with a 1 on every matched edge; the logical flip is the parity of the matched edges that
cross the logical (dec.logicals). Here is the first of 2,000 shots with three or more fired
detectors.
sampler = dcirc.compile_detector_sampler(seed=SEED)
dets, obs = sampler.sample(2000, separate_observables=True)
full = dec.decode_batch_to_full_correction(dets)
logical_edges = {tuple(sorted(e)) for e in dec.logicals[0]}
shot = next(s for s in range(len(dets)) if dets[s].sum() >= 3)
print("shot", shot, "fired detectors:", np.nonzero(dets[shot])[0].tolist())
for i in np.nonzero(full[shot])[0]:
u, v = graph.edges[i]
crosses = tuple(sorted((u, v))) in logical_edges
print(f" matched edge {(u, v)}: p_err = {graph.graph.edges[(u, v)]['p_err']:.4f}, "
f"crosses the logical: {crosses}")
print("predicted flip:", int(dec.decode_batch_to_logical_flip(dets[shot:shot + 1])[0, 0]),
"| actual flip:", int(obs[shot, 0]))shot 77 fired detectors: [4, 5, 9] matched edge (16, 4): p_err = 0.0084, crosses the logical: True matched edge (9, 5): p_err = 0.0078, crosses the logical: False predicted flip: 1 | actual flip: 1
Three fired detectors cannot pair up among themselves, so one of them is matched to the boundary, and that boundary edge crosses the logical. The decoder predicts a flip, and it happened: this shot is corrected.
3. A Union–Find decoder in plain Python
Union–Find (Delfosse and Nickerson) replaces the global matching with local cluster growth. The version below works on the same graph and the same samples as PyMatching:
grow: every cluster with an odd number of fired detectors (●) grows by one half-step on
each of its edges; an edge of length L is full after L half-steps (unit: L = 2)
○────○────●────○────○────●────○ two odd clusters, one per fired detector
○────○════●════○────○════●════○ after 2 half-steps the edges next to each ● are full
○────○════●════○════○════●════○ the middle edge fills from both sides: the clusters
merge, hold 2 fired detectors (even) and stop
peel: take a spanning tree of each cluster and walk it from the leaves inward; keep the
edge above every node that is still fired, and flip that edge's other end
correction = the three edges between the two ●A cluster that reaches the boundary node also stops growing: the boundary can absorb any
parity. Two variants: unit gives every edge length 2 (two half-steps), ignoring weights;
weighted gives an edge
class UnionFindDecoder:
"""Union-Find decoder (cluster growth with integer edge lengths, then peeling)."""
def __init__(self, decoder, weighted=True, scale=2.0):
g = decoder.decoding_graph
self.boundary = set(g.boundaries)
self.edges = [tuple(e) for e in g.edges]
self.adj = [[] for _ in range(max(g.nodes) + 1)]
for i, (u, v) in enumerate(self.edges):
self.adj[u].append((v, i))
self.adj[v].append((u, i))
w = np.array([g.graph.edges[e]["weight"] for e in self.edges])
self.length = (np.maximum(1, np.rint(scale * w)).astype(int) if weighted
else np.full(len(self.edges), 2))
index = {tuple(sorted(e)): i for i, e in enumerate(self.edges)}
self.logical = np.zeros(len(self.edges), dtype=np.uint8)
for e in decoder.logicals[0]:
self.logical[index[tuple(sorted(e))]] = 1
def decode(self, defects):
"""Return the list of edge indices in the correction for one shot."""
parent, members, parity, has_boundary = {}, {}, {}, {}
def find(x):
if x not in parent: # a new single-node cluster
parent[x], members[x], parity[x] = x, [x], 0
has_boundary[x] = x in self.boundary
return x
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root: # path compression
parent[x], x = root, parent[x]
return root
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return
if len(members[ra]) < len(members[rb]): # union by size
ra, rb = rb, ra
parent[rb] = ra
members[ra] += members.pop(rb)
parity[ra] ^= parity.pop(rb)
has_boundary[ra] |= has_boundary.pop(rb)
for v in defects:
parity[find(v)] = 1
growth, full = {}, set()
while True:
odd = [r for r in list(members) if parity[r] and not has_boundary[r]]
if not odd:
break
newly_full = []
for r in odd: # one half-step for every odd cluster
for v in members[r]:
for _, e in self.adj[v]:
if e in full:
continue
growth[e] = growth.get(e, 0) + 1
if growth[e] >= self.length[e]:
full.add(e)
newly_full.append(e)
for e in newly_full:
union(*self.edges[e])
# peeling: a BFS tree per cluster, rooted at the boundary if it holds it;
# walk it leaves first
tree_adj = {}
for e in full:
u, v = self.edges[e]
tree_adj.setdefault(u, []).append((v, e))
tree_adj.setdefault(v, []).append((u, e))
flipped, seen, correction = set(defects), set(), []
for start in [b for b in self.boundary if b in tree_adj] + sorted(tree_adj):
if start in seen:
continue
order, up_edge = [], {}
seen.add(start)
queue = deque([start])
while queue:
x = queue.popleft()
order.append(x)
for y, e in tree_adj[x]:
if y not in seen:
seen.add(y)
up_edge[y] = (x, e)
queue.append(y)
for x in reversed(order[1:]):
if x in flipped:
px, e = up_edge[x]
correction.append(e)
flipped.discard(x)
flipped.symmetric_difference_update({px})
return correction
def decode_batch_to_logical_flip(self, dets):
out = np.zeros((len(dets), 1), dtype=np.uint8)
for s in np.nonzero(dets.any(axis=1))[0]:
correction = self.decode(np.nonzero(dets[s])[0].tolist())
out[s, 0] = int(self.logical[correction].sum() % 2) if correction else 0
return out
uf = UnionFindDecoder(dec, weighted=True)
uf_edges = uf.decode(np.nonzero(dets[shot])[0].tolist())
print("shot", shot, "Union-Find correction:", [tuple(graph.edges[i]) for i in uf_edges])shot 77 Union-Find correction: [(16, 4), (9, 5)]
Now the race: three settings of SI1000 noise with rounds
settings = [(3, 1e-3, 100_000), (5, 2e-3, 50_000), (7, 2e-3, 20_000)]
results = []
print(f"{'setting':<22}{'shots':>8}{'matching':>10}{'UF unit':>9}{'UF weighted':>13}")
for d, p, shots in settings:
dec_d, dcirc_d = build(d, p)
dets_d, obs_d = dcirc_d.compile_detector_sampler(seed=SEED).sample(
shots, separate_observables=True)
row = [int(np.any(dec_d.decode_batch_to_logical_flip(dets_d) != obs_d, axis=1).sum())]
for weighted in (False, True):
uf_d = UnionFindDecoder(dec_d, weighted=weighted)
pred = uf_d.decode_batch_to_logical_flip(dets_d)
row.append(int(np.any(pred != obs_d, axis=1).sum()))
results.append(row)
print(f"{f'd = {d}, p = {p:g}':<22}{shots:>8}{row[0]:>10}{row[1]:>9}{row[2]:>13}")setting shots matching UF unit UF weighted d = 3, p = 0.001 100000 344 434 359 d = 5, p = 0.002 50000 388 656 433 d = 7, p = 0.002 20000 77 214 95
fig, ax = plt.subplots()
xs = np.arange(len(settings))
for k, (label, offset) in enumerate((("UF unit", -0.18), ("UF weighted", 0.18))):
ratio = [r[k + 1] / r[0] for r in results]
ax.bar(xs + offset, ratio, width=0.34, label=label)
ax.axhline(1, color="0.3", lw=1, label="matching")
ax.set_xticks(xs, [f"d = {d}\np = {p:g}" for d, p, _ in settings])
ax.set_ylabel("failures / matching failures")
ax.set_axisbelow(True)
ax.legend()
plt.show()Logical failures of Union–Find relative to minimum-weight matching on the same seeded samples (SI1000, rounds = d). Unit edge lengths ignore the weights and lose more as d grows; integer weights of round(2w) half-steps recover most of the gap.
Weights matter more as the code grows: at
4. The quick start: run_decoding_on_circuit
For a first look, Deltakit wraps sampling and decoding in one call. It has no seed and
prints a progress bar (silenced here), so we show only what it returns, not its numbers;
for reproducible counts use StimDecoderManager(..., seed=SEED) as in Notebook 6.
with contextlib.redirect_stderr(io.StringIO()): # hide the progress bar
result = run_decoding_on_circuit(dcirc, 20_000, dec)
print("keys:", sorted(result))
print("shots:", result["shots"])keys: ['fails', 'fails_log_0', 'shots'] shots: 20000
Try this
- Rerun section 1 at
and and compare the MW/ML gap at . Why does it shrink at low ? (Hint: count the fired checks of the syndromes in disagree.)- Decode
dets_dfrom thesetting with a PyMatchingDecoderbuilt at(wrong weights) and compare its failures with the correct one. - Try
scale=1.0andscale=4.0inUnionFindDecoder. Finer lengths approximate the weights better; how close to matching do they get?- Change
build(3, 1e-3)in section 2 torounds=1and count the time-like edges again.