Skip to main content
KetQat

Appearance

Lesson 61 h 20 min

Minimum-weight perfect matching decoding

Matching graphs, MWPM decoding with PyMatching and decoder performance.

After this lesson you can

  • Derive edge weights ln((1-q)/q) and show that a minimum-weight edge set is a most likely error for independent mechanisms
  • Build a matching graph with a boundary node from a Stim detector error model
  • Reduce decoding to minimum-weight perfect matching on fired detectors with boundary twins, and implement it with NetworkX
  • Decode sampled shots with PyMatching, count logical failures and compare decoders on identical samples
  • Explain what MWPM ignores (correlations between X and Z, degeneracy, hyperedges) and when that matters
  • Reproduce the KetQat SDK surface-code-memory product exactly from its seed derivation

Read first: Syndrome extraction with Stim

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 XX and ZZ 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 ee, each occurring with probability qeq_e 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 EE produces the detection events ∂E\partial E: a detector fires when an odd number of chosen edges touch it. (The boundary node absorbs any parity.) Its probability is

Pr⁡[E]=∏e∈Eqe∏e∉E(1−qe)=(∏e(1−qe))∏e∈Eqe1−qe,\Pr[E] = \prod_{e \in E} q_e \prod_{e \notin E}(1-q_e) = \Bigl(\prod_{e}(1-q_e)\Bigr)\prod_{e\in E}\frac{q_e}{1-q_e},

so

−ln⁡Pr⁡[E]=const+∑e∈Ewe,we=ln⁡1−qeqe.-\ln \Pr[E] = \text{const} + \sum_{e \in E} w_e, \qquad w_e = \ln\frac{1-q_e}{q_e}.

Maximising the probability of the error is minimising the total weight. For qe<1/2q_e < 1/2 every weight is positive, and rarer mechanisms are heavier. Two mechanisms with identical effects are merged before this step, combining as independent events: q=q1(1−q2)+q2(1−q1)q = q_1(1-q_2) + q_2(1-q_1).

Worked example. Take the 5-qubit bit-flip code under code-capacity noise with flip probability p=0.05p = 0.05 and syndrome (1,0,0,1)(1, 0, 0, 1): 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 w=ln⁡(0.95/0.05)=ln⁡19≈2.944w = \ln(0.95/0.05) = \ln 19 \approx 2.944. Two explanations exist: connect check 0 to check 3 (data qubits 1, 2, 3; weight 3w≈8.833w \approx 8.83), or connect each fired check to its nearest boundary (data qubits 0 and 4; weight 2w≈5.892w \approx 5.89). Matching chooses the second, X0X4X_0X_4, exactly the minimum-weight correction of the repetition-code lesson. Its probability ratio to the alternative is e3w−2w=19e^{3w - 2w} = 19.

From graph to matching

The minimum-weight EE with ∂E\partial E equal to the observed detection events can be found in two steps.

  1. Shortest paths. For every pair of fired detectors u,vu, v compute the shortest-path distance D(u,v)D(u, v) in the graph, and for every fired detector its distance D(u,boundary)D(u, \text{boundary}) to the boundary node.
  2. Matching. Build a complete graph on the fired detectors, plus one boundary twin bub_u for each fired uu. Give edge uu–vv weight D(u,v)D(u,v), edge uu–bub_u weight D(u,boundary)D(u, \text{boundary}), 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 ZZ-memory experiment the detectors are built from ZZ-check outcomes, and an XX error on a data qubit in the bulk flips exactly two ZZ checks (two detectors in the same round), or one if it sits next to a boundary that carries only ZZ 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. ZZ errors are invisible to a ZZ memory's detectors and are handled by the XX-type detectors of an XX memory, independently.

A space-time example

Return to the hand-written distance-3, two-round repetition memory of the Stim lesson (uniform noise, p=0.01p = 0.01). 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 qq Weight ln⁡1−qq\ln\frac{1-q}{q} 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 X0X_0, 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 XX and ZZ. A YY error is an XX and a ZZ error on the same qubit. Under depolarizing noise XX and ZZ 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, p=0.03p = 0.03, 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 [0.00425,0.00624][0.00425, 0.00624]), for depolarizing noise after every Clifford gate only, d=3d = 3, 3 rounds, p=0.005p = 0.005. 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:

  1. matching_graph(dem): nodes, boundary, merged parallel edges, weights, observable flags; checked edge by edge against PyMatching's own graph.
  2. 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.
  3. 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 ln⁡1−qq\ln\frac{1-q}{q}; 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 qeq_e give edge weights ln⁡1−qeqe\ln\frac{1-q_e}{q_e}; 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 XX–ZZ 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.

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.

Writing a matching decoder and checking it against PyMatching

advanced · about 2 h 30 min · needs numpy, stim, pymatching, networkx, pytest, ketqat[qec]

