Skip to main content
KetQat

Appearance

Lesson 114 h

Capstone: implement and benchmark a decoder

Build an error model, generate syndromes, decode, measure logical error rates and publish a reproducible report.

After this lesson you can

  • Construct and state a circuit-level error model for a memory experiment and check it for sanity with Stim
  • Generate seeded, platform-independent syndrome data from a detector error model
  • Implement a union-find decoder on a matching graph and verify it on every single fault before benchmarking it
  • Configure PyMatching as a baseline and compare decoders on identical samples with Wilson intervals and an exact paired test
  • Plan shot counts, report zero-failure points as upper bounds, and state only conclusions the data support
  • Produce a reproducible technical report and a deterministic, hash-verified JSON summary for a portfolio

Read first: Syndrome extraction with Stim, Minimum-weight perfect matching decoding, Logical error rates and thresholds, Resource estimation for fault-tolerant computers

The project

You will implement a decoder, benchmark it honestly against a strong baseline, and write it up so that someone else can reproduce every number. This is what decoder papers, internal evaluations and hiring portfolios in quantum error correction actually look like, and doing it well is mostly a matter of discipline: a stated model, paired data, intervals on every rate, and a report that separates what was measured from what was assumed.

Concretely, you will:

  1. Construct an error model. A Stim memory circuit (repetition code by default, rotated surface code as an extension) with a stated circuit-level noise model.
  2. Generate syndrome data with Stim. Via the circuit's detector error model, sampled with a seeded, platform-independent recipe.
  3. Implement and configure decoders. Your own union-find decoder (scaffold provided) and PyMatching as the baseline, plus the trivial decoder as a floor.
  4. Evaluate logical error probabilities with Wilson score intervals.
  5. Compare settings and algorithms across decoders, distances and noise strengths, using paired tests on identical samples.
  6. Write a reproducible technical report from the template in the exercise: model, method, parameters, seeds, environment versions, results with uncertainty, limitations.
  7. Export code and results to a portfolio: a deterministic JSON summary with parameters, seeds, package versions, per-point counts and rates, and the SHA-256 of the results. It is written to a local file; nothing is uploaded.

The exercise's automated checks cover the core of items 1–5 and 7. The report and the quality of the comparison are assessed with the published capstone rubric.

Step 1: an error model you can state in one paragraph

Decoder results are meaningless without the model that produced the syndromes. Three levels of model are common:

  • Code capacity: independent Pauli errors on data qubits, perfect syndrome measurement. Simple and useful for understanding a code, but it ignores measurement errors entirely.
  • Phenomenological: data errors plus independent flips of each syndrome bit in each round. It introduces the time dimension.
  • Circuit level: every gate, idle step, reset and measurement can fail. This captures hook errors and correlations, and it is what the default configuration uses.

Our circuit-level model applies, with one parameter pp, a two-qubit depolarizing channel after each CNOT, single-qubit depolarizing noise on data qubits before each round, and bit flips after resets and before measurements. In Stim's generated circuits these are the arguments after_clifford_depolarization, before_round_data_depolarization, after_reset_flip_probability and before_measure_flip_probability, all set to pp (Gidney, Stim). Note what pp is: a probability per operation, not per round and not a measured hardware figure.

The repetition code's syndrome extraction for d=3d=3 measures Z0Z1Z_{0}Z_{1} and Z1Z2Z_{1}Z_{2} with two ancillas, every round:

Quantum circuit on 5 wires (d0, a0, d1, a1, d2). step 1: CNOT, control d0, target a0. step 2: CNOT, control d1, target a0. step 3: CNOT, control d1, target a1. step 4: CNOT, control d2, target a1. step 5: measure a0. step 6: measure a1.d0a0d1a1d2
One round of repetition-code syndrome extraction for d = 3 (ancillas start in |0>)

Stim compares each ancilla outcome with the previous round's to form detectors, and the final data readout gives one more layer of detectors and the logical observable. A dd-round memory of the distance-dd repetition code has (d−1)(d+1)(d-1)(d+1) detectors. Before decoding anything, check the model: the detector count is what you expect, the noiseless circuit produces no detection events, all error probabilities in the detector error model lie in (0,0.5)(0, 0.5), and the detection-event rate grows with pp. The exercise automates these checks; your report should mention that you ran them.

Step 2: data you can regenerate anywhere

Stim converts the circuit into a detector error model (DEM): a list of independent mechanisms, each with a probability and the detectors and observables it flips. Sampling the DEM is equivalent to sampling the circuit for detection events and observable flips, and the exercise checks this statistically against Stim's own sampler.

Why not just use Stim's sampler? It is much faster, but its documentation is explicit that seeded results may differ between Stim versions and between machines with different SIMD instruction widths. For a benchmark whose numbers you want others to reproduce bit for bit, the exercise therefore samples the DEM with NumPy's PCG64 generator following an exact recipe: draw a uniform number per (shot, mechanism) and fire mechanism jj when it is below pjp_j. Each benchmark point gets its own seed, derived by hashing the base seed together with the code, distance, rounds and pp, so adding a point never changes the data of another.

All decoders at a point are evaluated on the same shots. This paired design removes sampling noise from the comparison: a difference between decoders cannot come from one of them having been handed easier syndromes.

Step 3: decoders

The trivial decoder: a floor

