A distance- rotated surface code stores one logical qubit in data qubits, plus ancillas to measure its checks. At that is 287 physical qubits for a single logical qubit. The surface code is popular because its checks are local and it can be decoded by matching (Lecture 5), not because it is frugal. Its rate, logical qubits per physical qubit, goes to zero as the code grows.

Quantum low-density parity-check (qLDPC) codes keep the property that matters for hardware, checks that touch only a few qubits, and drop the requirement that those qubits be neighbours on a flat grid. In exchange they encode many logical qubits per block. The best-known example is the gross code , which stores 12 logical qubits in 144 data qubits. Its authors estimate that, at a physical error rate of , it keeps all 12 logical qubits for nearly a million syndrome cycles using 288 physical qubits in total, where the surface code would need nearly 3,000 qubits for the same protection (PUBLISHED; Bravyi et al., Nature 627, 778 (2024), arXiv 2308.07915; these are simulations with a circuit-level noise model, not a device). This lecture builds such codes, shows why matching cannot decode them, and says what Deltakit 0.10.2 offers instead.

Notebook and field map

Notebook 7: Bivariate bicycle codes builds the and gross codes, counts how many detectors each circuit error flips, watches matching refuse them, and decodes code-capacity noise with a home-made BP+OSD decoder. Field map: CSS codes and the binary picture, Hypergraph product codes, Bivariate bicycle codes, Belief propagation and BP-OSD, From DEM to decoding graph.

Rate, distance and overhead

Everything in this lecture is a CSS code (Lecture 1): -type checks are the rows of a binary matrix , -type checks are the rows of , both with columns, one per data qubit. The checks commute exactly when over , and the number of logical qubits is .

Definition 7.1 (qLDPC code family).

A family of CSS codes is quantum low-density parity-check (qLDPC) if there are constants and such that every code in the family has checks of weight at most and every qubit in at most checks: every row and column of and stays sparse as grows.

The surface code is qLDPC by Definition 7.1 (, ). What it lacks is rate. A useful figure of merit is : how many logical qubits you get, weighted by how well they are protected, per data qubit. For the rotated and toric codes it is exactly 1 (about ½ for the unrotated planar code). That is not bad luck.

Theorem 7.1 (Bravyi–Poulin–Terhal bound).

For any family of stabilizer codes whose checks are local on a two-dimensional grid (each check acts on qubits within a fixed distance of each other), .

So by Theorem 7.1 no code with short-range checks on a flat grid beats the surface code by more than a constant factor in : to do better, some checks must reach across the chip. In the table, counts data qubits; the last column adds one ancilla per check, as Deltakit’s memory circuits do.

codequbits with ancillas
rotated surface code, 1287
toric code, 1144
hypergraph product of two Hamming codes2.5100
bivariate bicycle6144
bivariate bicycle (gross code)12288
bivariate bicycle13.5576

Twelve logical qubits at distance 12 cost physical qubits as surface-code patches and 288 as one gross-code block. (The “nearly 3,000” above compares equal logical error rates, the fairer test.) The BB distances are from Bravyi et al.; the homework recomputes , and the ratios.

Hypergraph products

How do you build a quantum code with many logical qubits and low-weight checks? The first general answer took two good classical codes and multiplied them.

Definition 7.2 (Hypergraph product).

Let () and () be classical parity-check matrices. Their hypergraph product is the CSS code on qubits with

Theorem 7.2 (Parameters of a hypergraph product).

The checks of Definition 7.2 commute, and the code has logical qubits, where and . Its distance is , where is the distance of the code with check matrix (infinite if that code is empty).

The commutation is one line: by the mixed-product rule, over . Each check weight is a row weight plus a column weight of the classical matrices, so sparse inputs give a sparse quantum code. Tillich and Zémor prove the count of in Theorem 7.2.

Example 7.1 (The toric code is a hypergraph product).

Take the check matrix of the cyclic repetition code, whose row checks bits and . Then (the all-ones vector), so , and . The two blocks of columns are the horizontal and vertical edges of an torus, and the rows of and are its stars and plaquettes: this is Kitaev’s toric code. With the open repetition code (, so ) you get the planar surface code instead.

The code below checks Example 7.1 numerically for . It builds the product with numpy.kron, counts logical qubits from ranks, and hands the matrices to Deltakit’s generic CSSCode.from_matrix, which accepts any pair of commuting check matrices.

