About this notebook
Companion to Lecture 4: Noise, detectors and detector error models. Every cell below was executed headless with the course’s pinned Deltakit (deltakit 0.10.2, deltakit-stim 0.2.7, pymatching 2.4.0, Python 3.12.12); each output is exactly what the code printed. Download the notebook (.ipynb)
Lecture 4 followed the chain from a noise model to a decoding graph:
noise model ──► noisy circuit ──► detector error model ──► decoding graph ──► decoder
SD6, SI1000, QPU(...).compile_ stim .detector_error_ dem_to_decoding_ PyMatching
Toy, phenom. and_add_noise_... model(decompose_...) graph_and_logicalsHere you run every link and measure it. You will:
- run three noise models at the same
and see that " " means very different things; - watch the detection-event rate round by round;
- measure how the detector error model (DEM) grows with distance;
- take a decoding graph apart, and check its edge probabilities against sampled data;
- switch leakage on and watch the decoder lose ground;
- build true phenomenological noise, which the default compile path silently drops.
import collections
import math
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 import measurement_noise_profile
from deltakit.circuit.gates import PauliBasis
from deltakit.circuit.noise_channels import Depolarise1
from deltakit.core.decoding_graphs import dem_to_decoding_graph_and_logicals
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,
ExhaustiveGateSet,
PhenomenologicalNoise,
SD6Noise,
SI1000Noise,
ToyNoise,
)
set_matplotlib_formats("svg")
SEED = 2026
print("deltakit", deltakit.__version__, "| deltakit_stim", stim.__version__)deltakit 0.10.2 | deltakit_stim 0.2.7
Three helpers carry the whole notebook: build a noisy
def noisy_memory(d, rounds, noise, basis=PauliBasis.Z):
"""A d x d rotated-code memory circuit, compiled and with noise added."""
circ = css_code_memory_circuit(
RotatedPlanarCode(d, d), num_rounds=rounds, logical_basis=basis
)
return QPU(circ.qubits, noise_model=noise).compile_and_add_noise_to_circuit(circ)
def noise_table(stim_circ):
"""How many times each noise channel appears, by name and probability."""
count = collections.Counter()
for inst in stim_circ.flattened():
args = inst.gate_args_copy()
if inst.name in ("DETECTOR", "OBSERVABLE_INCLUDE", "QUBIT_COORDS", "SHIFT_COORDS"):
continue
if not args:
continue
n = len(inst.targets_copy()) // (2 if inst.name == "DEPOLARIZE2" else 1)
count[inst.name, round(args[0], 6)] += n
return dict(sorted(count.items()))
def count_failures(noisy, shots):
"""Decode `shots` seeded samples with PyMatching; return (fails, shots)."""
dec, dcirc = PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy)
manager = StimDecoderManager(dcirc, dec, seed=SEED, batch_size=100_000)
n, f = manager.run_batch_shots(shots)
return int(f), int(n)1. Same , three models
SD6Noise, SI1000Noise and ToyNoise all take one number M and MX.
MODELS = {
"SD6": SD6Noise(p=1e-3),
"SI1000": SI1000Noise(p=1e-3),
"Toy": ToyNoise(p=1e-3),
}
for name, model in MODELS.items():
table = noise_table(noisy_memory(3, 3, model).as_stim_circuit())
print(f"{name}:")
for (gate, p), n in table.items():
print(f" {gate:12s} p={p:<8g} x{n}")SD6: DEPOLARIZE1 p=0.001 x215 DEPOLARIZE2 p=0.001 x72 M p=0.001 x33 X_ERROR p=0.001 x33 SI1000: DEPOLARIZE1 p=0.0001 x215 DEPOLARIZE1 p=0.002 x36 DEPOLARIZE2 p=0.001 x72 M p=0.005 x33 X_ERROR p=0.002 x33 Toy: DEPOLARIZE1 p=0.0001 x281 DEPOLARIZE2 p=0.001 x72 M p=0.001 x33
Now decode each one, 200,000 shots, at
model_results = {}
print(" d model detector rate fails / 200,000")
for d in (3, 5):
for name, model in MODELS.items():
noisy = noisy_memory(d, d, model)
sampler = noisy.as_stim_circuit().compile_detector_sampler(seed=SEED)
rate = sampler.sample(100_000).mean()
model_results[d, name] = count_failures(noisy, 200_000)
print(f"{d:2d} {name:8s} {rate:12.4f} {model_results[d, name][0]:12d}")d model detector rate fails / 200,000 3 SD6 0.0205 515 3 SI1000 0.0266 730 3 Toy 0.0088 96 5 SD6 0.0251 186 5 SI1000 0.0302 177 5 Toy 0.0111 14
fig, ax = plt.subplots()
xs = np.arange(len(MODELS))
for k, d in enumerate((3, 5)):
fails = [model_results[d, name][0] for name in MODELS]
shots = [model_results[d, name][1] for name in MODELS]
lep, err = calculate_lep_and_lep_stddev(fails=fails, shots=shots)
ax.bar(xs + (k - 0.5) * 0.36, lep, width=0.36, yerr=err, capsize=3,
label=f"d = {d}, {d} rounds")
ax.set_xticks(xs, list(MODELS))
ax.set_yscale("log")
ax.set_ylabel("logical error probability")
ax.set_xlabel("noise model, all at p = 10⁻³")
ax.set_axisbelow(True)
ax.grid(axis="x", visible=False)
ax.legend()
plt.show()Logical error probability of a d-round rotated-code memory at p = 10⁻³ under three noise models, 200,000 shots per bar, PyMatching. The same p gives failure rates that differ by up to an order of magnitude (7.6× at d = 3, 13× at d = 5).
SI1000 lights the most detectors at both sizes. At ToyNoise puts only
Always quote the noise model with
A logical error rate “at
” means nothing without the model. When you compare with a paper, check which model it used and how it defines .
2. Detection events, round by round
Run ten rounds at
def rate_by_round(stim_circ, shots=50_000):
dets = stim_circ.compile_detector_sampler(seed=SEED).sample(shots)
coords = stim_circ.get_detector_coordinates()
t = np.array([coords[i][2] for i in range(stim_circ.num_detectors)])
rounds = np.unique(t)
return rounds, np.array([dets[:, t == r].mean() for r in rounds])
round_rates = {}
for name, model in MODELS.items():
round_rates[name] = rate_by_round(noisy_memory(5, 10, model).as_stim_circuit())
print(f"{name:7s}", " ".join(f"{x:.4f}" for x in round_rates[name][1]))SD6 0.0141 0.0277 0.0276 0.0279 0.0279 0.0279 0.0279 0.0278 0.0280 0.0279 0.0142 SI1000 0.0181 0.0318 0.0319 0.0316 0.0316 0.0318 0.0319 0.0321 0.0321 0.0320 0.0280 Toy 0.0058 0.0118 0.0117 0.0121 0.0121 0.0121 0.0122 0.0122 0.0120 0.0121 0.0092
fig, ax = plt.subplots()
for name, (rounds, rates) in round_rates.items():
ax.plot(rounds, rates, marker="o", label=name)
ax.set_xlabel("round t (detector coordinate)")
ax.set_ylabel("fraction of detectors that fire")
ax.set_ylim(0, 0.042)
ax.legend(title="noise model", loc="upper center", ncols=3)
plt.show()Fraction of detectors that fire in each round of a 10-round, d = 5 memory at p = 10⁻³, 50,000 shots. The first and last rounds hold only the 12 Z-check detectors and fire less; the bulk is flat, so nothing builds up over time.
The first round compares one measurement with the known value of a fresh preparation and the last round compares one with the data readout, so both fire less than the bulk, which compares two noisy measurements. In the bulk the rate is flat for all three models. Section 5 shows a case where it is not.
3. The detector error model and its size
detector_error_model() turns the noisy circuit into a list of independent error mechanisms.
Each row reads error(p) D… L…: probability, detectors flipped, observables flipped. Here are
the first rows of the
sc3 = noisy_memory(3, 3, SI1000Noise(p=1e-3)).as_stim_circuit()
raw3 = sc3.detector_error_model()
dem3 = sc3.detector_error_model(decompose_errors=True)
print("raw rows:", raw3.num_errors, "| decomposed rows:", dem3.num_errors)
big = [e for e in raw3.flattened() if e.type == "error"
and sum(t.is_relative_detector_id() for t in e.targets_copy()) > 2]
print("raw rows that flip more than two detectors:", len(big))
print("a raw row: ", big[0])
pieces = [e for e in dem3.flattened() if e.type == "error"
and any(t.is_separator() for t in e.targets_copy())]
print("a decomposed row:", pieces[0])raw rows: 221 | decomposed rows: 290 raw rows that flip more than two detectors: 113 a raw row: error(0.000533333) D1 D3 D7 a decomposed row: error(0.000533333) D1 D3 ^ D7
A decomposed row lists its pieces separated by ^. Each piece flips at most two detectors,
so it can become an edge of the decoding graph. Now grow the code, with
dem_sizes = {}
print(" d qubits detectors raw rows decomposed rows graph edges rows/detector")
for d in (3, 5, 7, 9):
sc = noisy_memory(d, d, SI1000Noise(p=1e-3)).as_stim_circuit()
raw = sc.detector_error_model()
dem = sc.detector_error_model(decompose_errors=True)
graph, _ = dem_to_decoding_graph_and_logicals(dem)
dem_sizes[d] = (sc.num_detectors, raw.num_errors, dem.num_errors, len(graph.edges))
print(f"{d:2d} {sc.num_qubits:7d} {sc.num_detectors:10d} {raw.num_errors:9d}"
f" {dem.num_errors:16d} {len(graph.edges):12d}"
f" {dem.num_errors / sc.num_detectors:14.1f}")d qubits detectors raw rows decomposed rows graph edges rows/detector 3 17 24 221 290 78 12.1 5 49 120 1951 2233 502 18.6 7 97 336 6289 6920 1558 20.6 9 161 720 14531 15647 3534 21.7
fig, ax = plt.subplots()
ds = sorted(dem_sizes)
labels = ["detectors", "raw DEM rows", "decomposed DEM rows", "graph edges"]
for k, (label, marker) in enumerate(zip(labels, "os^D")):
ax.plot(ds, [dem_sizes[d][k] for d in ds], marker=marker, label=label)
ax.plot(ds, [dem_sizes[3][2] * (d / 3) ** 3 for d in ds], "--", color="0.5",
label="slope 3")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xticks(ds, [str(d) for d in ds])
ax.minorticks_off()
ax.set_xlabel("code distance d (rounds = d)")
ax.set_ylabel("count")
ax.legend()
plt.show()Size of the detector error model of a d-round SI1000 memory against distance, on log–log axes. Detectors, (d²−1)d of them, run parallel to the d³ guide (dashed). DEM rows and graph edges rise a little faster at small d, as the bulk takes over.
The detector count is exactly
4. Inside a decoding graph
dem_to_decoding_graph_and_logicals turns the decomposed DEM into a graph. Each node has a
detector record with its coordinates; each edge has a record with its probability p_err and
weight. The weight is exactly
graph, logicals = dem_to_decoding_graph_and_logicals(dem3)
recs = graph.detector_records
print("nodes", len(graph.nodes), "| edges", len(graph.edges),
"| boundary", sorted(graph.boundaries))
print("detector 0:", recs[0])
edge = sorted(graph.edges, key=lambda e: sorted(e))[0]
rec = graph.edge_records[edge]
print("edge", sorted(edge), " p_err", f"{rec.p_err:.6f}", " weight", f"{rec.weight:.6f}",
" ln((1-p)/p)", f"{math.log((1 - rec.p_err) / rec.p_err):.6f}")nodes 25 | edges 78 | boundary [24]
detector 0: {'spatial_coord': (4.0, 0.0), 'time': 0}
edge [0, 3] p_err 0.002332 weight 6.058679 ln((1-p)/p) 6.058679
def edge_kind(u, v):
if graph.boundaries & {u, v}:
return "boundary"
if recs[u].time == recs[v].time:
return "space"
if recs[u].spatial_coord == recs[v].spatial_coord:
return "time"
return "diagonal"
weights = collections.defaultdict(list)
for e in graph.edges:
weights[edge_kind(*tuple(e))].append(graph.edge_records[e].weight)
for kind, w in weights.items():
print(f"{kind:8s} {len(w):2d} edges, weight {min(w):.2f} .. {max(w):.2f}")boundary 24 edges, weight 3.90 .. 5.93 space 18 edges, weight 5.09 .. 6.06 time 16 edges, weight 4.87 .. 4.88 diagonal 20 edges, weight 6.84 .. 8.23
fig, ax = plt.subplots()
bins = np.linspace(3.5, 8.5, 26)
kinds = ["boundary", "time", "space", "diagonal"]
ax.hist([weights[k] for k in kinds], bins=bins, stacked=True, label=kinds)
ax.set_xlabel("edge weight ln((1−p)/p)")
ax.set_ylabel("number of edges")
ax.set_axisbelow(True)
ax.grid(axis="x", visible=False)
ax.legend(title="edge class")
plt.show()Edge weights w = ln((1−p)/p) of the d = 3, three-round SI1000 decoding graph, by edge class. Time-like edges (measurement flips, at 5p) are the cheapest bulk edges and space-time diagonals the dearest; boundary edges spread widest because many faults merge into them.
Checking the graph against data
The decoding graph comes from the noise model. An experiment has only samples. For two
detectors
where
x = sc3.compile_detector_sampler(seed=SEED).sample(500_000).astype(np.float64)
mean = x.mean(axis=0)
corr = x.T @ x / len(x)
pairs, model_p, data_p, edge_kinds = [], [], [], []
for e in graph.edges:
u, v = sorted(tuple(e))
kind = edge_kind(u, v)
if kind == "boundary":
continue
num = 4 * (corr[u, v] - mean[u] * mean[v])
den = 1 - 2 * mean[u] - 2 * mean[v] + 4 * corr[u, v]
pairs.append((u, v))
data_p.append(0.5 - 0.5 * math.sqrt(1 - num / den))
model_p.append(graph.edge_records[e].p_err)
edge_kinds.append(kind)
model_p, data_p, edge_kinds = np.array(model_p), np.array(data_p), np.array(edge_kinds)
rel = np.abs(data_p - model_p) / model_p
print(f"{len(pairs)} bulk edges: median relative difference {np.median(rel):.3f}")
print(f"edges more than 50% off: {np.sum(rel > 0.5)}, of classes",
sorted(set(edge_kinds[rel > 0.5].tolist())))54 bulk edges: median relative difference 0.057 edges more than 50% off: 8, of classes ['diagonal']
fig, ax = plt.subplots(figsize=(5.4, 4.6))
for kind, marker in (("time", "o"), ("space", "s"), ("diagonal", "^")):
m = edge_kinds == kind
ax.scatter(model_p[m], data_p[m], marker=marker, label=kind, zorder=3)
lim = [1.5e-4, 1.5e-2]
ax.plot(lim, lim, "--", color="0.5", label="data = graph")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(lim)
ax.set_ylim(lim)
ax.set_xlabel("edge probability in the decoding graph")
ax.set_ylabel("estimated from samples, p_ij")
ax.legend(title="edge class")
plt.show()Pair probabilities estimated from 500,000 sampled shots (p_ij formula) against the decoding graph's edge probabilities, for the 54 bulk edges of the d = 3, three-round SI1000 graph. Most points lie on the diagonal; eight diagonal-class edges sit about a factor of 2 above it.
Half the edges agree to within 6 per cent. The eight outliers are not sampling noise. The
samples see every mechanism that flips both detectors, including rows of the raw DEM that
flip three detectors. The decomposition split some of those rows into pieces that put
def pair_probability(dem, u, v):
"""Merge every DEM row that flips both detectors u and v."""
q = 0.0
for row in dem.flattened():
if row.type != "error":
continue
dets = {t.val for t in row.targets_copy() if t.is_relative_detector_id()}
if {u, v} <= dets:
p = row.args_copy()[0]
q = q + p - 2 * q * p
return q
raw_p = np.array([pair_probability(raw3, u, v) for u, v in pairs])
print("edge graph p all raw rows p samples p_ij")
for i in np.argsort(-rel)[:4]:
print(f"{str(pairs[i]):9s} {model_p[i]:.2e} {raw_p[i]:.2e} {data_p[i]:.2e}")
rel_raw = np.abs(data_p - raw_p) / raw_p
print(f"samples vs all raw rows: median relative difference {np.median(rel_raw):.3f},"
f" largest {rel_raw.max():.3f}")edge graph p all raw rows p samples p_ij (9, 13) 2.67e-04 5.33e-04 5.98e-04 (8, 15) 2.67e-04 5.33e-04 5.56e-04 (17, 20) 2.67e-04 5.33e-04 5.18e-04 (2, 11) 2.67e-04 5.33e-04 5.01e-04 samples vs all raw rows: median relative difference 0.024, largest 0.189
So decomposition is not free: it throws away the correlations inside a hyperedge, and a
matching decoder never sees them. Decoders that keep hyperedges (Lectures 5 and 7) can. On
hardware the same comparison is a diagnostic. Where
5. Leakage
deltakit_stim simulates leakage with two extra instructions: LEAKAGE(p) moves a qubit out
of the qubit subspace and RELAX(p) brings it back. What does a leaked qubit do? Force one to
leak, apply a CX to a partner, and measure both:
tiny = stim.Circuit("R 0 1\nLEAKAGE(1) 0\nCX 0 1\nM 0 1")
ones = tiny.compile_sampler(seed=SEED).sample(20_000).mean(axis=0)
print("fraction of 1s: leaked qubit", round(float(ones[0]), 3),
"| its CX partner", round(float(ones[1]), 3))fraction of 1s: leaked qubit 0.502 | its CX partner 0.504
Both read as fair coins. A leaked qubit gives a random result, and every two-qubit gate with
it scrambles the partner, until a reset or a RELAX returns it. SI1000Noise(p, pL) adds
LEAKAGE(pL) after two-qubit gates and resets. The DEM is built from Pauli faults only, so it
does not change. The detectors notice:
for pL in (0.0, 1e-4):
sc = noisy_memory(3, 3, SI1000Noise(p=1e-3, pL=pL)).as_stim_circuit()
names = sorted({i.name for i in sc.flattened()} & {"LEAKAGE", "RELAX"})
rows = sc.detector_error_model(decompose_errors=True).num_errors
print(f"pL={pL:g}: leakage instructions {names}, DEM rows {rows}")
leak_rates = {}
for pL in (0.0, 1e-4, 1e-3):
sc = noisy_memory(5, 10, SI1000Noise(p=1e-3, pL=pL)).as_stim_circuit()
leak_rates[pL] = rate_by_round(sc)
print(f"pL={pL:<6g}", " ".join(f"{x:.3f}" for x in leak_rates[pL][1]))pL=0: leakage instructions [], DEM rows 290 pL=0.0001: leakage instructions ['LEAKAGE', 'RELAX'], DEM rows 290 pL=0 0.018 0.032 0.032 0.032 0.032 0.032 0.032 0.032 0.032 0.032 0.028 pL=0.0001 0.019 0.034 0.034 0.035 0.037 0.037 0.037 0.038 0.039 0.040 0.034 pL=0.001 0.027 0.053 0.060 0.067 0.073 0.079 0.085 0.091 0.097 0.103 0.090
fig, ax = plt.subplots()
for pL, (rounds, rates) in leak_rates.items():
ax.plot(rounds, rates, marker="o", label=f"pL = {pL:g}")
ax.set_xlabel("round t (detector coordinate)")
ax.set_ylabel("fraction of detectors that fire")
ax.set_ylim(bottom=0)
ax.legend()
plt.show()Fraction of detectors that fire in each round of a 10-round, d = 5 SI1000 memory at p = 10⁻³, with leakage off and on, 50,000 shots. With leakage the rate climbs round after round as leaked qubits accumulate.
Now decode. The decoder is built from the DEM, so it is the same with leakage on or off; only the samples change.
leak_results = {}
print(" d pL fails / 200,000")
for d in (3, 5):
for pL in (0.0, 1e-4, 1e-3):
noisy = noisy_memory(d, d, SI1000Noise(p=1e-3, pL=pL))
leak_results[d, pL] = count_failures(noisy, 200_000)
print(f"{d:2d} {pL:<8g} {leak_results[d, pL][0]:10d}")d pL fails / 200,000 3 0 730 3 0.0001 1008 3 0.001 3819 5 0 177 5 0.0001 411 5 0.001 3910
fig, ax = plt.subplots()
pLs = [0.0, 1e-4, 1e-3]
for d in (3, 5):
fails = [leak_results[d, pL][0] for pL in pLs]
shots = [leak_results[d, pL][1] for pL in pLs]
lep, err = calculate_lep_and_lep_stddev(fails=fails, shots=shots)
ax.errorbar(range(3), lep, yerr=err, marker="o", capsize=3, label=f"d = {d}")
ax.set_yscale("log")
ax.set_xticks(range(3), ["0", "10⁻⁴", "10⁻³"])
ax.set_xlim(-0.3, 2.3)
ax.set_xlabel("leakage probability pL (SI1000 with p = 10⁻³)")
ax.set_ylabel("logical error probability (d rounds)")
ax.legend()
plt.show()Logical error probability of a d-round SI1000 memory at p = 10⁻³ for three leakage rates pL, 200,000 shots per point, PyMatching built from the leakage-free DEM. At pL = 10⁻³ the d = 5 code is no better than d = 3.
Without leakage, going from
6. True phenomenological noise
PhenomenologicalNoise applies a channel at every I gate, and the memory circuit has one
I layer per round on the data qubits. But compile_and_add_noise_to_circuit compiles the
circuit first, and compilation removes I gates. The workaround skips compilation:
ExhaustiveGateSet() accepts every gate, and add_noise_to_circuit only adds noise.
def phenomenological(p):
return PhenomenologicalNoise(
phenomenological_noise=lambda q: Depolarise1(q, p),
measurement_flip=measurement_noise_profile(p),
)
def phen_memory(d, rounds, p):
circ = css_code_memory_circuit(
RotatedPlanarCode(d, d), num_rounds=rounds, logical_basis=PauliBasis.Z
)
qpu = QPU(circ.qubits, ExhaustiveGateSet(), noise_model=phenomenological(p))
return qpu.add_noise_to_circuit(circ)
circ = css_code_memory_circuit(
RotatedPlanarCode(3, 3), num_rounds=3, logical_basis=PauliBasis.Z
)
compiled = QPU(circ.qubits, noise_model=phenomenological(1e-3))
compiled = compiled.compile_and_add_noise_to_circuit(circ)
print("compiled:", noise_table(compiled.as_stim_circuit()))
print("direct: ", noise_table(phen_memory(3, 3, 1e-3).as_stim_circuit()))compiled: {('M', 0.001): 33}
direct: {('DEPOLARIZE1', 0.001): 27, ('M', 0.001): 9, ('MX', 0.001): 24}
The compiled circuit has measurement flips only. The direct one adds a DEPOLARIZE1 on each
of the 9 data qubits in each of the 3 rounds. With the direct circuit you can test the
textbook claim that matching has a phenomenological threshold near 3% (Lecture 4). Run
phen_results = {}
print(" p d fails / 100,000")
for p in (0.02, 0.04):
for d in (3, 5, 7):
phen_results[p, d] = count_failures(phen_memory(d, d, p), 100_000)
print(f"{p:<6g} {d:2d} {phen_results[p, d][0]:10d}")p d fails / 100,000 0.02 3 3254 0.02 5 1762 0.02 7 928 0.04 3 10481 0.04 5 10990 0.04 7 10915
At
Try this
- Give
ToyNoisea separatep_measurement_flip=5e-3and rerun section 1 at. How close does it come to SI1000? - In section 4, change the noise to
SD6Noise. Which edge class becomes the cheapest?- Rerun the
check on the leaky circuit with pL=1e-3. Which edges disagree with the model now, and in which direction?- Add
and to section 6 and locate the phenomenological crossing more precisely. Why does it drift as grows?