The trivial decoder always predicts "no logical flip". Its failure rate is the probability that the observable flipped at all. Any decoder worth reporting must beat it by a wide margin; the exercise requires your decoder to fail on at most half as many shots as the trivial decoder at d=5d=5, p=0.03p=0.03.

Union-find

The union-find decoder of Delfosse and Nickerson grows clusters around detection events until every cluster can be neutralised internally, then picks a correction inside the grown region by peeling a spanning forest (Delfosse and Nickerson). They prove it corrects every error of weight up to (d−1)/2(d-1)/2 in their setting, and its running time is almost linear in the number of qubits. The version you implement is the simplest: unweighted, with half-edge growth.

Worked example. Take a distance-5 repetition code with perfect measurements (code capacity): data qubits q0,…,q4q_0,\dots,q_4, detectors Di=ZiZi+1D_i = Z_iZ_{i+1} for i=0,…,3i=0,\dots,3, and one boundary node BB that stands for "beyond either end". The matching graph is a path B−D0−D1−D2−D3−BB - D_0 - D_1 - D_2 - D_3 - B, where the edge between Di−1D_{i-1} and DiD_i is qubit qiq_i, q0q_0 joins BB to D0D_0 and q4q_4 joins D3D_3 to BB. Let XX errors hit q1q_1 and q2q_2. Then D0D_0 fires (because of q1q_1), D1D_1 sees both and stays silent, and D2D_2 fires (because of q2q_2).

  • Round 1. The clusters {D0}\{D_0\} and {D2}\{D_2\} are odd. Each adds half an edge on both of its incident edges: q0,q1q_0, q_1 for D0D_0 and q2,q3q_2, q_3 for D2D_2. Nothing is fully grown yet.
  • Round 2. Both clusters are still odd and grow again. Now q0,q1,q2,q3q_0, q_1, q_2, q_3 are fully grown. Merging along them joins B,D0,D1,D2,D3B, D_0, D_1, D_2, D_3 into one cluster that contains the boundary, so growth stops.
  • Peeling. Root the spanning tree at BB: B−D0−D1−D2−D3B - D_0 - D_1 - D_2 - D_3 (edges q0q_0 to q3q_3). Leaf D3D_3 has no event: drop it. D2D_2 has an event: add its parent edge q2q_2 to the correction and toggle D1D_1, which now carries an event. D1D_1: add q1q_1 and toggle D0D_0, whose event is cancelled. D0D_0 is clear, so q0q_0 is not used.

The correction {q1,q2}\{q_1, q_2\} equals the error, so there is no logical failure. With circuit-level noise the graph comes from the DEM: nodes are detectors, edges are graphlike error mechanisms (Stim's decompose_errors=True splits the rest), and each edge carries a bit mask of the observables it flips. The decoder's output is the XOR of the masks along the correction.

The baseline: minimum-weight perfect matching

PyMatching, configured with Matching.from_detector_error_model(dem), finds a minimum-weight correction with edge weights ln⁡((1−pe)/pe)\ln((1-p_e)/p_e), using the sparse blossom algorithm (Higgott and Gidney). Matching-based decoding of the surface code goes back to Dennis, Kitaev, Landahl and Preskill (Dennis et al.). Because your union-find decoder ignores the edge weights, expect it to be somewhat worse at the same distance. How much worse, and whether the gap is resolved by your data, is the question your report answers.

Verify before you benchmark

A decoder that is wrong on simple inputs produces plausible-looking curves. Before any statistics, check that it corrects every single fault of the DEM (for a code of distance at least 3 this is required) and that the empty syndrome gives no flip. The exercise runs exactly this check for both your decoder and PyMatching, on the repetition code and on the d=3d=3 surface code.

Step 4: statistics you can defend

Intervals for every rate

With kk failures in nn shots, report p^=k/n\hat p = k/n together with a 95% Wilson score interval (Wilson),

p^+z22n±zp^(1−p^)n+z24n21+z2n,z=1.95996.\frac{\hat p + \frac{z^2}{2n} \pm z\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}}, \qquad z = 1.95996.

Brown, Cai and DasGupta compare binomial intervals and recommend the Wilson interval over the textbook normal ("Wald") interval, whose coverage is poor for small kk or extreme p^\hat p (Brown, Cai and DasGupta), which is exactly the regime of logical error rates.

Worked example. k=7k = 7, n=10,000n = 10{,}000, so p^=7×10−4\hat p = 7\times10^{-4} and z2=3.8415z^2 = 3.8415. The centre is (7×10−4+1.921×10−4)/1.000384=8.917×10−4(7\times10^{-4} + 1.921\times10^{-4})/1.000384 = 8.917\times10^{-4} and the half-width is 1.9592×6.995×10−8+9.60×10−9=5.526×10−41.9592\times\sqrt{6.995\times10^{-8} + 9.60\times10^{-9}} = 5.526\times10^{-4}, giving [3.39×10−4, 1.444×10−3][3.39\times10^{-4},\ 1.444\times10^{-3}]. The interval is not symmetric around p^\hat p, and it is wide: seven failures pin the rate down only to within a factor of about four.

With zero failures the interval is [0, z2/(n+z2)][0,\ z^2/(n+z^2)], about 3.84/n3.84/n. Report such a point as an upper bound, never as a rate of zero.

from scipy.stats import binomtest

for k, n in [(7, 10_000), (0, 10_000)]:
    ci = binomtest(k, n).proportion_ci(confidence_level=0.95, method="wilson")
    print(f"{k}/{n}: [{ci.low:.3e}, {ci.high:.3e}]")