import numpy as np
from deltakit.explorer.codes import CSSCode
 
 
def 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 rank
 
 
def 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 % 2
 
 
L = 4
rep = (np.eye(L, dtype=int) + np.roll(np.eye(L, dtype=int), 1, axis=1)) % 2
hx, hz = hgp(rep, rep)
n = hx.shape[1]
print("n =", n, "  Hx", hx.shape, "  Hz", hz.shape)
print("Hx Hz^T = 0:", not ((hx @ hz.T) % 2).any())
print("check weights", sorted(set(hx.sum(1).tolist())),
      "  checks per qubit", sorted(set(hx.sum(0).tolist())))
print("k from ranks:", n - gf2_rank(hx) - gf2_rank(hz))
toric = CSSCode.from_matrix(h_x=hx, h_z=hz)
print("k from Deltakit:", toric.calculate_number_of_logical_qubits())
n = 32   Hx (16, 32)   Hz (16, 32)
Hx Hz^T = 0: True
check weights [4]   checks per qubit [2]
k from ranks: 2
k from Deltakit: 2

Hypergraph products have constant rate whenever the classical inputs do: feed in two good classical LDPC codes with and you get . Their weakness is distance. Because grows like the product of the classical lengths while is at most the classical distance, . The product of two Hamming codes has but distance only 3. The homework explores this trade.

Bivariate bicycle codes

Bivariate bicycle (BB) codes give up the product structure for a cheaper trick: build and from two matrices that commute, so that the checks commute automatically.

Definition 7.3 (Bivariate bicycle code).

Let be the cyclic shift matrix, and set and , two commuting permutation matrices of size with . Pick and as sums of three powers of and . The bivariate bicycle code is the CSS code on qubits with

The gross code uses , , and ; the same and with give .

Commutation is immediate: , because all powers of and commute. Every check has weight 6 (three ones from , three from ) and every qubit is in three checks and three checks, so Definition 7.3 gives a qLDPC family. Bravyi et al. show that , and they found the good choices of and by computer search. On the torus of qubit pairs, and reach one and two steps along one direction and three steps along the other: short jumps on the torus. A torus is not a flat grid, though. Laid out on a chip, some of these links become long, and links that do not stay short as the codes grow are what lets a family beat Theorem 7.1.

The jumps are buildable: Bravyi et al. show that the gross code’s connectivity graph splits into two planar graphs of degree 3 (thickness 2), so two layers of couplers suffice, and that a syndrome cycle needs only 7 layers of CNOTs, whatever the code length. Under a standard circuit-level noise model with BP-OSD decoding they find a threshold of about (PUBLISHED, same paper; the arXiv abstract says , and version 2 of the arXiv paper revised the numerical results after a simulation bug was fixed). IBM’s public roadmap builds its planned 2029 fault-tolerant machine, Starling, on BB codes, with a target of 200 logical qubits and gates (VENDOR; IBM Quantum blog, 2025-06-10).

Decoding without matching

A matching decoder (Lecture 5) works on a graph: detectors are nodes, and each error mechanism is an edge between the one or two detectors it flips. That is why Lecture 4 asked Stim to decompose the detector error model into edges.

In the surface code every data qubit sits in at most two checks, so an error lights at most two of them: an edge. In a BB code every data qubit sits in three checks, so the same error lights three: a hyperedge, which no combination of edges in the model reproduces (see the figure). With repeated rounds one fault can light up to nine detectors.

surface code bivariate bicycle code Z check Z check X error lights 2 checks: an edge matching can pair them Z check Z check Z check X error lights 3 checks: a hyperedge no pair of edges gives the same pattern

Decoders for qLDPC codes work on the Tanner graph instead: one node per error mechanism (per qubit, for code-capacity noise), one node per check, and an edge whenever the mechanism flips the check. A hyperedge is just a mechanism node of degree three or more.

Definition 7.4 (Belief propagation).

Belief propagation (BP) estimates, for each error mechanism, the probability that it occurred given the syndrome. Each mechanism starts from its prior, written as a log-likelihood ratio . Then messages alternate: each mechanism tells each of its checks how likely it is to have fired, judging from its prior and its other checks; each check tells each of its mechanisms how likely it is to have fired, given the syndrome bit and the other mechanisms. After each round, flip every mechanism whose total belief is below zero, and stop if those flips reproduce the syndrome.