You will implement minimum-weight perfect matching (MWPM) decoding from scratch: turn a Stim detector error model into a weighted matching graph, solve each shot's matching problem exactly with NetworkX, and translate the matching into a prediction of the logical observable. You then check, shot by shot, that your decoder finds matchings of the same weight as PyMatching, and that a full Stim + PyMatching pipeline reproduces the KetQat SDK's surface-code-memory product exactly.

Functions to implement in starter.py

Function Contract
repetition_memory(d, rounds, p) Provided: Stim's repetition-code memory with all four noise arguments equal to pp.
sample_shots(circuit, shots, seed) Measurements, detection events and observable flips of the same shots (sample measurements, then convert with compile_m2d_converter).
matching_graph(dem) NetworkX graph on the detectors plus a BOUNDARY node; edge attributes probability, observables (frozenset) and weight =ln⁡1−qq=\ln\frac{1-q}{q}; merge parallel edges as independent mechanisms; ValueError for components with more than two detectors.
mwpm_decode(graph, events, num_observables) Exact MWPM per shot with boundary twins; returns predictions and the total matching weight per shot.
pymatching_decode(dem, events) PyMatching predictions and weights (return_weights=True).
count_failures(predictions, flips) Shots with any wrong observable.
majority_vote_failures(measurements, d) Baseline that ignores the syndrome: majority of the final dd data readouts.
reproduce_sdk_surface_code_memory(distance, rounds, p, basis, shots, seed) Run the SDK product, read its coordinate_seed, rebuild and decode the same experiment yourself, and return both failure counts.

The matching construction

For a shot with fired detectors FF, build a complete graph on FF and on one boundary twin bub_u per u∈Fu \in F. Edge uu–vv has the shortest-path distance between uu and vv in the matching graph, edge uu–bub_u has uu's distance to the boundary, and all twins are joined by zero-weight edges. A minimum-weight perfect matching of this graph pairs every defect either with another defect or with the boundary. Predict the observable as the XOR of the observables flipped along the shortest paths of the matched pairs. Use nx.single_source_dijkstra for distances and paths, and nx.max_weight_matching(..., maxcardinality=True) on negated weights. Cache shortest paths per node and results per distinct defect set; most shots repeat.

What the checks verify

  • Measurements, detection events and observables describe the same shots and are reproducible.
  • Your matching graph has exactly PyMatching's edges, probabilities, weights and observable sets, for a repetition code and a distance-3 surface code.
  • On 1,500–2,000 seeded shots of three circuits, your total matching weight equals PyMatching's on every shot (both are optimal), and the failure counts differ by at most a few shots (equal-weight ties can be broken differently).
  • MWPM beats the syndrome-blind majority vote on a 5-round repetition memory.
  • Your pipeline reproduces the SDK product's failure count exactly for two parameter sets (the run records are written to a temporary directory).

Run the checks

python -m pytest test_exercise.py

The NetworkX decoder is for understanding and verification. It is orders of magnitude slower than PyMatching's sparse blossom and is not meant for sweeps.

Terminal
python -m pip install numpy stim pymatching networkx pytest "ketqat[qec]"

starter.py

Python
"""Starter: minimum-weight perfect matching by hand, compared with PyMatching.

The decoder below is deliberately simple and slow: it builds the matching graph
from a detector error model, computes shortest paths with Dijkstra, and solves
the matching problem with NetworkX's blossom implementation. PyMatching (sparse
blossom) solves the same optimisation far faster; agreeing with it on the same
samples is the point of the exercise.
"""

from __future__ import annotations

import math

import networkx as nx
import numpy as np
import pymatching
import stim

BOUNDARY = "boundary"


def repetition_memory(d: int, rounds: int, p: float) -> stim.Circuit:
    """Stim's repetition-code memory with all four generator noise arguments equal to p."""
    return 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,
    )