This prints 7/10000: [3.391e-04, 1.444e-03] and 0/10000: [0.000e+00, 3.840e-04]. The exercise asks you to implement the formula and checks it against SciPy and, if installed, the KetQat SDK.

Paired comparisons

Because both decoders saw the same shots, the informative quantities are the discordant counts: shots where only decoder A failed (bb) and shots where only B failed (cc). Under the null hypothesis that the decoders are equally good, each discordant shot is equally likely to go either way, so the exact two-sided McNemar test uses b∼Binomial(b+c,1/2)b \sim \mathrm{Binomial}(b+c, 1/2).

The reference implementation on the default configuration illustrates this. At d=7d=7, p=0.02p=0.02, 20,000 shots and the seed derived from base seed 20261123, the union-find decoder failed 134 times and PyMatching 84 times; 75 shots failed only for union-find and 25 only for PyMatching, and the exact test gives p≈5.6×10−7p\approx 5.6\times10^{-7}. The gap is resolved. At d=7d=7, p=0.01p=0.01, union-find failed 12 times and PyMatching 11 times, with 5 and 4 discordant shots, and p=1p = 1: these data cannot distinguish the decoders at that point, and the report must say so rather than rank them. (These numbers come from the reference implementation; yours may differ slightly where implementations break ties differently, but the PyMatching and trivial counts are fixed by the seed.)

Planning shots

The relative standard error of p^\hat p is roughly 1/k1/\sqrt{k}. To know a rate to about ±20% (one standard error) you need about 25 failures; to ±10%, about 100. At pL≈10−3p_L\approx10^{-3} that means 10510^5 shots per point. Decide the shot counts (or a stopping rule such as "until 100 failures or 10610^6 shots") before looking at results, and report the rule. Choosing to stop when a comparison looks favourable biases it.

Step 5: comparisons that mean something

Comparisons are only meaningful between runs that share the code, distance, rounds, noise model and unit of rate. Within that constraint, useful questions include: how the ratio of union-find to PyMatching failure rates changes with pp and dd; whether union-find's rate still falls with distance at a given pp; and roughly where curves for different distances cross. Be careful with that last one. A crossing of two distances is not a threshold estimate; threshold claims need at least three distances, enough shots near the crossing and a finite-size analysis, as discussed in the earlier lesson on logical error rates and thresholds. Per-shot rates of experiments with different numbers of rounds are not comparable without converting to per-round rates.

Step 6: the report and the portfolio summary

The exercise README contains the report template. Its required sections are: summary; model; method; parameters; seeds and reproducibility; environment versions; results with uncertainty; comparison; limitations; conclusions; references. Two sections deserve emphasis. Seeds and reproducibility must give the exact commands that regenerate every number, and the results_sha256 of your exported JSON. Limitations must list what the study does not show: other noise models, larger distances, decoder speed (you have not measured it in a comparable way), and implementation simplifications such as unweighted growth.

export_portfolio writes the JSON summary with sorted keys, fixed separators and a trailing newline, so two runs with the same inputs produce byte-identical files. The hash covers the per-point results only (not the environment), so the same results on different machines produce the same hash, while the environment block records what produced them.

Common pitfalls

  • Benchmarking an unverified decoder. Always check single faults and simple syndromes first.
  • Unpaired comparisons. Evaluating decoders on different samples adds noise that hides or invents differences.
  • Rates without intervals, or zero reported as zero. Every rate needs an interval; zero failures give an upper bound.
  • Overlapping intervals read as "no difference". Overlap of two marginal intervals is a weak test; use the paired test on discordant shots.
  • Trusting seeds across machines. Stim's own seeded sampler is reproducible only with the same Stim version and the same SIMD width. Say which sampler you used.
  • Tuning on the test data. If you adjust your decoder after looking at results, regenerate the reported data with fresh seeds.
  • Mixing units. Per-shot rates of rr-round experiments are not per-round rates.
  • Overclaiming. No threshold from two distances, no hardware conclusions from a uniform depolarizing model, no speed claims without a fair timing study.

How the capstone is assessed

The automated checks in the exercise must pass. The report is then assessed with the published rubric on six criteria: correctness, statistical rigour, reproducibility, comparison quality, report clarity, and honesty about limitations. Passing the capstone is an educational record of work you completed in this course; it is not a professional certification or a verified skill claim. The code, results and report are yours. You decide whether and where to publish them, and KetQat does not publish or reuse them without your explicit permission.

Summary

  • A decoder benchmark is a model, data, decoders, statistics and a report, and each must be stated precisely enough to be reproduced.
  • Sample the detector error model with a portable seeded recipe; give each point its own derived seed; evaluate all decoders on the same shots.
  • Verify your decoder on every single fault before benchmarking it, and keep the trivial decoder as a floor and PyMatching as a baseline.
  • Report Wilson intervals, treat zero failures as upper bounds, compare decoders with an exact paired test, and plan shot counts in advance.
  • Publish a report with seeds, versions and limitations, and a hash-verified JSON summary that lets anyone check your numbers.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Capstone: implement and benchmark a quantum error decoder

advanced · about 8 h · needs numpy, scipy, stim, pymatching, pytest

This is the course's capstone project. You build a complete, reproducible decoder benchmark: an error model, syndrome data generated with Stim, a decoder you implement yourself (union-find), PyMatching as the baseline, logical error rates with Wilson intervals, paired comparisons, a technical report and a deterministic JSON summary you can link from a portfolio.