BP is exact on a tree, costs time linear in the number of edges per round, and parallelises well, so it is the starting point for real-time qLDPC decoding. On quantum codes it has two problems. Short cycles in the Tanner graph echo messages back to their source. Worse, quantum codes are degenerate: corrections that differ by a stabilizer are equally good. Facing two equally likely minimal corrections, BP splits its belief between them, the hard decision matches neither, and BP never converges.

Definition 7.5 (Ordered statistics decoding).

Ordered statistics decoding (OSD) post-processes BP’s output when BP fails. Sort the error mechanisms from most to least likely according to BP. Walking down that list, keep the first columns of the check matrix that are linearly independent over , and solve for those mechanisms exactly, with all others set to zero. The result always reproduces the syndrome. OSD-0 stops there; higher orders also try flipping a few of the remaining mechanisms and keep the most likely solution.

BP+OSD (Definition 7.4 followed by Definition 7.5) is the decoder behind the gross-code numbers above (introduced by Panteleev and Kalachev, made standard by Roffe et al.). Its weak point is speed: Gaussian elimination costs , hard to finish within a microsecond-scale syndrome cycle. Relay-BP stays with message passing. It chains several BP runs, each with different random “memory” terms that damp or amplify earlier beliefs (some negative, to break the deadlocks caused by degeneracy), each starting from the previous run’s final beliefs. In circuit-level simulations of the gross code at , the authors report a logical error rate about ten times lower than BP+OSD with combination-sweep order 10 (Relay-BP decoding and separately; about a hundred times when it decodes them jointly); real-time speed is estimated from an assumed 20 ns per BP iteration, not measured on hardware (PREPRINT; Müller et al., arXiv 2506.01779, version 2 of 2025-08-22).

In Deltakit

deltakit.explorer.codes.BivariateBicycleCode(param_l, param_m, m_A_powers, m_B_powers) builds Definition 7.3. Its powers follow , , so both codes here use [3, 1, 2] twice. It exposes the check matrices as m_Hx and m_Hz (dense int64 arrays) and one set of logical operators, but no distance: the weights of the returned logicals only bound it from above.

from deltakit.explorer.codes import BivariateBicycleCode
 
for ell, m in ((6, 6), (12, 6)):
    bb = BivariateBicycleCode(param_l=ell, param_m=m,
                              m_A_powers=[3, 1, 2], m_B_powers=[3, 1, 2])
    hx, hz = bb.m_Hx, bb.m_Hz
    half = hx.shape[1] // 2
    a, b = hx[:, :half], hx[:, half:]
    print(f"l={ell}, m={m}: n = {bb.n}, k = {bb.k}, Hx {hx.shape}")
    print("  check weights", sorted(set(hx.sum(1).tolist())),
          " checks per qubit", sorted(set(hx.sum(0).tolist())))
    print("  AB = BA:", np.array_equal(a @ b % 2, b @ a % 2),
          "  k from ranks:", bb.n - gf2_rank(hx) - gf2_rank(hz),
          "  2 dim(ker A & ker B):", 2 * (half - gf2_rank(np.vstack([a, b]))))
    wts = sorted(len(op) for op in bb.z_logical_operators)
    print("  lightest returned Z logical:", wts[0])
l=6, m=6: n = 72, k = 12, Hx (36, 72)
  check weights [6]  checks per qubit [3]
  AB = BA: True   k from ranks: 12   2 dim(ker A & ker B): 12
  lightest returned Z logical: 6
l=12, m=6: n = 144, k = 12, Hx (72, 144)
  check weights [6]  checks per qubit [3]
  AB = BA: True   k from ranks: 12   2 dim(ker A & ker B): 12
  lightest returned Z logical: 12

The lightest returned logical has weight 6 for and 12 for the gross code, equal to the true distances, but nothing guarantees that in general.

css_code_memory_circuit accepts BB codes too. The next block builds a 6-round and a 7-round distance-7 surface-code memory experiment with SI1000 noise, and counts the detectors each error flips in the undecomposed detector error model.

import collections
 
from deltakit.circuit.gates import PauliBasis
from deltakit.explorer.codes import RotatedPlanarCode, css_code_memory_circuit
from deltakit.explorer.qpu import QPU, SI1000Noise
 
 
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):
    """Number of DEM errors, by how many detectors each one flips."""
    sc = noisy.as_stim_circuit()
    dem = sc.detector_error_model(decompose_errors=False)
    count = collections.Counter()
    for inst in dem.flattened():
        if inst.type == "error":
            targets = inst.targets_copy()
            count[sum(t.is_relative_detector_id() for t in targets)] += 1
    return sc.num_detectors, dem.num_errors, dict(sorted(count.items()))
 
 
