About this notebook

Companion to Lecture 0: Orientation. 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)

A memory experiment stores one logical qubit for a number of rounds of error correction, measures it, and asks whether the answer is still right. It is the “hello world” of quantum error correction (QEC), and it already uses every stage of the Deltakit pipeline:

 code ──────────► circuit ──────────► noisy circuit ──► samples ──────► predictions ──► LEP
 RotatedPlanar    css_code_memory_    QPU(...).compile_  detector       decoder         fails/shots
 Code(3, 3)       circuit(...)        and_add_noise_...  sampler        .decode_batch_  ± error bar
                  (deltakit.circuit)  (SI1000 noise)     (Stim, seeded) to_logical_flip

In this notebook you will:

  1. build a distance-3 rotated surface code and look at it;
  2. turn it into a memory-experiment circuit and add realistic noise;
  3. build a matching decoder, and meet the circuit it hands back;
  4. sample 100,000 shots, decode them and count logical failures;
  5. repeat for distances 3, 5 and 7 at four noise strengths, and see where a bigger code starts to help.

Every number below comes from a seeded run (SEED). Run the notebook with the course’s qecdk kernel and you get exactly the same numbers; the box at the end of section 4 explains why the kernel matters.

import deltakit
import deltakit_stim as stim
import matplotlib.pyplot as plt
import numpy as np
from matplotlib_inline.backend_inline import set_matplotlib_formats
 
from deltakit.circuit.gates import PauliBasis
from deltakit.decode import PyMatchingDecoder
from deltakit.decode.analysis import StimDecoderManager
from deltakit.explorer.analysis import calculate_lep_and_lep_stddev
from deltakit.explorer.codes import RotatedPlanarCode, css_code_memory_circuit
from deltakit.explorer.qpu import QPU, SD6Noise, SI1000Noise
 
set_matplotlib_formats("svg")
SEED = 2026
print("deltakit", deltakit.__version__)
deltakit 0.10.2

1. A code

The rotated surface code of distance puts data qubits on a square grid and one ancilla qubit on each check. Each check measures the product of (or of ) on the two or four data qubits around it. Deltakit calls the code RotatedPlanarCode; width and height are the distances against the two kinds of logical error.

code = RotatedPlanarCode(width=3, height=3)
print("data qubits:   ", len(code.data_qubits))
print("ancilla qubits:", len(code.ancilla_qubits))
# stabilisers are grouped by when they are measured; this code has one group
print("stabilisers:   ", [len(g) for g in code.stabilisers])
print("distances (X, Z):", code.x_distance, code.z_distance)
data qubits:    9
ancilla qubits: 8
stabilisers:    [8]
distances (X, Z): 3 3
fig, ax = code.draw_patch()
ax.grid(False)
plt.show()
The distance-3 rotated surface code as Deltakit draws it. Dark dots are the nine data qubits, orange dots the eight ancillas. Cyan plaquettes are Z checks and grey ones X checks; the triangles on the boundary are weight-2 checks, two of each type. Axes are the qubit coordinates that reappear in the detector coordinates.

The distance-3 rotated surface code as Deltakit draws it. Dark dots are the nine data qubits, orange dots the eight ancillas. Cyan plaquettes are Z checks and grey ones X checks; the triangles on the boundary are weight-2 checks, two of each type. Axes are the qubit coordinates that reappear in the detector coordinates.

2. A circuit, then a noisy circuit

A code is a set of checks; an experiment is a circuit. css_code_memory_circuit writes the whole experiment: reset the data qubits in the basis, measure every check for num_rounds rounds, measure the data qubits, and declare which measurement parities are detectors (they are deterministic without noise) and which one is the logical observable. The result is a deltakit.circuit.Circuit; .as_stim_circuit() converts it to Stim.

circ = css_code_memory_circuit(
    code, num_rounds=3, logical_basis=PauliBasis.Z
)
clean = circ.as_stim_circuit()
print(type(circ).__name__, "->", type(clean).__module__)
print("qubits      ", clean.num_qubits)
print("measurements", clean.num_measurements)
print("detectors   ", clean.num_detectors)
print("observables ", clean.num_observables)
Circuit -> deltakit_stim._stim_polyfill
qubits       17
measurements 33
detectors    24
observables  1

There are 8 checks × 3 rounds = 24 check measurements, plus 9 final data measurements: 33 in all. The first round of checks is already deterministic, because the data qubits start in ; the first round of checks is random and gives no detector. That is why there are 24 detectors: 4 checks × (3 rounds + 1 comparison with the final data measurement) = 16, plus 4 checks × 2 later rounds = 8.

The circuit has no noise yet. A QPU adds it: it compiles the circuit to the machine’s native gates and inserts noise channels according to a noise model. SI1000Noise(p=...) is the “superconducting-inspired” model of Gidney et al. (2021): one parameter sets every error rate, with two-qubit gates at and other locations at fixed multiples of it. First, which instructions does each circuit use?

qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=1e-3))
noisy = qpu.compile_and_add_noise_to_circuit(circ)
sc = noisy.as_stim_circuit()
 
ANNOTATIONS = {"DETECTOR", "OBSERVABLE_INCLUDE", "QUBIT_COORDS", "TICK"}
 
 
def gate_names(c):
    return sorted({i.name for i in c.flattened()} - ANNOTATIONS)
 
 
print("before:", gate_names(clean))
print("after: ", gate_names(sc))
before: ['CX', 'CZ', 'I', 'M', 'MX', 'R', 'RX']
after:  ['CX', 'DEPOLARIZE1', 'DEPOLARIZE2', 'H', 'M', 'R', 'X_ERROR']

The compiler rewrote , -basis resets (RX) and -basis measurements (MX) into the native set {H, CX, R, M}, removed the explicit idles (I), and added three kinds of noise. Rather than trust a table, read off the rates it used:

NOISY = {"DEPOLARIZE1", "DEPOLARIZE2", "X_ERROR", "M"}
rates = sorted({
    (i.name, round(i.gate_args_copy()[0], 6))
    for i in sc.flattened()
    if i.name in NOISY and i.gate_args_copy()
})
for name, rate in rates:
    print(f"{name:12s} {rate:g}  = {rate / 1e-3:g} p")
DEPOLARIZE1  0.0001  = 0.1 p
DEPOLARIZE1  0.002  = 2 p
DEPOLARIZE2  0.001  = 1 p
M            0.005  = 5 p
X_ERROR      0.002  = 2 p

These are the SI1000 rules: two-qubit gates depolarise with probability , single-qubit gates and idles with , qubits idling during a measurement or reset with , resets flip with and measurements report the wrong bit with . Lecture 4 explains where such models come from.

From this circuit Stim derives a detector error model (DEM): the list of independent error mechanisms, each with its probability and the detectors and observable it flips.

dem = sc.detector_error_model(decompose_errors=True)
print("DEM error mechanisms:", dem.num_errors)
print("first three:")
for inst in list(dem.flattened())[:3]:
    print("  ", inst)
DEM error mechanisms: 290
first three:
   error(0.00239839) D0
   error(0.00233204) D0 D3
   error(0.00750577) D0 D5

3. A decoder, and the circuit it hands back

A decoder reads the detection events of one shot and predicts whether the observable was flipped. PyMatchingDecoder wraps PyMatching, a minimum-weight perfect matching decoder (Lecture 5). Its factory builds the decoder and returns a Stim circuit:

dec, dec_circ = PyMatchingDecoder.construct_decoder_and_stim_circuit(
    noisy
)
print("detectors in the noisy circuit:  ", sc.num_detectors)
print("detectors in the decoder circuit:", dec_circ.num_detectors)
detectors in the noisy circuit:   24
detectors in the decoder circuit: 16

The two numbers differ. The factory reorders the detectors by their coordinates and then trims the circuit: it removes every detector in a part of the decoding graph that no error connects to a logical observable. In a -basis memory the 8 -check detectors form such a part (they only see errors, which cannot flip ), so they go. The decoder expects exactly the 16 columns of the circuit it returned. Sampling the circuit you built is a common first mistake, and the error message says so:

wrong, _ = sc.compile_detector_sampler(seed=SEED).sample(
    10, separate_observables=True
)
try:
    dec.decode_batch_to_logical_flip(wrong)
except ValueError as err:
    print("ValueError:", err)
ValueError: `shots` array should have at least 16 columns (the number of detectors), and no more than 17 columns (the number of nodes), but instead has 24 columns

Rule of thumb

Sample from the circuit the decoder factory returns, not from the one you built. Even when the counts agree, its detectors are in a different order.

4. Sample, decode, count

Stim’s detector sampler simulates the noisy circuit shot by shot (thousands at a time, with bit-packed Pauli frames) and returns two boolean arrays: the detection events, one column per detector, and the true observable flips, one column per observable.

shots = 100_000
sampler = dec_circ.compile_detector_sampler(seed=SEED)
dets, obs = sampler.sample(shots, separate_observables=True)
print("dets", dets.shape, dets.dtype, "  obs", obs.shape, obs.dtype)
print("fraction of detectors that fired:", round(float(dets.mean()), 4))
print("shots with no detection event:   ", int((~dets.any(axis=1)).sum()))
dets (100000, 16) bool   obs (100000, 1) bool
fraction of detectors that fired: 0.0252
shots with no detection event:    77305

A shot fails when the decoder’s predicted flip disagrees with the true flip. The logical error probability (LEP) is the fraction of failed shots, and its standard error is the binomial .