The automated checks below cover the core pieces. The report is assessed against the published capstone rubric, which also says what "pass" means: an educational record, not a certification. Your code, results and report belong to you; KetQat does not publish or reuse them without your permission.

Part 1: the pieces (starter.py)

Function Contract
build_memory_circuit(code, distance, rounds, p) "repetition" (repetition_code:memory) or "surface" (surface_code:rotated_memory_z) with the noise model in the module docstring.
dem_arrays(dem) Mechanism probabilities and sparse detector/observable incidence matrices, in the order of dem.flattened().
sample_dem(dem, shots, seed, chunk=4096) Platform-independent sampling with NumPy; follow the recipe in the docstring exactly.
dem_to_graph(dem) Matching graph of a decomposed DEM: edges (u, v, obs_mask, prob), boundary node num_detectors.
union_find_decode(graph, syndrome) Your decoder. Unweighted union-find with half-edge growth and peeling, returning an observable bit mask. The private _DisjointSet scaffold handles the cluster bookkeeping.
decode(decoder, dem, graph, dets) "trivial" (never predicts a flip), "union_find" (yours, once per distinct syndrome) or "pymatching" (Matching.from_detector_error_model).
wilson_interval(failures, shots, z=Z95) 95% Wilson score interval.
paired_comparison(fail_a, fail_b) Discordant counts and the exact two-sided McNemar p-value.
point_seed(base_seed, code, distance, rounds, p) A per-point seed derived with SHA-256, so points are independent and reproducible.
run_benchmark(config) Every decoder on the same samples at every point; counts, rates, intervals and paired comparisons against the baseline.
export_portfolio(results, path) Writes a deterministic JSON summary (parameters, seeds, package versions, per-point counts and rates, and the SHA-256 of the results) to a local file. Nothing is uploaded.

Hints for the union-find decoder

Union-find decoding was introduced by Delfosse and Nickerson (Quantum 5, 595 (2021), arXiv:1709.06218). The version you implement is the simplest one:

  1. Each detection event is a cluster of odd parity. Clusters that contain the boundary node are never odd (the boundary can absorb one event).
  2. Growth. Every odd cluster adds half an edge to each edge incident to its nodes. An edge with two halves is fully grown; merge the clusters at its ends. Grow all odd clusters in a round before merging, then repeat until no odd cluster remains.
  3. Peeling. Take the fully grown edges, build a spanning forest (start from the boundary node if it is in the forest), and process nodes from the leaves inward: if a leaf carries a detection event, put its parent edge in the correction and toggle the event on the parent.
  4. Return the XOR of the observable masks of the correction edges.

Debugging tips: start with a single fault (one edge's syndrome); then two faults far apart; then a fault next to the boundary. decode should call your function once per distinct syndrome (numpy.unique(..., axis=0, return_inverse=True)): at low pp most shots repeat a handful of syndromes, which makes a pure-Python decoder fast enough.

What the checks verify

python -m pytest test_exercise.py (a few seconds):

  1. Error model sanity: detector counts ((d−1)(r+1)(d-1)(r+1) for the repetition code, (d2−1)r(d^2-1)r for the surface-code Z memory), probabilities in (0,0.5)(0, 0.5), silence without noise, and more detection events at higher pp.
  2. Sampler: follows the NumPy recipe exactly and agrees statistically with Stim's own circuit sampler (5 standard errors per detector).
  3. Decoder correctness on known syndromes: for the d=5d=5 repetition code and the d=3d=3 surface code, both your decoder and PyMatching must correct every single fault in the detector error model, and the empty syndrome gives no flip.
  4. Stated performance bound: on 4,000 shots (seed 2026) of the d=5d=5, 5-round repetition code at p=0.03p=0.03, your decoder fails on at most half as many shots as the trivial decoder.
  5. Estimator and intervals: Wilson intervals match SciPy's (and the KetQat SDK's, when installed); the McNemar p-value matches SciPy's exact binomial test.
  6. Benchmark: seeded runs reproduce exactly, seeds follow point_seed, and the paired counts are consistent with the failure counts.
  7. Deterministic export: two exports are byte-identical, results_sha256 matches an independent re-hash of the points, versions are recorded, and changing a single count changes the hash.

Passing the checks is necessary, not sufficient: the rubric also assesses your comparison and your report.

Part 2: the study

Run at least:

import starter as bench   # your implementation
results = bench.run_benchmark(bench.DEFAULT_CONFIG)       # repetition code, d = 3, 5, 7
bench.export_portfolio(results, "runs/decoder-benchmark.json")

(Create runs/ first.) The default configuration takes a few seconds with a correct implementation. Then extend the study in at least one direction and justify your choice before you look at the results: the surface code at d∈{3,5}d\in\{3,5\}, more noise strengths, more shots where intervals overlap, a different number of rounds, or a second decoder of your own (for example a weighted union-find, or a greedy matcher). Keep DEFAULT_CONFIG results in your report: the quiz asks for one of its numbers, which is decoder independent because it comes from your sampler and PyMatching.

Part 3: the report

Write a technical report of 1,500–3,000 words (figures and tables excluded) using the template below. Save it as report_template.md and fill it in, or copy the headings into your own document; every section is required.

# <Title: what you benchmarked>