bb72 = BivariateBicycleCode(param_l=6, param_m=6,
                            m_A_powers=[3, 1, 2], m_B_powers=[3, 1, 2])
surface = noisy_memory(RotatedPlanarCode(width=7, height=7), rounds=7)
bb_noisy = noisy_memory(bb72, rounds=6)
for name, noisy in (("surface d=7", surface), ("BB [[72,12,6]]", bb_noisy)):
    dets, errors, hist = symptoms(noisy)
    print(f"{name}: {dets} detectors, {errors} errors")
    print("  by detectors flipped:",
          " ".join(f"{k}:{v}" for k, v in hist.items()))
surface d=7: 336 detectors, 6289 errors
  by detectors flipped: 1:240 2:1980 3:1354 4:2715
BB [[72,12,6]]: 432 detectors, 17244 errors
  by detectors flipped: 1:72 2:504 3:3132 4:1224 5:2916 6:4572 7:1872 8:1620 9:1332

The surface code also has errors that flip three or four detectors: a error is an error and a error at once, and each half lights its own pair. Stim splits those into edges. The BB circuit has 16,668 errors that flip three or more detectors, and the three-check pattern in the figure above cannot be split into pairs. Asking for a matching decoder fails at that step:

from deltakit.decode import PyMatchingDecoder
 
PyMatchingDecoder.construct_decoder_and_stim_circuit(bb_noisy)

It raises ValueError: Failed to decompose errors into graphlike components with at most two symptoms. The message then names the culprit: one fault that flips nine detectors and four of the twelve logical observables. Deltakit’s BP-OSD is the cloud decoder BPOSDecoder; without a client holding a Riverlane token it raises NotImplementedError (Remark 7.1):

from deltakit.decode import BPOSDecoder
 
BPOSDecoder(bb_noisy)
Remark 7.1 (No local qLDPC decoder in Deltakit 0.10.2).

Every decoder in Deltakit 0.10.2 that can handle hyperedges (BPOSDecoder, ACDecoder and BeliefMatchingDecoder; the matching and clustering decoders on Lecture 0’s list need edges) is a cloud decoder. To decode a BB code locally you bring your own: Notebook 7 writes min-sum BP and OSD-0 in numpy for code-capacity noise, and the ldpc package (not installed here) does BP+OSD on detector error models.

Try this

  • In the first block, replace the cyclic repetition code by the open one, np.eye(L - 1, L, dtype=int) + np.eye(L - 1, L, k=1, dtype=int), and check that you get and , as Example 7.1 says.
  • Build the code: BivariateBicycleCode(9, 6, [3, 1, 2], [3, 1, 2]). Compute from ranks and from .
  • Run symptoms(noisy_memory(bb72, rounds=1)). Why does no error flip exactly one detector?
  • In Notebook 7, change the min-sum scaling factor from 0.625 to 1.0 and see how much more often BP fails to converge.

Readings

  • S. Bravyi, A. W. Cross, J. M. Gambetta, D. Maslov, P. Rall and T. J. Yoder, High-threshold and low-overhead fault-tolerant quantum memory, Nature 627, 778 (2024). Sections 1 to 3 of arXiv 2308.07915v2 (the Nature version does not number its sections).
  • J.-P. Tillich and G. Zémor, Quantum LDPC codes with positive rate and minimum distance proportional to , arXiv 0903.0566, IEEE Trans. Inf. Theory 60, 1193 (2014). The hypergraph product.
  • S. Bravyi, D. Poulin and B. Terhal, Tradeoffs for reliable quantum information storage in 2D systems, Phys. Rev. Lett. 104, 050503 (2010). The bound .
  • N. P. Breuckmann and J. N. Eberhardt, Quantum low-density parity-check codes, PRX Quantum 2, 040101 (2021). A review.
  • P. Panteleev and G. Kalachev, Degenerate quantum LDPC codes with good finite length performance, Quantum 5, 585 (2021), and J. Roffe, D. R. White, S. Burton and E. Campbell, Decoding across the quantum low-density parity-check code landscape, Phys. Rev. Research 2, 043423 (2020). BP+OSD.
  • T. Müller et al., Improved belief propagation is sufficient for real-time decoding of quantum memory, arXiv 2506.01779 (preprint). Relay-BP.