Capstone: Simulate a Code with Stim + PyMatching and Estimate the Threshold
You'll be able to:
You can generate a repetition or surface code memory circuit in Stim, sample detector events under a circuit-level noise model, decode them with PyMatching, convert shots into logical error per round, plot the curves for several distances, read off a threshold estimate from where they cross, and write up the result with its caveats.
Putting it together: a threshold experiment on your laptop
Every number in this track — thresholds, Λ, the scaling law — came out of simulations of exactly the kind you will run now. The two tools are Stim, Craig Gidney's stabilizer-circuit simulator, and PyMatching, Oscar Higgott's matching decoder. Both are free, pip-installable, and are what the Google papers in module 5 used.
What Stim does
Stim takes a circuit of Clifford gates, resets and measurements, with noise annotations attached (for example X_ERROR(0.001) or DEPOLARIZE2(0.001) after a CNOT), and samples it extremely fast by tracking stabilizers rather than amplitudes (module 2's Gottesman–Knill theorem in action). Two annotations make it a QEC tool rather than a generic simulator:
- DETECTOR declares a parity of measurement results that is deterministic in the absence of noise — typically "this check's value compared with its value last round". A detector firing means an error somewhere nearby.
- OBSERVABLE_INCLUDE declares the logical observable whose final value you are trying to preserve; it is what you compare the decoder's prediction against.
Stim can also compile the circuit into a detector error model (DEM): a list of every independent error mechanism, its probability, and which detectors and observables it flips. That is precisely the weighted graph a matching decoder needs, and PyMatching reads it directly. The generated-circuit helper gives you repetition codes and surface codes with the standard noise knobs, so you do not have to lay out qubits yourself.
The procedure
- Install:
pip install stim pymatching numpy matplotlib. - For each distance d in {3, 5, 7, 9} and each physical error rate p in a log-spaced sweep (say 10⁻³ to 10⁻¹), build the circuit:
import stim, pymatching, numpy as np
def logical_error_rate(d, p, shots=10_000, code="repetition_code:memory"):
circuit = stim.Circuit.generated(
code, distance=d, rounds=d,
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)
matcher = pymatching.Matching.from_detector_error_model(dem)
sampler = circuit.compile_detector_sampler()
detectors, observables = sampler.sample(shots, separate_observables=True)
predictions = matcher.decode_batch(detectors)
failures = np.any(predictions != observables, axis=1).mean()
return failures
- Convert the per-shot failure rate P over r = d rounds into a per-round rate. The logical state flips with probability P after r rounds, so if ε is the per-round flip probability, P = ½(1 − (1 − 2ε)^r) and therefore ε = ½(1 − (1 − 2P)^(1/r)). Using the per-round rate is what lets you compare distances fairly, since larger d means more rounds and more chances to fail.
- Plot ε against p on log–log axes, one line per distance, with binomial error bars: for n shots and k failures, the standard error is roughly √(k)/n. With 10,000 shots and P = 10⁻³ you get ten failures and a ±30% error bar; increase shots at the low-p end or you will be fitting noise.
- Read the threshold off the plot as the p where the curves cross: below it, larger distance is lower; above it, larger distance is higher. Then swap the code string for surface_code:rotated_memory_z, repeat with d in {3, 5} (distance 7 is slower but fine), and note the much lower crossing point.
What to expect, and why
Under this noise model you should find the repetition code's curves crossing at a physical error rate of several percent and the surface code's somewhere below one percent. The repetition code's threshold is higher because it only fights one error type on a line, so its matching graph is a chain with no competing paths; the surface code's is lower because it pays for protecting against both X and Z and because its syndrome-extraction circuits are deeper. Below threshold, a factor-of-two drop in p should make each distance step suppress error by roughly a factor of two more — your own measurement of Λ, which you can compare with module 5's.
How to write it up honestly
Your half-page should name the following assumptions, because every one of them is violated by real hardware:
- Noise model. You used uniform depolarising noise with the same p on every operation. Real devices have readout error several times gate error, idle errors that depend on circuit timing, and some qubits far worse than others.
- Independence. The DEM treats every error mechanism as independent. Leakage, crosstalk and the correlated bursts in Google's 2024 paper are not.
- Decoder. Your threshold is the threshold of this code with this decoder. A better decoder (correlated matching, neural) moves it up; union-find moves it down. Quote the pair, never the code alone.
- Finite size. Curves for d = 3 and d = 5 cross at a slightly different p from d = 7 and d = 9. Small-distance crossings overestimate the asymptotic threshold; say which pair you used.
- Statistics. State shot counts and error bars. A crossing read from ten failures is not a measurement.
- Memory only. This is a logical memory experiment. Nothing here says anything about logical gates, which (module 6) is where most of the cost lives.
If your write-up contains a threshold estimate with its decoder named, a Λ with its p named, and a list like the one above, you have done what the authors of the papers in module 5 did — at smaller scale, with the same tools, and with the same obligations to say what the number does not mean.
What to remember
- Stim samples Clifford circuits with Pauli noise by tracking stabilizers; detectors and observables turn samples into decoder problems.
- The detector error model is the weighted matching graph; PyMatching consumes it directly.
- Convert per-shot failure to per-round error before comparing distances.
- The threshold is where curves of different distance cross — and it belongs to a code and a decoder and a noise model.
- Write the caveats down: noise model, independence, decoder, finite size, statistics, memory-only.
Curated Materials
2.2hThe deep work happens here — the lesson is your briefing.
Live on aiqbench
This lesson's subject on the rest of the site, today.
In the news, last 30 days
- GPU decoder keeps pace with a superconducting qubit clock on a continuous stream, with NVIDIA NVQLink interconnectAlice & Bob ·
- Classiq and Diraq Partner on Fault-Tolerant Silicon Quantum ComputingThe Quantum Insider ·
- Classiq and Diraq Collaborate to Advance Fault-Tolerant Quantum Computing on SiliconHPCwire ·
Test your knowledge
5 questions in 100 seconds, on a page of its own. Read everything above first.
Test your knowledge →Module Mission
45–60 minpip install stim pymatching matplotlib. Use stim.Circuit.generated('repetition_code:memory', distance=d, rounds=d, after_clifford_depolarization=p, before_measure_flip_probability=p, after_reset_flip_probability=p, before_round_data_depolarization=p) for d in {3,5,7,9} and p in a log-spaced sweep from 1e-3 to 1e-1. For each (d,p) sample 10,000 shots with the detector sampler, decode with pymatching.Matching.from_detector_error_model(circuit.detector_error_model(decompose_errors=True)), count logical failures, convert to error per round, and plot logical error per round vs p on log–log axes with one line per distance. Report the crossing point as your threshold estimate and then repeat with 'surface_code:rotated_memory_z' at d in {3,5} to see the different threshold. Write a half-page note on what your estimate assumes.
Loading your work…