Author: <name or handle>. This report and the code it describes are my own work.
<State any help, code or text you reused, with its source.>

## 1. Summary
Question, model, decoders, main result with its uncertainty, main limitation.

## 2. Model
Code family and basis; distances and rounds; the exact noise model (Stim
arguments and the meaning of p); what counts as a logical failure; the unit of
every rate (per shot of r rounds or per round, with the conversion).

## 3. Method
Sampling route and why; each decoder and its configuration (graph, weights,
parallel edges, simplifications) with citations; the paired design; interval
method, paired test and any stopping rule fixed in advance.

## 4. Parameters
Table: code, distance, rounds, p, shots, decoders.

## 5. Seeds and reproducibility
Base seed and the per-point seed rule; the exact command(s) that regenerate every
number and figure; the results_sha256 of the exported JSON and where it lives.

## 6. Environment
Python, NumPy, SciPy, Stim and PyMatching versions (from the export), OS and CPU.

## 7. Results with uncertainty
Table of failures/shots, rate and 95% Wilson interval for every point and decoder;
zero-failure points as upper bounds; a log-scale figure of rate against p per
distance and decoder, with interval bars and captions stating model and shots.

## 8. Comparison
Which differences the data resolve (paired test, intervals) and which not; ratios
with uncertainty; what the comparison does not show.

## 9. Limitations
Model, statistics, implementation, and what you would do next.

## 10. Conclusions
Only what the evidence supports. No threshold claim from two distances, no silent
extrapolation, no claims about hardware.

## 11. References
Every paper and library used, with DOI or arXiv id.

Part 4: the portfolio summary

export_portfolio writes one JSON file with sorted keys and a trailing newline. Its results_sha256 lets a reader verify that the numbers in your report are the ones in the file. Link the JSON, your code and your report from wherever you keep your portfolio; nothing in this exercise uploads anything.

Reproducibility notes

  • The NumPy sampler is designed to be platform independent with the pinned versions (Stim 1.16.0, PyMatching 2.4.0, NumPy 2.5.5). Stim's built-in sampler is faster, but its documentation warns that seeded results can differ across Stim versions and across machines with different SIMD widths. If you use it, say so and record the machine.
  • Do not tune decoder choices on the same shots you report. Fix the configuration, then generate the reported data with new seeds.
Terminal
python -m pip install numpy scipy stim pymatching pytest

starter.py

Python
"""Capstone starter: implement and benchmark a quantum error decoder.

Pipeline: error model (Stim circuit) -> detector error model -> seeded samples ->
decoders (trivial, your union-find, PyMatching) -> logical error rates with Wilson
intervals and paired comparisons -> a deterministic JSON summary for a portfolio.

Noise model (uniform circuit-level depolarizing, parameter p): Stim's generated
memory circuits with after_clifford_depolarization = p,
before_round_data_depolarization = p, before_measure_flip_probability = p and
after_reset_flip_probability = p.

Implement every public function (they raise NotImplementedError). The private
helper _DisjointSet below is a scaffold you may use for union_find_decode, or
replace with your own. Run the checks with `python -m pytest test_exercise.py`.
This code is yours: you may publish it in your portfolio.
"""

from __future__ import annotations

import hashlib
import json
import platform
from pathlib import Path

import numpy as np
import pymatching
import scipy
import scipy.sparse as sp
import stim
from scipy.stats import binom

Z95 = 1.959963984540054
SCHEMA = "ketqat-academy.decoder-benchmark/v1"
NOISE_MODEL = (
    "uniform circuit-level depolarizing: after_clifford_depolarization=p, "
    "before_round_data_depolarization=p, before_measure_flip_probability=p, after_reset_flip_probability=p"
)
CODES = {"repetition": "repetition_code:memory", "surface": "surface_code:rotated_memory_z"}
DEFAULT_CONFIG = {
    "code": "repetition",
    "distances": [3, 5, 7],
    "error_rates": [0.01, 0.02, 0.03],
    "rounds": None,
    "shots": 20000,
    "seed": 20261123,
    "decoders": ["trivial", "union_find", "pymatching"],
    "baseline": "pymatching",
}


# ---------------------------------------------------------------- error model


def build_memory_circuit(code: str, distance: int, rounds: int, p: float) -> stim.Circuit:
    """Memory experiment for code "repetition" (repetition_code:memory) or "surface"
    (surface_code:rotated_memory_z) with the module's noise model."""
    raise NotImplementedError


def dem_arrays(dem: stim.DetectorErrorModel):
    """(probabilities, detector matrix (num_detectors x m), observable matrix
    (num_observables x m)) for the m `error` instructions of dem.flattened(), in order.
    Separators are ignored: a mechanism flips the XOR of its components."""
    raise NotImplementedError


def sample_dem(dem: stim.DetectorErrorModel, shots: int, seed: int, chunk: int = 4096):
    """Platform-independent samples (detection events, observable flips), both bool.

    Recipe: rng = numpy.random.default_rng(seed); in row blocks of at most `chunk`
    shots draw u = rng.random((rows, m)); mechanism j fires iff u[shot, j] < p_j."""
    raise NotImplementedError


# ---------------------------------------------------------------- decoders