pred = dec.decode_batch_to_logical_flip(dets)
fails = int(np.any(pred != obs, axis=1).sum())
lep, lep_std = calculate_lep_and_lep_stddev(fails=fails, shots=shots)
print(f"fails: {fails} of {shots}")
print(f"LEP:   {lep:.2e} ± {lep_std:.1e}")
print(f"undecoded (just read the observable): {obs.mean():.2e}")
fails: 344 of 100000
LEP:   3.44e-03 ± 1.9e-04
undecoded (just read the observable): 4.87e-02

Decoding lowers the failure rate from the raw rate (reading the noisy observable without correction) to for this short, three-round experiment.

StimDecoderManager packages the same loop: it samples its circuit with the given seed, decodes in batches and returns (shots, fails). With the same seed and one batch it reproduces the count above.

manager = StimDecoderManager(
    dec_circ, dec, seed=SEED, batch_size=shots
)
n, f = manager.run_batch_shots(shots)
print(f"shots {n}, fails {f}")
shots 100000, fails 344

Why the kernel matters for reproducibility

A seed fixes the random numbers, but not which qubit receives each one. That follows the order of the targets in the circuit, and Deltakit builds the first reset layer from a Python frozenset, whose order depends on Python’s string-hash seed. Change PYTHONHASHSEED and the same SEED gives a slightly different count (344 here, 340 with hash seed 1): statistically the same experiment, but not the same bits. The course’s qecdk kernel sets PYTHONHASHSEED=0, as do the scripts that built these pages.

5. Does a bigger code help?

The point of a code family is that a larger distance should suppress logical errors, if the physical error rate is low enough. Run the whole pipeline for (with rounds each) at four values of , 200,000 shots per point. The function below is the notebook in five lines.

def run_memory(d, p, shots=200_000):
    code = RotatedPlanarCode(width=d, height=d)
    circ = css_code_memory_circuit(
        code, num_rounds=d, logical_basis=PauliBasis.Z
    )
    qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=p))
    noisy = qpu.compile_and_add_noise_to_circuit(circ)
    dec, dec_circ = PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy)
    manager = StimDecoderManager(dec_circ, dec, seed=SEED, batch_size=100_000)
    return manager.run_batch_shots(shots)
 
 
ps = [5e-4, 1e-3, 2e-3, 4e-3]
ds = [3, 5, 7]
results = {}
print("p       " + "".join(f"   d={d} fails" for d in ds))
for p in ps:
    row = []
    for d in ds:
        n, f = run_memory(d, p)
        results[d, p] = (int(f), int(n))
        row.append(f"{int(f):>13d}")
    print(f"{p:<8g}" + "".join(row))
p          d=3 fails   d=5 fails   d=7 fails
0.0005            189           33            3
0.001             730          177           46
0.002            2617         1511          759
0.004            9495         9932         9690
fig, ax = plt.subplots()
for d in ds:
    fails = [results[d, p][0] for p in ps]
    n = [results[d, p][1] for p in ps]
    lep, err = calculate_lep_and_lep_stddev(fails=fails, shots=n)
    ax.errorbar(ps, lep, yerr=err, marker="o", capsize=3, label=f"d = {d}")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel("physical error rate p (SI1000)")
ax.set_ylabel("logical error probability (d rounds)")
ax.legend(title="distance")
plt.show()
Logical error probability of a d-round memory experiment against the SI1000 noise strength p, 200,000 shots per point, PyMatching. Below about p = 4×10⁻³ each step up in distance lowers the logical error rate; near that value the three curves meet.

Logical error probability of a d-round memory experiment against the SI1000 noise strength p, 200,000 shots per point, PyMatching. Below about p = 4×10⁻³ each step up in distance lowers the logical error rate; near that value the three curves meet.

Two things to read off the figure.

  • Below threshold, distance pays. At , going from to cuts the failures by about a factor of 4, and from to by another factor of 4, even though the larger codes also run more rounds. Lecture 6 turns this into the error-suppression factor by converting to error per round.
  • Near the curves meet. Around that point a bigger code stops helping: this is the threshold of this code, noise model and decoder. Lecture 6 explains why the crossing drifts with size and how to estimate it honestly.

The point at rests on 3 failures, so its error bar is more than half the value. The symmetric error bar is a poor description there; Lecture 6 uses asymmetric intervals instead.

Try this

  1. Change logical_basis to PauliBasis.X. Which checks give detectors now, and how many columns does the decoder’s circuit have?
  2. Replace SI1000Noise(p=p) by SD6Noise(p=p) and rerun the sweep. Does the crossing move?
  3. Run run_memory(5, 1e-3) with 1, 3, 5 and 9 rounds (add a rounds argument). How does the logical error probability grow with the number of rounds?
  4. Pass a different SEED and see how much the , count moves.