Lecture 7 gives the hypergraph product of two classical check matrices
() and (): ,
and , where ,
, and when . Take .
is the check matrix of the cyclic repetition code (row checks bits
and ). Find and , then and .
is the open repetition code: the first rows of the cyclic one. Find ,
and , and give for and .
is the Hamming code, whose columns are the numbers 1 to 7 in binary,
Find .
For the Hamming product, show directly that no -type operator of weight 1 or 2
commutes with all the checks. (When does a weight-2 vector lie in ?) Then
find a -type logical operator of weight 3.
Compare for the toric code at and for the Hamming product. How many
data qubits would 16 separate distance-3 rotated surface codes need?
Check and with Deltakit’s CSSCode.from_matrix, and your weight-3 operator with
numpy.
Solution
Each row and each column of has two ones. forces neighbouring bits to be
equal, so and . is a cyclic repetition check
matrix too (its row checks bits and ), so . Then
and : the toric code.
Still , so . The rows are independent: the
last row is the only one that touches bit , so no sum of rows that uses it can
vanish; drop it and repeat. So . Hence
, and : the planar surface
code. gives and gives .
The columns 1, 2 and 4 form an identity matrix, so , and
. So , and
: a code.
A -type operator on a set of qubits commutes with every check exactly when the
columns of in add up to zero. One column must then be zero, or two columns must
be equal. Neither happens. Label the rows of
by pairs (check of , bit ). The column of qubit in the left block is
the Hamming column placed at bit : weight 1 to 3, and distinct for distinct
. The column of qubit in the right block is row of placed at check
: weight 4, distinct for distinct . Weights 1 to 3 never equal weight 4, so all
58 columns are distinct and nonzero, and the distance is at least 3. For weight 3,
take a Hamming codeword of weight 3, such as (),
and put it on bit of the left block: on qubits , , ,
which are qubits 0, 7 and 14. It commutes with every check because , and the
code below shows that it is not a product of checks. has the same structure, so
the distance is 3 as well.
Toric, : . Hamming product: .
Sixteen distance-3 rotated patches use data qubits (272 with
ancillas), against 58 (100 with one ancilla per check). The price is distance: the
product of two distance-3 codes is still distance 3, however many qubits it has.
import numpy as npfrom deltakit.explorer.codes import CSSCodedef gf2_rank(m): """Rank over GF(2) by Gaussian elimination on a copy of m.""" a = np.array(m, dtype=np.uint8) % 2 rank = 0 for col in range(a.shape[1]): rows = np.nonzero(a[rank:, col])[0] if rows.size == 0: continue pivot = rank + rows[0] a[[rank, pivot]] = a[[pivot, rank]] hit = np.nonzero(a[:, col])[0] a[hit[hit != rank]] ^= a[rank] rank += 1 if rank == a.shape[0]: break return rankdef hgp(h1, h2): (r1, n1), (r2, n2) = h1.shape, h2.shape hx = np.hstack([np.kron(h1, np.eye(n2, dtype=int)), np.kron(np.eye(r1, dtype=int), h2.T)]) hz = np.hstack([np.kron(np.eye(n1, dtype=int), h2), np.kron(h1.T, np.eye(r2, dtype=int))]) return hx % 2, hz % 2def cyclic(L): return (np.eye(L, dtype=int) + np.roll(np.eye(L, dtype=int), 1, 1)) % 2hamming = np.array([[1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 1]])inputs = {"toric L=6": cyclic(6), "planar L=3": cyclic(3)[:-1], "planar L=4": cyclic(4)[:-1], "Hamming": hamming}for name, h in inputs.items(): hx, hz = hgp(h, h) n = hx.shape[1] k = n - gf2_rank(hx) - gf2_rank(hz) dk = CSSCode.from_matrix(h_x=hx, h_z=hz) print(f"{name:11s} n = {n:2d}, k = {k:2d}, Deltakit k = " f"{dk.calculate_number_of_logical_qubits()}")cols = {tuple(c) for c in hx.T}print("Hamming product: Hx columns distinct", len(cols) == n, " none zero", bool(hx.any(axis=0).all()))z_op = np.zeros(n, dtype=int)z_op[[0, 7, 14]] = 1print("Z on 0, 7, 14: commutes with X checks", not (hx @ z_op % 2).any(), " product of Z checks", gf2_rank(np.vstack([hz, z_op])) == gf2_rank(hz))
toric L=6 n = 72, k = 2, Deltakit k = 2planar L=3 n = 13, k = 1, Deltakit k = 1planar L=4 n = 25, k = 1, Deltakit k = 1Hamming n = 58, k = 16, Deltakit k = 16Hamming product: Hx columns distinct True none zero TrueZ on 0, 7, 14: commutes with X checks True product of Z checks False
Problem 2 (How many qubits a bivariate bicycle code stores).
Let and , where is the
cyclic shift, and let , ,
and , on qubits.
Show that .
Show that and
. Use to show that the two
intersections have the same dimension, and conclude that .
Bravyi et al. list , with the same and as a
code. Check and with BivariateBicycleCode and with part 2.
Count physical qubits (data plus one ancilla per check) needed to store 12 logical qubits
at distance 12: the gross code against 12 rotated surface-code patches of distance 12.
Repeat at distance 6 with , and compute for all four codes.
Name two things that 12 separate surface-code patches give you and one gross-code block
does not.
Solution
, so any two polynomials in and commute, and
. Then, over ,
A matrix with rows has rank minus the dimension of its left kernel. A
row vector kills exactly when and , that is
. For the same argument gives
. Since is a permutation, , so
: the same polynomial in and . Let be
the permutation that sends basis vector to . Then and
, so and , and
has the same dimension. Therefore
Deltakit gives and , and has dimension 4. The
distance 10 is from the paper (PUBLISHED; Bravyi et al.,
Nature 627, 778 (2024); the code is in
Table 3 of arXiv 2308.07915v2). Deltakit 0.10.2 cannot
check it: its one distance routine, compute_graph_distance, needs a matching graph, and a
BB code’s errors are hyperedges (Notebook 7).
A rotated patch of distance uses qubits. Distance 12:
qubits against for the gross code, about 12 times
more. Distance 6: against , about 5.9 times more.
is 1 for every surface-code patch, 12 for the gross code and 6 for
.
Any two of these. Locality: a patch needs only nearest-neighbour couplers on a square
grid, while the gross code needs long-range ones (two planar layers, thickness 2).
Logical gates: each patch can be prepared, measured, moved and merged on its own by
lattice surgery (Lecture 8), while the 12 qubits of a BB block share one set of checks,
so acting on one of them needs extra machinery. Decoding: patches decode with matching;
BB codes need BP+OSD or similar (Lecture 7), which is slower.
from deltakit.explorer.codes import BivariateBicycleCodefor ell, m in ((6, 6), (9, 6), (12, 6)): bb = BivariateBicycleCode(param_l=ell, param_m=m, m_A_powers=[3, 1, 2], m_B_powers=[3, 1, 2]) half = bb.n // 2 a, b = bb.m_Hx[:, :half], bb.m_Hx[:, half:] dim_cap = half - gf2_rank(np.vstack([a, b])) print(f"l={ell:2d}, m={m}: n = {bb.n:3d}, k = {bb.k:2d}, " f"2 dim(ker A & ker B) = {2 * dim_cap}")
l= 6, m=6: n = 72, k = 12, 2 dim(ker A & ker B) = 12l= 9, m=6: n = 108, k = 8, 2 dim(ker A & ker B) = 8l=12, m=6: n = 144, k = 12, 2 dim(ker A & ker B) = 12
Problem 3 (Errors that flip one detector).
Matching needs every error to flip one or two detectors, and Notebook 7 found that most
errors of a BB memory flip more. Here you find the few that flip exactly one. Use
, a -basis memory experiment of rounds from css_code_memory_circuit,
and SI1000Noise(p=1e-3).
With perfect measurements, how many checks does a single error on a data qubit
flip? Is there anything like the boundary of a surface code?
How many detectors sit at , at each , and at ? Why?
Which faults can flip exactly one detector? Predict how many such DEM errors there are
for and 6, and in which rounds they sit. Then count them with Deltakit.
Solution
Every column of has weight 3: each data qubit sits in three checks, so a single
error flips three. The code lives on a torus and every qubit looks the same, so there
is no boundary and no data error with a smaller syndrome.
The data start in , so only the 36 checks have a known value in the first
round: 36 detectors at . Each later round compares all 72 checks with the round
before: 72 detectors at each . The final data readout recomputes the 36
checks (not the checks): 36 detectors at .
A fault that changes one recorded outcome of one check, without touching the data: a
measurement error, or a reset error on the ancilla. Number the rounds .
For an check the detectors are for
. An outcome in the middle appears in two of them. The first outcome
appears only in , and the last, , only in .
These are the single-detector errors:
: no -check detectors at all, so 0;
: both outcomes appear only in . Two faults with identical symptoms
merge into one DEM error, so 36, all at ;
: , at and .
A -check outcome never does this: the first is compared with the known initial value
(), the last with the data readout (), so it is always in two detectors. The
count below agrees, and none of the single-detector errors sits on a check (sites
with a detector at ). These “boundary” errors live at the time boundaries of the
checks, so they do not give matching the spatial boundary it would need.
import collectionsfrom deltakit.circuit.gates import PauliBasisfrom deltakit.explorer.codes import css_code_memory_circuitfrom deltakit.explorer.qpu import QPU, SI1000Noisebb = BivariateBicycleCode(param_l=6, param_m=6, m_A_powers=[3, 1, 2], m_B_powers=[3, 1, 2])qpu = QPU(qubits=bb.qubits, noise_model=SI1000Noise(p=1e-3))print("Z checks per data qubit:", sorted(set(bb.m_Hz.sum(axis=0).tolist())))def one_detector_errors(rounds): """Rounds t of DEM errors that flip one detector; how many on Z checks.""" circ = css_code_memory_circuit(bb, num_rounds=rounds, logical_basis=PauliBasis.Z) noisy = qpu.compile_and_add_noise_to_circuit(circ).as_stim_circuit() coords = noisy.get_detector_coordinates() z_sites = {tuple(c[:2]) for c in coords.values() if c[2] == 0} per_t = collections.Counter(int(c[2]) for c in coords.values()) by_t, on_z = collections.Counter(), 0 dem = noisy.detector_error_model(decompose_errors=False) for err in dem.flattened(): dets = [t.val for t in err.targets_copy() if t.is_relative_detector_id()] if err.type == "error" and len(dets) == 1: x, y, t = coords[dets[0]] by_t[int(t)] += 1 on_z += (x, y) in z_sites return dict(sorted(per_t.items())), dict(sorted(by_t.items())), on_zprint("detectors per t at r = 3:", one_detector_errors(3)[0])for rounds in (1, 2, 3, 6): _, by_t, on_z = one_detector_errors(rounds) print(f"r = {rounds}: {sum(by_t.values()):2d} errors, by t {by_t}," f" on Z checks {on_z}")
Z checks per data qubit: [3]detectors per t at r = 3: {0: 36, 1: 72, 2: 72, 3: 36}r = 1: 0 errors, by t {}, on Z checks 0r = 2: 36 errors, by t {1: 36}, on Z checks 0r = 3: 72 errors, by t {1: 36, 2: 36}, on Z checks 0r = 6: 72 errors, by t {1: 36, 5: 36}, on Z checks 0
Problem 4 (The lattice-surgery seam).
Lecture 8’s figure shows the seam of a merge of two distance-3 patches: patch
1’s boundary column, a bridge column prepared in , and patch 2’s boundary column,
each with 3 qubits (rows 0, 1, 2 from the top). Between the columns sit four new checks:
a square on rows 1–2 left of the bridge, a square on rows 0–1 right of it, a weight-2 cap on
row 0 left of it and a cap on row 2 right of it. Two squares fill the remaining places.
Lecture 8 and the field map’s lattice-surgery card state the answers to parts 1, 2 and 4;
derive them yourself before you look, then do part 3 for any .
Show that the product of the four new checks is .
In the first merged round, why is each new check a random even when the two
patches hold a eigenstate? Why is the squares’ outcome predictable?
Extend the pattern to odd distance (squares alternate , down each side of the
bridge, out of step on the two sides). How many new checks, squares and bridge
qubits are there? Check the product for .
Why is the merged patch measured for rounds rather than once?
Solution
Name the qubits (column, row) with column 0 = patch 1, 1 = bridge, 2 = patch 2. The four
checks cover , ,
and . Each bridge qubit is in two of them (row 0: the
right square and the top cap; row 1: both squares; row 2: the left square and the bottom
cap), so its cancels in the product. Each boundary qubit is in exactly one. The
product is on all of column 0 times on all of column 2, and a column of s
along that boundary is for each patch.
The bridge starts in , which is stabilized by on each bridge
qubit. Every new check contains on one or two bridge qubits, so it anticommutes
with one of those s and its first outcome is uniformly random. The product contains no
bridge , commutes with all of them, and gives the value of . Each
square is an old weight-2 boundary check of one patch times on two bridge qubits,
which read on ; so it repeats the old check’s value and can be compared
with it, as a detector.
Down each side there are squares, half of each type; the two caps close the ends.
So new checks, squares and bridge qubits. For
that is 4, 2 and 3. The code below builds the checks and confirms that the
product is the two boundary columns, every bridge qubit sits in two checks, and every
square meets every check in an even number of qubits.
A single misread new check flips the inferred . Repeating the merged
checks for rounds and decoding them like a memory experiment makes it take about
faults to fool the result, which matches the spatial distance. This is why each
lattice-surgery step costs about syndrome cycles.
def seam(d): """New Z checks and X squares of a ZZ merge; qubits are (column, row).""" z, x = [], [] for r in range(d - 1): left = {(0, r), (1, r), (0, r + 1), (1, r + 1)} right = {(1, r), (2, r), (1, r + 1), (2, r + 1)} (z if r % 2 else x).append(left) (x if r % 2 else z).append(right) z += [{(0, 0), (1, 0)}, {(1, d - 1), (2, d - 1)}] # the two caps return z, xfor d in (3, 5, 7): z, x = seam(d) product = set() for check in z: product ^= check boundary = {(c, r) for c in (0, 2) for r in range(d)} per_bridge = {sum((1, r) in c for c in z) for r in range(d)} commute = all(len(a & b) % 2 == 0 for a in z for b in x) print(f"d={d}: Z checks {len(z)}, X squares {len(x)}, bridge in" f" {per_bridge}, product ok {product == boundary}," f" commute {commute}")
d=3: Z checks 4, X squares 2, bridge in {2}, product ok True, commute Trued=5: Z checks 6, X squares 4, bridge in {2}, product ok True, commute Trued=7: Z checks 8, X squares 6, bridge in {2}, product ok True, commute True
Problem 5 (A detector that is the logical).
Lecture 8 compiled a three-round memory of the three-qubit repetition code: data on qubits 0,
2, 4, ancilla 1 checks and ancilla 3 checks . The circuit ends like this:
Name the five measurements behind rec[-1] to rec[-5] at the end of the circuit, and
write each of the last three detectors as a parity of last-round ancilla outcomes ,
and data outcomes , , .
Earlier rounds add a detector (round 1) and (each later round
against the one before) for . Show that the observable is the XOR of all
nine detectors. Conclude that an error flips the observable exactly when it flips an odd
number of detectors, and that any decoder whose correction reproduces the syndrome is
never wrong.
How many detectors should an -round memory of this code have, and how many does the
compiler emit? Check with Deltakit for to 4, and test the claim of part 2 on the
noisy circuit, with and without the last detector.
Lecture 8 measured 0 failures in 100,000 shots at for the compiled circuit and
4397 without its last detector. Which number estimates the memory’s logical error rate?
What does shortest_graphlike_error() return for each noisy circuit?
Solution
M 0 2 4 is the last measurement, so rec[-1], rec[-2], rec[-3] are , ,
, and the M 1 3 before it gives rec[-4] and rec[-5]. The
detectors are (ancilla 1 against the data it checked),
(the same for ancilla 3), and alone.
Each chain XORs to the last-round outcome
, which also appears in one final detector, so all ancilla outcomes cancel. What is
left is from the first final detector, from the second
and from the third: , the observable. This is an identity between measurement
records, so it holds whatever the errors are: an error flips the observable exactly when
it flips an odd number of detectors. A decoder’s correction has the same syndrome as the
true error, so it flips the observable the same way, and the prediction is always right.
The decoder does nothing clever: the observable has leaked into the detectors.
All measurements are deterministic (everything starts in ), so their
parities form a space of dimension . The observable is one direction in that
space, and the detectors may span at most the rest: independent detectors, 8 for
. With one more, the observable becomes a sum of detectors, as in part 2. The
compiler emits (5, 7, 9, 11 for to 4), one too many. In the noisy
circuit every one of the 21 DEM errors passes the parity test; drop the last detector and
4 of the 21 fail it.
4397 in 100,000, about . The zero comes from a decoder that reads off the
detectors, not from good protection. Stim says the same thing. On the compiled circuit
shortest_graphlike_error() raises
ValueError: Failed to find any graphlike logical errors., because no set of errors flips
the observable silently; without the last detector it returns 3 errors, the distance of
the code.
import deltakit_stim as stimfrom deltakit.circuit import Circuitfrom deltakit_compile.frontend.common import CircuitBuilder, QubitRegfrom deltakit_compile.frontend.logasm import LogAsmBuilderfrom deltakit_compile.frontend.logical_assembler import ( LogicalAssembler, LogicalAssemblerConfig)from deltakit_compile.passes.stim.stim_export.pipeline import ( StimExportPipelineConfig)assembler = LogicalAssembler( LogicalAssemblerConfig(export_config=StimExportPipelineConfig()))def repetition_memory(rounds): """Compile a 3-qubit repetition memory (data 0, 2, 4) to Stim.""" prep = CircuitBuilder() q = prep.add_arg(QubitReg(5)) prep.gate("RZ", q) check = CircuitBuilder() q = check.add_arg(QubitReg(5)) check.gate("RZ", (q[1], q[3])) for ctrl, targ in ((0, 1), (2, 1), (2, 3), (4, 3)): check.gate("CX", (q[ctrl], q[targ])) check.add_return(check.measure("Z", (q[1], q[3]))) readout = CircuitBuilder() q = readout.add_arg(QubitReg(5)) m = readout.measure("Z", (q[0], q[2], q[4])) obs = readout.declare_observable() obs.include([m[0]]) readout.add_return(obs.get_corrected()) prep, check = prep.build("prep"), check.build("zz_round") readout = readout.build("readout") lb = LogAsmBuilder() reg = lb.declare_patch(QubitReg(5)) lb.call_circuit(prep(reg)) for _ in range(rounds): lb.call_circuit(check(reg)) lb.add_return(lb.call_circuit(readout(reg))) return stim.Circuit(assembler.compile(lb.build_program()).program)def noisy(circ, p=1e-3): dk = Circuit.from_stim_circuit(circ) qpu = QPU(qubits=dk.qubits, noise_model=SI1000Noise(p=p)) return qpu.compile_and_add_noise_to_circuit(dk).as_stim_circuit()def parity_violations(circ): """DEM errors whose observable flip differs from their detector parity.""" dem = noisy(circ).detector_error_model(decompose_errors=False) errs = [e.targets_copy() for e in dem.flattened() if e.type == "error"] bad = sum(sum(t.is_relative_detector_id() for t in ts) % 2 != sum(t.is_logical_observable_id() for t in ts) % 2 for ts in errs) return f"{bad} of {len(errs)} errors"for rounds in (1, 2, 3, 4): c = repetition_memory(rounds) print(f"r = {rounds}: {c.num_measurements} measurements," f" {c.num_detectors} detectors, {c.num_observables} observable")rep = repetition_memory(3)last = max(i for i, ins in enumerate(rep) if ins.name == "DETECTOR")trimmed = stim.Circuit()for i, ins in enumerate(rep): if i != last: trimmed.append(ins)for name, c in (("compiled", rep), ("trimmed", trimmed)): try: short = len(noisy(c).shortest_graphlike_error()) except ValueError: short = "ValueError" print(f"{name}: parity fails {parity_violations(c)};" f" shortest graphlike error {short}")