class _DisjointSet:
    """Scaffold: union-find over cluster roots with the bookkeeping a UF decoder needs.

    parity[r]   number of detection events in the cluster of root r, mod 2
    boundary[r] whether the cluster contains the boundary node
    members[r]  the nodes of the cluster (only valid at roots)
    """

    def __init__(self, n: int, events, boundary_node: int):
        self.parent = list(range(n))
        self.size = [1] * n
        self.parity = [int(bool(e)) for e in events]
        self.boundary = [i == boundary_node for i in range(n)]
        self.members = [[i] for i in range(n)]

    def find(self, a: int) -> int:
        while self.parent[a] != a:
            self.parent[a] = self.parent[self.parent[a]]  # path halving
            a = self.parent[a]
        return a

    def union(self, a: int, b: int) -> int:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return ra
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        self.parity[ra] ^= self.parity[rb]
        self.boundary[ra] = self.boundary[ra] or self.boundary[rb]
        self.members[ra].extend(self.members[rb])
        self.members[rb] = []
        return ra

    def is_odd(self, root: int) -> bool:
        """A cluster still grows when it has odd parity and does not touch the boundary."""
        return bool(self.parity[root]) and not self.boundary[root]


def dem_to_graph(dem: stim.DetectorErrorModel) -> dict:
    """Matching graph of a graphlike (decomposed) detector error model.

    Every component (between ^ separators) of every error must flip one or two
    detectors. A one-detector component becomes an edge to the boundary node, whose
    index is num_detectors. Parallel edges keep the most probable one. Returns
    {"num_detectors", "boundary", "num_observables", "edges": [(u, v, obs_mask, prob)]}
    with u < v, sorted."""
    raise NotImplementedError


def union_find_decode(graph: dict, syndrome) -> int:
    """Unweighted union-find decoder (Delfosse-Nickerson) on a matching graph.

    1. Each detection event starts an odd cluster. A cluster containing the boundary
       node is never odd.
    2. While an odd cluster exists: every odd cluster adds half an edge to each edge
       incident to its nodes; edges that reach two halves become fully grown, and the
       clusters at their ends are merged (union by size, path compression).
    3. Peeling: build a spanning forest of the grown edges (boundary node first as a
       root), then walk each tree from the leaves inward; a leaf carrying a detection
       event puts its parent edge in the correction and passes the event to its parent.
    Returns the XOR of the observable masks of the correction edges."""
    raise NotImplementedError


def decode(decoder: str, dem: stim.DetectorErrorModel, graph: dict, dets) -> np.ndarray:
    """Predicted observable flips, shape (shots, num_observables), bool.

    "trivial" always predicts no flip; "union_find" applies union_find_decode once per
    distinct syndrome; "pymatching" uses pymatching.Matching.from_detector_error_model."""
    raise NotImplementedError


# ---------------------------------------------------------------- statistics


def wilson_interval(failures: int, shots: int, z: float = Z95):
    """Wilson score interval (lower, upper) for a binomial proportion."""
    raise NotImplementedError


def paired_comparison(fail_a, fail_b) -> dict:
    """Paired comparison of two decoders on the same shots (boolean failure vectors).

    Returns {"only_a", "only_b", "both", "neither", "p_value"}, where p_value is the
    exact two-sided McNemar test: 2 * P[Binomial(only_a + only_b, 1/2) <= min], capped
    at 1 (and 1 when there are no discordant shots)."""
    raise NotImplementedError


# ---------------------------------------------------------------- benchmark


def point_seed(base_seed: int, code: str, distance: int, rounds: int, p: float) -> int:
    """Seed of one benchmark point: the first 16 hex digits of
    sha256(f"{base_seed}|{code}|{distance}|{rounds}|{p!r}") as an integer, mod 2**63."""
    raise NotImplementedError


def run_benchmark(config: dict) -> dict:
    """Run every (distance, p) point of config with every decoder on the same samples.

    Returns {"schema", "config", "noise_model", "points": [...]} where each point is
    {"code", "distance", "rounds", "p", "shots", "seed", "decoder", "failures", "rate",
    "ci_low", "ci_high", "vs_baseline"}; vs_baseline is paired_comparison(this decoder,
    baseline) for non-baseline decoders and None for the baseline. Points are ordered
    by distance, then p, then the order of config["decoders"]."""
    raise NotImplementedError


def _canonical(obj) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True)


def export_portfolio(results: dict, path) -> str:
    """Write a deterministic JSON summary to `path` (a local file; nothing is uploaded).

    Document keys: schema, parameters (the config), noise_model, seeds (the per-point
    seeds, deduplicated in point order), environment (python, numpy, scipy, stim,
    pymatching versions), points, results_sha256 = sha256 of the canonical JSON of the
    points (sort_keys, separators (",", ":"), ASCII). The file is
    json.dumps(document, sort_keys=True, indent=2) plus a newline. Returns results_sha256."""
    raise NotImplementedError

test_exercise.py

Python
"""Automated checks for the decoder-benchmark capstone.

These cover the core pieces only; the report is assessed against the published
rubric. Independent references: Stim's own sampler and detector counts, every
single fault of the detector error model (an exact decoding requirement for a
distance >= 3 code), the trivial decoder as a performance floor, SciPy's Wilson
interval and exact binomial test, the KetQat SDK's Wilson interval (if
installed), and an independent re-hash of the exported file.
"""

import hashlib
import importlib.util
import json
import os
from pathlib import Path

import numpy as np
import pymatching
import pytest
import stim
from scipy.stats import binomtest


def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


target = _load_target()