def sample_shots(circuit: stim.Circuit, shots: int, seed: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """(measurements, detection_events, observable_flips) for the SAME shots.

    measurements = circuit.compile_sampler(seed=seed).sample(shots); then
    circuit.compile_m2d_converter().convert(measurements=..., separate_observables=True).
    All three arrays are boolean.
    """
    raise NotImplementedError("sample_shots: implement this function")


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

    Nodes: detector indices 0..num_detectors-1 and the string BOUNDARY. Each
    component of each `error(q)` instruction (components are separated by `^`)
    with one detector becomes an edge to BOUNDARY, with two detectors an edge
    between them; components with more than two detectors raise ValueError.
    Edge attributes: "probability" q, "observables" (frozenset of observable
    indices flipped) and "weight" = ln((1 - q) / q). Parallel edges with the same
    observables merge as independent mechanisms, q = q1 (1 - q2) + q2 (1 - q1);
    parallel edges with different observables raise ValueError.
    """
    raise NotImplementedError("matching_graph: implement this function")


def mwpm_decode(graph: nx.Graph, detection_events: np.ndarray, num_observables: int) -> tuple[np.ndarray, np.ndarray]:
    """Decode a batch with an exact minimum-weight perfect matching.

    For each shot let F be the set of fired detectors. Build a complete graph on
    F plus one boundary twin b_u per u in F: edge u-v with the shortest-path
    distance between u and v, edge u-b_u with u's distance to BOUNDARY, and
    zero-weight edges between all twins. Find a minimum-weight perfect matching
    (e.g. nx.max_weight_matching on negated weights with maxcardinality=True),
    then XOR the observables along the shortest path of every matched pair
    (u-b_u means u's path to BOUNDARY; twin-twin pairs contribute nothing).

    Returns (predictions, weights): predictions has shape (shots, num_observables)
    and dtype bool; weights[s] is the total weight of shot s's matching.
    """
    raise NotImplementedError("mwpm_decode: implement this function")


def pymatching_decode(dem: stim.DetectorErrorModel, detection_events: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """(predictions, weights) from pymatching.Matching.from_detector_error_model(dem).decode_batch(..., return_weights=True)."""
    raise NotImplementedError("pymatching_decode: implement this function")


def count_failures(predictions: np.ndarray, observable_flips: np.ndarray) -> int:
    """Shots in which any predicted observable differs from the actual flip."""
    raise NotImplementedError("count_failures: implement this function")


def majority_vote_failures(measurements: np.ndarray, d: int) -> int:
    """Syndrome-blind baseline for repetition_memory: majority vote of the final d data readouts.

    The memory starts in logical 0, so a shot fails when more than d/2 of the last
    d measurement bits are 1.
    """
    raise NotImplementedError("majority_vote_failures: implement this function")


def reproduce_sdk_surface_code_memory(distance: int, rounds: int, p: float, basis: str, shots: int, seed: int) -> tuple[int, int]:
    """(our_failures, sdk_failures) for the KetQat SDK product [email protected].

    Run the product with these inputs, read result["coordinate_seed"], rebuild the
    circuit with stim.Circuit.generated(f"surface_code:rotated_memory_{basis}",
    distance=..., rounds=..., after_clifford_depolarization=p), sample it with
    compile_detector_sampler(seed=coordinate_seed).sample(shots, separate_observables=True)
    and decode with PyMatching built from detector_error_model(decompose_errors=True).
    """
    raise NotImplementedError("reproduce_sdk_surface_code_memory: implement this function")

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

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()

import math

import numpy as np
import pymatching
import pytest
import stim


def surface(d, rounds, p):
    return stim.Circuit.generated("surface_code:rotated_memory_z", distance=d, rounds=rounds, after_clifford_depolarization=p)


def test_samples_are_consistent():
    c = target.repetition_memory(3, 3, 0.02)
    m, det, obs = target.sample_shots(c, 500, seed=1)
    assert m.shape == (500, c.num_measurements)
    assert det.shape == (500, c.num_detectors) and obs.shape == (500, 1)
    # Independent recomputation of the observable: Stim's generator puts it on the last data readout.
    assert np.array_equal(obs[:, 0], m[:, -1])
    m2, det2, _ = target.sample_shots(c, 500, seed=1)
    assert np.array_equal(m, m2) and np.array_equal(det, det2)


@pytest.mark.parametrize("circuit", [target.repetition_memory(5, 4, 0.01), surface(3, 3, 0.01)], ids=["repetition", "surface"])
def test_matching_graph_matches_pymatching(circuit):
    dem = circuit.detector_error_model(decompose_errors=True)
    graph = target.matching_graph(dem)
    reference = pymatching.Matching.from_detector_error_model(dem)
    ref_edges = {}
    for u, v, data in reference.edges():
        a = target.BOUNDARY if u is None else u
        b = target.BOUNDARY if v is None else v
        ref_edges[frozenset((a, b))] = data
    mine = {frozenset((u, v)): data for u, v, data in graph.edges(data=True)}
    assert set(mine) == set(ref_edges)
    for key, data in mine.items():
        ref = ref_edges[key]
        assert data["probability"] == pytest.approx(ref["error_probability"], rel=1e-6)
        assert data["weight"] == pytest.approx(ref["weight"], rel=1e-6)
        assert data["observables"] == frozenset(ref["fault_ids"])


def test_matching_graph_rejects_hyperedges():
    dem = stim.DetectorErrorModel("error(0.1) D0 D1 D2")
    with pytest.raises(ValueError):
        target.matching_graph(dem)


def test_matching_graph_edge_weight_formula():
    dem = stim.DetectorErrorModel("error(0.1) D0 L0\nerror(0.2) D0 D1\nerror(0.05) D0 D1")
    g = target.matching_graph(dem)
    assert g.edges[0, target.BOUNDARY]["weight"] == pytest.approx(math.log(9))
    q = 0.2 * 0.95 + 0.05 * 0.8
    assert g.edges[0, 1]["probability"] == pytest.approx(q)
    assert g.edges[0, target.BOUNDARY]["observables"] == frozenset({0})


@pytest.mark.parametrize("circuit,shots", [
    (target.repetition_memory(5, 5, 0.03), 1500),
    (target.repetition_memory(3, 3, 0.05), 2000),
    (surface(3, 3, 0.01), 1500),
], ids=["rep-d5", "rep-d3", "surface-d3"])
def test_handwritten_mwpm_is_optimal_like_pymatching(circuit, shots):
    dem = circuit.detector_error_model(decompose_errors=True)
    _, det, obs = target.sample_shots(circuit, shots, seed=2024)
    mine, my_weights = target.mwpm_decode(target.matching_graph(dem), det, dem.num_observables)
    theirs, their_weights = target.pymatching_decode(dem, det)
    # Both decoders solve the same optimisation, so the optimal weights must agree on
    # every shot. Predictions may differ only on ties (equal-weight matchings).
    assert np.allclose(my_weights, their_weights, rtol=1e-5, atol=1e-5)
    f_mine, f_theirs = target.count_failures(mine, obs), target.count_failures(theirs, obs)
    assert abs(f_mine - f_theirs) <= max(3, 0.05 * f_theirs)


def test_matching_beats_syndrome_blind_majority_vote():
    d = 5
    c = target.repetition_memory(d, 5, 0.03)
    m, det, obs = target.sample_shots(c, 3000, seed=7)
    dem = c.detector_error_model(decompose_errors=True)
    pm, _ = target.pymatching_decode(dem, det)
    # Majority vote ignores every syndrome measurement, so errors accumulated over
    # all rounds reach the final readout uncorrected.
    assert target.count_failures(pm, obs) < target.majority_vote_failures(m, d)


def test_count_failures():
    pred = np.array([[0], [1], [1], [0]], dtype=bool)
    actual = np.array([[0], [0], [1], [1]], dtype=bool)
    assert target.count_failures(pred, actual) == 2


def test_reproduces_ketqat_surface_code_memory_product(tmp_path, monkeypatch):
    pytest.importorskip("ketqat_runner.catalog")
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path))
    ours, sdk = target.reproduce_sdk_surface_code_memory(3, 3, 0.005, "z", 20_000, seed=7)
    assert ours == sdk  # same circuit, same sampler seed, same decoder: identical counts
    ours, sdk = target.reproduce_sdk_surface_code_memory(5, 5, 0.004, "x", 5_000, seed=1)
    assert ours == sdk

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. An error mechanism has probability q=0.001q = 0.001. What is its edge weight in the matching graph?

    1 pt
  2. In the 5-qubit bit-flip code under code-capacity noise with p=0.02p = 0.02, checks 0 and 3 fire. How many times more probable is the boundary explanation X0X4X_0X_4 than the explanation X1X2X3X_1X_2X_3?

    1 pt
  3. Why does the matching graph need a boundary node?

    1 pt
  4. With your exercise functions: c = repetition_memory(5, 5, 0.03), _, det, obs = sample_shots(c, 1500, seed=2024), decode with mwpm_decode(matching_graph(dem), det, 1) where dem = c.detector_error_model(decompose_errors=True). What is the sum of the matching weights over all 1,500 shots?

    2 pts

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

  5. Run your reproduce_sdk_surface_code_memory(5, 5, 0.004, "x", 5000, seed=1). How many logical failures do you (and the SDK) report?

    2 pts

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

  6. Select every approximation that MWPM decoding of a surface-code memory makes under circuit-level depolarizing noise.

    1 pt

    Select all that apply.

  7. Your NetworkX decoder and PyMatching return equal total matching weights on every shot but differ in their predicted observable on 2 shots out of 1,500. What does this most likely indicate?

    1 pt

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

References

  1. Jack Edmonds (1965). Paths, Trees, and Flowers. Canadian Journal of Mathematics 17, 449-467. doi:10.4153/CJM-1965-045-4
  2. Eric Dennis et al. (2002). Topological quantum memory. Journal of Mathematical Physics 43, 4452-4505. doi:10.1063/1.1499754
  3. Oscar Higgott (2022). PyMatching: A Python Package for Decoding Quantum Codes with Minimum-Weight Perfect Matching. ACM Transactions on Quantum Computing 3, 16. doi:10.1145/3505637
  4. 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
  5. Craig Gidney (2021). Stim: a fast stabilizer circuit simulator. Quantum 5, 497. doi:10.22331/q-2021-07-06-497