About this notebook
Companion to Lecture 7: qLDPC and bivariate bicycle codes. 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 7 introduced the bivariate bicycle (BB) codes
- Build both codes and look at the check matrix
. - Count how many detectors each circuit-level error flips, for a BB code and a surface code.
- Watch PyMatching refuse the BB circuit.
- Write min-sum belief propagation (BP) and ordered-statistics decoding (OSD-0) in numpy.
- Decode both codes under code-capacity noise (independent
errors on data qubits, perfect syndromes), with BP alone and BP followed by OSD.
The decoder is about forty lines and decodes 3,000 shots of the gross code in a few seconds. It is a teaching decoder: it ignores measurement errors, which is what a real BB decoder spends most of its effort on.
import collections
import deltakit
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.explorer.codes import (
BivariateBicycleCode,
RotatedPlanarCode,
css_code_memory_circuit,
)
from deltakit.explorer.qpu import QPU, SI1000Noise
set_matplotlib_formats("svg")
SEED = 2026
print("deltakit", deltakit.__version__)deltakit 0.10.2
1. Two BB codes
BivariateBicycleCode(param_l, param_m, m_A_powers, m_B_powers) builds the code with
def gf2_rref(a):
"""Row-reduce a copy of a over GF(2). Returns (nonzero rows, pivot columns)."""
a = (np.array(a, dtype=np.uint8) % 2).copy()
rows, cols = a.shape
pivots, r = [], 0
for c in range(cols):
if r == rows:
break
nz = np.nonzero(a[r:, c])[0]
if nz.size == 0:
continue
p = r + nz[0]
a[[r, p]] = a[[p, r]]
others = np.nonzero(a[:, c])[0]
a[others[others != r]] ^= a[r]
pivots.append(c)
r += 1
return a[:r], pivots
def gf2_rank(a):
return len(gf2_rref(a)[1])
codes = {
"[[72,12,6]]": BivariateBicycleCode(param_l=6, param_m=6,
m_A_powers=[3, 1, 2], m_B_powers=[3, 1, 2]),
"[[144,12,12]]": BivariateBicycleCode(param_l=12, param_m=6,
m_A_powers=[3, 1, 2], m_B_powers=[3, 1, 2]),
}
for name, code in codes.items():
hx, hz = code.m_Hx, code.m_Hz
print(f"{name}: n = {code.n}, Hx {hx.shape}, Hz {hz.shape}, "
f"rank Hx = {gf2_rank(hx)}, rank Hz = {gf2_rank(hz)}, "
f"k = n - ranks = {code.n - gf2_rank(hx) - gf2_rank(hz)}")[[72,12,6]]: n = 72, Hx (36, 72), Hz (36, 72), rank Hx = 30, rank Hz = 30, k = n - ranks = 12 [[144,12,12]]: n = 144, Hx (72, 144), Hz (72, 144), rank Hx = 66, rank Hz = 66, k = n - ranks = 12
Six checks of each type are redundant (rank 30 of 36, and 66 of 72): products of other
checks. Without that redundancy
Picture the matrix. Each row is one
hx72 = codes["[[72,12,6]]"].m_Hx
fig, ax = plt.subplots(figsize=(6.4, 3.8))
ax.imshow(hx72, cmap="Greys", interpolation="nearest", aspect="equal")
ax.axvline(35.5, color="#c06318", linewidth=1.5)
ax.set_xticks([0, 12, 24, 36, 48, 60, 71])
ax.set_yticks([0, 12, 24, 35])
for x, block in ((17.5, "A"), (53.5, "B")):
ax.text(x, -1.5, block, ha="center", va="bottom", fontsize=11, color="#c06318")
ax.set_xlabel("data qubit")
ax.set_ylabel("X check")
ax.grid(False)
plt.show()The X-check matrix Hx = [A | B] of the [[72,12,6]] code: 36 checks (rows) by 72 data qubits (columns), dark cells are 1. Every row has three 1s in each block, and every column has three 1s in total. The diagonal stripes are the cyclic shifts x and y.
2. How many detectors does one error flip?
Matching needs every error to flip at most two detectors (Lecture 5). Build a 6-round memory
experiment for
def noisy_memory(code, rounds, p=1e-3):
circ = css_code_memory_circuit(code, num_rounds=rounds, logical_basis=PauliBasis.Z)
qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=p))
return qpu.compile_and_add_noise_to_circuit(circ)
def symptoms(noisy):
"""Counter: number of detectors flipped -> number of DEM error mechanisms."""
dem = noisy.as_stim_circuit().detector_error_model(decompose_errors=False)
count = collections.Counter()
for inst in dem.flattened():
if inst.type == "error":
count[sum(t.is_relative_detector_id() for t in inst.targets_copy())] += 1
return count
bb_noisy = noisy_memory(codes["[[72,12,6]]"], rounds=6)
surface_noisy = noisy_memory(RotatedPlanarCode(7, 7), rounds=7)
hist = {
"surface code d = 7, 7 rounds": symptoms(surface_noisy),
"BB [[72,12,6]], 6 rounds": symptoms(bb_noisy),
}
for name, count in hist.items():
total = sum(count.values())
big = sum(v for k, v in count.items() if k > 2)
print(f"{name}: {total} mechanisms, {big} flip more than two detectors "
f"({big / total:.0%})")surface code d = 7, 7 rounds: 6289 mechanisms, 4069 flip more than two detectors (65%) BB [[72,12,6]], 6 rounds: 17244 mechanisms, 16668 flip more than two detectors (97%)
fig, ax = plt.subplots()
ks = np.arange(1, 10)
for shift, (name, count) in zip((-0.2, 0.2), hist.items()):
total = sum(count.values())
ax.bar(ks + shift, [count.get(k, 0) / total for k in ks], width=0.4, label=name)
ax.axvline(2.5, color="#81796f", linestyle="--", linewidth=1)
ax.text(2.4, 0.48, "matching\nhandles", ha="right", va="top", fontsize=9, color="#81796f")
ax.set_xticks(ks)
ax.set_ylim(0, 0.5)
ax.set_xlabel("detectors flipped by one error mechanism")
ax.set_ylabel("fraction of mechanisms")
ax.legend(loc="upper right")
plt.show()Fraction of error mechanisms in the undecomposed detector error model, by the number of detectors each flips (SI1000, p = 0.001). Surface-code mechanisms with 3 or 4 detectors combine an X-type and a Z-type part (Y errors, two-qubit gate errors), and Stim splits them into pairs; most BB mechanisms flip 3 to 9 detectors and cannot be split.
3. Matching gives up
Asking for a matching decoder makes Stim try to split every mechanism into pieces of at most two detectors. For the BB circuit it cannot, and says which mechanism broke it: a single fault that flips nine detectors and four of the twelve logical observables.
PyMatchingDecoder.construct_decoder_and_stim_circuit(bb_noisy)… (traceback shortened)
105 stim_circuit = circuit.as_stim_circuit()
--> 106 graph, logicals, stim_circuit = parse_stim_circuit(stim_circuit)
107 return cls(graph, logicals), stim_circuit
File <repo>/.venv/lib/python3.12/site-packages/deltakit_decode/utils/_graph_circuit_helpers.py:77, in parse_stim_circuit(stim_circuit, trim_circuit, lexical_detectors)
74 circuit.reorder_detectors()
75 stim_circuit = circuit.as_stim_circuit()
---> 77 dem = stim_circuit_to_graph_dem(stim_circuit)
78 graph, logicals = dem_to_decoding_graph_and_logicals(dem)
80 if trim_circuit:
File <repo>/.venv/lib/python3.12/site-packages/deltakit_decode/utils/_graph_circuit_helpers.py:38, in stim_circuit_to_graph_dem(stim_circuit, approximate_disjoint_errors)
35 DemParser(detector_counter, lambda *_: None).parse(dem)
37 if detector_counter.max_num_detectors() > 2:
---> 38 dem = stim_circuit.detector_error_model(
39 decompose_errors=True,
40 approximate_disjoint_errors=approximate_disjoint_errors,
41 )
43 return dem
ValueError: Failed to decompose errors into graphlike components with at most two symptoms.
The error component that failed to decompose is 'D324, D325, D330, D347, D356, D368, D381, D390, D419, L3, L7, L10, L11'.
In Python, you can ignore this error by passing `ignore_decomposition_failures=True` to `stim.Circuit.detector_error_model(...)`.
From the command line, you can ignore this error by passing the flag `--ignore_decomposition_failures` to `stim analyze_errors`.
Circuit stack trace:
during TICK layer #61 of 72
at instruction #222 [which is a REPEAT 4 block]
Deltakit's own BP-OSD
deltakit.decode.BPOSDecoderexists, but in Deltakit 0.10.2 it runs on Riverlane’s cloud service: without aclientit raisesNotImplementedError. Here we write our own, for the simpler code-capacity problem.
4. Belief propagation and OSD in numpy
Under code-capacity noise each data qubit suffers an
variables (qubits) e0 e1 e2 e3 e4 ... e71
| \ | / | \ | / |
checks (Z stabilizers) s0 s1 s2 ... s35
messages: variable -> check : "how likely am I flipped, ignoring you"
check -> variable : "given the others, how likely are you flipped"Messages are log-likelihood ratios
The class below runs all shots at once. The trick is to number the edges, then keep two index arrays: the edges of each check (shape checks x 6) and the edges of each qubit (qubits x 3).
class MinSumBP:
"""Normalised min-sum BP for a 0/1 check matrix with constant row and column weight."""
def __init__(self, h, alpha=0.625, iters=30):
self.h = h.astype(np.uint8)
m, n = h.shape
rows, cols = np.nonzero(h) # edges, sorted by check
self.cols = cols
self.chk = np.arange(len(rows)).reshape(m, -1) # edge ids of each check
self.var = np.argsort(cols, kind="stable").reshape(n, -1) # edge ids of each qubit
self.alpha, self.iters = alpha, iters
def decode(self, synd, p):
shots, n = synd.shape[0], self.h.shape[1]
prior = np.log((1 - p) / p)
q = np.full((shots, self.cols.size), prior) # variable -> check messages
ssign = 1 - 2 * synd.astype(np.int8) # +1 if the check is quiet, -1 if it fired
done = np.zeros(shots, dtype=bool)
ehat = np.zeros((shots, n), dtype=np.uint8)
post = np.full((shots, n), prior)
for _ in range(self.iters):
qc = q[:, self.chk] # (shots, checks, 6)
sgn = np.where(qc < 0, -1, 1)
total_sign = sgn.prod(axis=2, keepdims=True) * ssign[:, :, None]
mag = np.abs(qc)
i1 = mag.argmin(axis=2)[:, :, None] # position of the smallest magnitude
m1 = np.take_along_axis(mag, i1, 2)
np.put_along_axis(mag, i1, np.inf, 2)
m2 = mag.min(axis=2, keepdims=True) # second smallest
excl = np.where(np.arange(qc.shape[2]) == i1, m2, m1) # min over the others
r = np.empty_like(q)
r[:, self.chk] = self.alpha * total_sign * sgn * excl # check -> variable
post_new = prior + r[:, self.var].sum(axis=2)
hard = (post_new < 0).astype(np.uint8)
ok = ((hard @ self.h.T) % 2 == synd).all(axis=1)
ehat[~done], post[~done] = hard[~done], post_new[~done]
done |= ok
if done.all():
break
q = post_new[:, self.cols] - r # leave out what the check itself said
return ehat, post, doneWhen BP does not converge, its final beliefs are still useful: they rank the qubits from
“most likely flipped” to “least likely”. OSD-0 takes that ranking, picks the first set of
columns of
def osd0(h, synd, llr):
"""OSD-0: solve h e = synd on the most-likely-flipped information set."""
order = np.argsort(llr, kind="stable") # most likely flipped first
a, b = h[:, order].copy(), synd.copy()
m, n = a.shape
pivots, r = [], 0
for c in range(n):
if r == m:
break
nz = np.nonzero(a[r:, c])[0]
if nz.size == 0:
continue
p = r + nz[0]
a[[r, p]], b[[r, p]] = a[[p, r]], b[[p, r]]
others = np.nonzero(a[:, c])[0]
others = others[others != r]
a[others] ^= a[r]
b[others] ^= b[r]
pivots.append(c)
r += 1
x = np.zeros(n, dtype=np.uint8)
x[pivots] = b[:r]
e = np.zeros(n, dtype=np.uint8)
e[order] = x
return eTo judge a correction we need the
def gf2_nullspace(a):
rref, pivots = gf2_rref(a)
n = a.shape[1]
free = [c for c in range(n) if c not in pivots]
basis = np.zeros((len(free), n), dtype=np.uint8)
for i, f in enumerate(free):
basis[i, f] = 1
for r, pc in enumerate(pivots):
basis[i, pc] = rref[r, f]
return basis
def z_logicals(hx, hz):
"""A basis of ker(hx) modulo rowspace(hz)."""
chosen, current = [], hz.astype(np.uint8)
for v in gf2_nullspace(hx):
trial = np.vstack([current, v])
if gf2_rank(trial) > gf2_rank(current):
chosen.append(v)
current = trial
return np.array(chosen, dtype=np.uint8)
lz = {name: z_logicals(c.m_Hx, c.m_Hz) for name, c in codes.items()}
for name, ops in lz.items():
print(f"{name}: {ops.shape[0]} Z logicals, weights {sorted(ops.sum(axis=1).tolist())}")[[72,12,6]]: 12 Z logicals, weights [6, 6, 6, 6, 6, 6, 8, 14, 16, 18, 20, 20] [[144,12,12]]: 12 Z logicals, weights [12, 12, 12, 12, 12, 12, 12, 24, 28, 34, 36, 38]
The lightest of these happen to have weight 6 and 12, the two codes’ distances, but row reduction promises nothing of the kind: the distance is the minimum weight over all logicals, products included, and finding it is a hard search. For counting failures any basis will do.
5. Decoding under code-capacity noise
For each
def run(name, ps, shots, rng, alpha=0.625):
code = codes[name]
hz = code.m_Hz.astype(np.uint8)
bp = MinSumBP(hz, alpha=alpha)
rows = []
for p in ps:
err = (rng.random((shots, code.n)) < p).astype(np.uint8)
synd = (err @ hz.T) % 2
ehat, post, conv = bp.decode(synd, p)
bp_wrong = (((ehat ^ err) @ lz[name].T) % 2).any(axis=1)
for i in np.nonzero(~conv)[0]:
ehat[i] = osd0(hz, synd[i], post[i])
osd_wrong = (((ehat ^ err) @ lz[name].T) % 2).any(axis=1)
rows.append(dict(p=p, conv=conv, bp_fail=~conv | bp_wrong, osd_fail=osd_wrong))
return rows
ps = [0.02, 0.04, 0.06, 0.08, 0.10]
shots = 3000
results = {
"[[72,12,6]]": run("[[72,12,6]]", ps, shots, np.random.default_rng(SEED)),
"[[144,12,12]]": run("[[144,12,12]]", ps, shots, np.random.default_rng(SEED + 1)),
}
print(f"{'code':14s} {'p':>5s} {'BP converged':>13s} {'BP-only fails':>14s} "
f"{'BP+OSD fails':>13s}")
for name, rows in results.items():
for r in rows:
print(f"{name:14s} {r['p']:5.2f} {r['conv'].mean():13.3f} "
f"{r['bp_fail'].sum():14d} {r['osd_fail'].sum():13d}")code p BP converged BP-only fails BP+OSD fails [[72,12,6]] 0.02 0.987 48 35 [[72,12,6]] 0.04 0.920 329 271 [[72,12,6]] 0.06 0.779 924 792 [[72,12,6]] 0.08 0.622 1533 1363 [[72,12,6]] 0.10 0.455 2195 2032 [[144,12,12]] 0.02 0.992 23 9 [[144,12,12]] 0.04 0.938 190 65 [[144,12,12]] 0.06 0.742 789 397 [[144,12,12]] 0.08 0.440 1708 1123 [[144,12,12]] 0.10 0.200 2438 1958
fig, ax = plt.subplots()
pa = np.array(ps)
for name, rows in results.items():
for key, style, label in (("bp_fail", "--", "BP only"),
("osd_fail", "-", "BP + OSD-0")):
f = np.array([r[key].mean() for r in rows])
err = np.sqrt(f * (1 - f) / shots)
color = "#2d62a0" if name == "[[72,12,6]]" else "#c06318"
ax.errorbar(pa, f, yerr=err, linestyle=style, marker="o", capsize=3, color=color,
label=f"{name}, {label}")
ax.plot(pa, 1 - (1 - pa) ** 12, ":", color="#81796f", label="12 bare qubits")
ax.set_yscale("log")
ax.set_xlabel("X-error probability per qubit, p")
ax.set_ylabel("logical failure rate")
ax.legend(loc="lower right")
plt.show()Fraction of 3,000 code-capacity shots with a logical failure, against the X-error probability p per qubit, for BP alone (dashed) and BP followed by OSD-0 (solid). Error bars are one binomial standard deviation. The dotted line is the chance that at least one of 12 unprotected qubits flips.
What the numbers say:
- OSD matters more for the bigger code. At
, OSD cuts the gross code’s failures from 190 to 65 in 3,000, but ‘s only from 329 to 271. BP on a quantum code often fails to converge: many different errors share a syndrome, and the beliefs split between them. OSD turns those undecided beliefs into a valid correction, which is right most of the time. - The gross code wins clearly at low
, barely at high . Doubling at fixed doubles the distance, and at the gross code fails 9 times against 35. By both codes fail on about two shots in three. - With OSD, both codes beat twelve bare qubits at every
on the plot. BP alone does not at .
Code capacity is the easy problem. Under circuit noise the decoder sees every detector of
every round (432 for six rounds of
Try this
- Run
run("[[72,12,6]]", [0.04, 0.08], 2000, np.random.default_rng(SEED), alpha=1.0)and compare how often BP converges with the default. - Count how many of the gross code’s shots at
BP gets wrong after converging: results["[[144,12,12]]"][2], combiningconvandbp_fail. Those are failures OSD never sees.- Build the
code, BivariateBicycleCode(9, 6, [3, 1, 2], [3, 1, 2]), add it tocodesandlz, and put it on the plot.- Change
itersinMinSumBPfrom 30 to 100. Does BP converge more often, and does the BP + OSD curve move?