SMALL = {"code": "repetition", "distances": [3, 5], "error_rates": [0.02], "rounds": None,
         "shots": 2000, "seed": 99, "decoders": ["trivial", "union_find", "pymatching"],
         "baseline": "pymatching"}


def _dem(code, d, p, rounds=None):
    return target.build_memory_circuit(code, d, rounds or d, p).detector_error_model(decompose_errors=True)


# ------------------------------------------------------------------ error model


@pytest.mark.parametrize("code,d,rounds,expected", [("repetition", 3, 3, 8), ("repetition", 5, 2, 12), ("surface", 3, 3, 24)])
def test_error_model_shape(code, d, rounds, expected):
    c = target.build_memory_circuit(code, d, rounds, 0.01)
    assert c.num_detectors == expected and c.num_observables == 1
    probs, H, L = target.dem_arrays(c.detector_error_model(decompose_errors=True))
    assert np.all((probs > 0) & (probs < 0.5))
    assert H.shape[0] == expected and L.shape[0] == 1


def test_error_model_is_silent_without_noise_and_grows_with_p():
    clean = target.build_memory_circuit("repetition", 5, 5, 0.0)
    assert not clean.compile_detector_sampler(seed=1).sample(200).any()
    assert not any(inst.type == "error" for inst in clean.detector_error_model().flattened())
    low = target.sample_dem(_dem("repetition", 5, 0.01), 4000, seed=3)[0].mean()
    high = target.sample_dem(_dem("repetition", 5, 0.03), 4000, seed=3)[0].mean()
    assert high > low > 0


def test_sampler_recipe_and_agreement_with_stim():
    dem = _dem("repetition", 5, 0.02)
    probs, H, L = target.dem_arrays(dem)
    d1, o1 = target.sample_dem(dem, 3000, seed=4, chunk=512)
    u = np.random.default_rng(4).random((3000, len(probs)))
    fired = (u < probs).astype(np.int64)
    assert np.array_equal(d1, (fired @ H.T.toarray().astype(np.int64)) % 2 == 1)
    assert np.array_equal(o1, (fired @ L.T.toarray().astype(np.int64)) % 2 == 1)
    circuit = target.build_memory_circuit("repetition", 5, 5, 0.02)
    shots = 30000
    mine = target.sample_dem(dem, shots, seed=5)[0].mean(axis=0)
    theirs = circuit.compile_detector_sampler(seed=6).sample(shots).mean(axis=0)
    se = np.sqrt((mine * (1 - mine) + theirs * (1 - theirs)) / shots)
    assert np.all(np.abs(mine - theirs) < 5 * se + 1e-9)


# ------------------------------------------------------------------ decoders


@pytest.mark.parametrize("code,d", [("repetition", 5), ("surface", 3)])
def test_graph_and_single_fault_decoding(code, d):
    dem = _dem(code, d, 0.01)
    graph = target.dem_to_graph(dem)
    assert graph["boundary"] == dem.num_detectors
    for u, v, mask, prob in graph["edges"]:
        assert 0 <= u < v <= graph["boundary"] and 0 < prob < 0.5 and mask in (0, 1)
    probs, H, L = target.dem_arrays(dem)
    Hd, Ld = H.toarray().astype(bool), L.toarray().astype(bool)
    assert target.union_find_decode(graph, np.zeros(dem.num_detectors, bool)) == 0
    syndromes = Hd.T  # one row per single fault
    expected = Ld.T
    for name in ("union_find", "pymatching"):
        pred = target.decode(name, dem, graph, syndromes)
        assert pred.shape == expected.shape
        assert np.array_equal(pred, expected), f"{name} must correct every single fault of a d={d} code"
    assert not target.decode("trivial", dem, graph, syndromes).any()


def test_union_find_beats_the_trivial_decoder():
    """Stated bound: on 4000 seeded shots of the d=5, 5-round repetition code at
    p=0.03, your decoder fails on at most half as many shots as the trivial decoder."""
    dem = _dem("repetition", 5, 0.03)
    graph = target.dem_to_graph(dem)
    dets, obs = target.sample_dem(dem, 4000, seed=2026)
    fail_uf = np.any(target.decode("union_find", dem, graph, dets) != obs, axis=1).sum()
    fail_trivial = np.any(obs, axis=1).sum()
    assert fail_uf <= 0.5 * fail_trivial
    matcher = pymatching.Matching.from_detector_error_model(dem)
    assert np.array_equal(target.decode("pymatching", dem, graph, dets), matcher.decode_batch(dets).astype(bool))


# ------------------------------------------------------------------ statistics


@pytest.mark.parametrize("k,n", [(0, 100), (1, 10), (7, 1000), (500, 1000), (1000, 1000), (3, 20000)])
def test_wilson_interval_matches_scipy(k, n):
    lo, hi = target.wilson_interval(k, n)
    ref = binomtest(k, n).proportion_ci(confidence_level=0.95, method="wilson")
    assert lo == pytest.approx(ref.low, abs=1e-12) and hi == pytest.approx(ref.high, abs=1e-12)
    assert lo <= k / n <= hi


def test_wilson_interval_matches_ketqat_sdk():
    stats = pytest.importorskip("ketqat_runner.qec_statistics")
    for k, n in ((0, 50), (12, 400), (399, 400)):
        assert target.wilson_interval(k, n) == pytest.approx(stats.wilson_interval(k, n), abs=1e-12)


def test_paired_comparison():
    rng = np.random.default_rng(1)
    a = rng.random(5000) < 0.05
    b = a.copy()
    flip = rng.random(5000) < 0.02
    b[flip] = ~b[flip]
    res = target.paired_comparison(a, b)
    assert res["only_a"] + res["only_b"] + res["both"] + res["neither"] == 5000
    assert res["only_a"] == int(np.sum(a & ~b)) and res["both"] == int(np.sum(a & b))
    n = res["only_a"] + res["only_b"]
    ref = binomtest(res["only_a"], n, 0.5).pvalue
    assert res["p_value"] == pytest.approx(ref, rel=1e-9)
    assert target.paired_comparison(a, a)["p_value"] == 1.0


# ------------------------------------------------------------------ benchmark and export


def test_benchmark_is_seeded_and_paired():
    r1 = target.run_benchmark(SMALL)
    r2 = target.run_benchmark(dict(SMALL))
    assert r1["points"] == r2["points"]
    assert len(r1["points"]) == 2 * 1 * 3
    for pt in r1["points"]:
        assert pt["seed"] == target.point_seed(99, "repetition", pt["distance"], pt["rounds"], pt["p"])
        assert pt["rate"] == pt["failures"] / pt["shots"]
        assert (pt["ci_low"], pt["ci_high"]) == target.wilson_interval(pt["failures"], pt["shots"])
        if pt["decoder"] == "pymatching":
            assert pt["vs_baseline"] is None
        else:
            vs = pt["vs_baseline"]
            assert vs["only_a"] + vs["both"] == pt["failures"]
    assert target.point_seed(1, "repetition", 3, 3, 0.01) != target.point_seed(1, "repetition", 3, 3, 0.02)
    assert target.point_seed(1, "repetition", 3, 3, 0.01) == target.point_seed(1, "repetition", 3, 3, 0.01)


def test_export_is_deterministic_and_hashed(tmp_path):
    results = target.run_benchmark(SMALL)
    h1 = target.export_portfolio(results, tmp_path / "a.json")
    h2 = target.export_portfolio(results, tmp_path / "b.json")
    raw_a = (tmp_path / "a.json").read_bytes()
    assert raw_a == (tmp_path / "b.json").read_bytes() and h1 == h2
    doc = json.loads(raw_a)
    for key in ("schema", "parameters", "noise_model", "seeds", "environment", "points", "results_sha256"):
        assert key in doc
    canonical = json.dumps(doc["points"], sort_keys=True, separators=(",", ":"), ensure_ascii=True)
    assert doc["results_sha256"] == hashlib.sha256(canonical.encode("ascii")).hexdigest() == h1
    assert doc["environment"]["stim"] == stim.__version__
    assert doc["environment"]["pymatching"] == pymatching.__version__
    assert doc["environment"]["numpy"] == np.__version__
    assert sorted(doc["seeds"]) == sorted({pt["seed"] for pt in results["points"]})
    tampered = json.loads(json.dumps(results))
    tampered["points"][0]["failures"] += 1
    assert target.export_portfolio(tampered, tmp_path / "c.json") != h1
    assert sorted(p.name for p in tmp_path.iterdir()) == ["a.json", "b.json", "c.json"]

Check your understanding

7 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. Run run_benchmark(DEFAULT_CONFIG) with your implementation (repetition code, rounds = d, 20,000 shots per point, base seed 20261123, NumPy DEM sampling as specified). How many shots did PyMatching fail on at d=5d = 5, p=0.03p = 0.03?

    2 pts

    Computed by running exercise “decoder-benchmark” on your computer.

  2. A decoder shows zero logical failures in 20,000 shots. What is the upper end of the 95% Wilson interval (z=1.95996z = 1.95996)? Enter it in units of 10−410^{-4}.

    1 pt
  3. On identical shots, decoder A fails on 10 shots where B succeeds, and B fails on 2 shots where A succeeds (other shots agree). What is the exact two-sided McNemar p-value?

    1 pt
  4. Why does the benchmark evaluate every decoder on the same sampled shots?

    1 pt
  5. Before benchmarking your union-find decoder on a distance-5 code, which check is the most informative first test?

    1 pt
  6. Which practices make your benchmark reproducible by someone on a different machine? Select all that apply.

    1 pt

    Select all that apply.

  7. What does passing the capstone represent?

    1 pt

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Nicolas Delfosse, Naomi H. Nickerson (2021). Almost-linear time decoding algorithm for topological codes. Quantum 5, 595. doi:10.22331/q-2021-12-02-595
  2. Oscar Higgott, Craig Gidney (2025). Sparse Blossom: correcting a million errors per core second with minimum-weight matching. Quantum 9, 1600. doi:10.22331/q-2025-01-20-1600
  3. Craig Gidney (2021). Stim: a fast stabilizer circuit simulator. Quantum 5, 497. doi:10.22331/q-2021-07-06-497
  4. Eric Dennis et al. (2002). Topological quantum memory. Journal of Mathematical Physics 43, 4452-4505. doi:10.1063/1.1499754
  5. Edwin B. Wilson (1927). Probable Inference, the Law of Succession, and Statistical Inference. Journal of the American Statistical Association 22(158), 209-212. doi:10.1080/01621459.1927.10502953
  6. Lawrence D. Brown, T. Tony Cai, Anirban DasGupta (2001). Interval Estimation for a Binomial Proportion. Statistical Science 16(2), 101-133. doi:10.1214/ss/1009213286