Lecture 1 treated a stabilizer code as a list of commuting Pauli operators. On paper any such list will do. A device, however, measures a check by running a circuit, and every gate in that circuit can fail. Two demands follow. Each check should act on a few qubits that sit next to each other, so that its circuit is short and needs only nearest-neighbour gates. And the circuit must not turn one fault into an error the code cannot handle. The surface code meets the first demand with checks of weight at most four on a square grid. That is why it is the standard choice for superconducting qubits, including the experiment quoted in Lecture 0.

This lecture builds the surface code from the toric code and writes the circuit that measures it. It then shows how a bad CNOT order turns one fault into two errors, which halves the distance. It ends with the two experiments that the rest of the primer is built from: memory and stability. On the Deltakit side you meet the code families in deltakit.explorer.codes, their schedule options, and css_code_memory_circuit.

Notebook and field map

Notebook 3: Surface-code circuits draws the patches, reads one round gate by gate, counts operations and detectors against distance, compares schedules, and measures what a hook-aligned CNOT order costs. Field map: The repetition code, The toric code, The rotated surface code and its boundaries, Syndrome extraction schedules and hook errors.

From the toric code to the rotated surface code

Put an square lattice on a torus and place one qubit on each edge, so . Every vertex gets a star , the product of on its four edges. Every face gets a plaquette , the product of on its four edges. A star and a plaquette share either no edge or two, so they commute.

Definition 3.1 (Toric code).

The stabilizer code on the edges of an periodic square lattice, with stabilizer group generated by all stars and all plaquettes . Its parameters are .

The count in the toric code (Definition 3.1) comes from the CSS formula of Lecture 1. There are stars, but their product is the identity, because each edge touches two vertices. The same holds for the plaquettes. So and .

The logical operators are strings. Take on every edge of a closed loop. It enters and leaves each vertex it visits, so it commutes with every star. If the loop bounds a region, it is the product of the plaquettes inside, a stabilizer. If it wraps around the torus, it is not, and it acts on the encoded qubits. The two independent wrapping directions give and , and loops on the dual lattice give and . The shortest wrapping loop has edges, so .

This picture also shows what a decoder faces. A error on an open string anticommutes only with the stars at its two ends. The syndrome shows these two endpoints (defects) and nothing about the path between them. The decoder must pair up defects and join each pair by a string. Any string between the same endpoints gives the same syndrome. If the correction and the true error together form a contractible loop, their product is a stabilizer and the correction worked. If together they wrap the torus, the result is a logical error. Many different errors are corrected by the same correction: this is degeneracy, and Lecture 5 turns it into minimum-weight matching.

A torus cannot be built on a chip, so cut it open. On a planar patch, two opposite boundaries cut through stars and the other two cut through plaquettes. A string of one type can end on a boundary that has no check of the opposite type beyond it, without leaving a defect there. A logical operator is then a string from one boundary to the opposite one, and one logical qubit remains: . That is 41 data qubits for distance 5. Turning the lattice by and keeping only a block of qubits does better.

Definition 3.2 (Rotated surface code).

For odd , place data qubits on a grid. Each square face holds one check, of or type in a checkerboard pattern: weight-4 checks in the bulk, and weight-2 checks on the boundary. The -type boundary checks sit on one pair of opposite sides and the -type ones on the other pair. Its parameters are . With one ancilla per check it uses qubits.

The figure shows the rotated code (Definition 3.2) at in Deltakit’s coordinates. RotatedPlanarCode(width, height) puts data qubits at odd and ancillas at even , with pointing up. By default the -type boundary checks are on the top and bottom edges. A string can end on those edges, because no check lies beyond them to see its end. So runs vertically, as on the left column, and runs horizontally, as on the top row. height is the distance and width the distance.

Z X X Z Z Z X X 0 1 2 3 4 5 6 x 0 1 2 3 4 5 6 y RotatedPlanarCode(3, 3) data qubit, odd (x, y) Z check X check Z_L: Z on the left column X_L: X on the top row each check's ancilla sits at the centre of its face, at even (x, y)

The same calls build all three families. len(code.x_logical_operators) is :

from deltakit.explorer.codes import (
    RotatedPlanarCode,
    UnrotatedPlanarCode,
    UnrotatedToricCode,
)
 
families = [
    ("toric L=3", UnrotatedToricCode(3, 3)),
    ("planar L=3", UnrotatedPlanarCode(3, 3)),
    ("planar L=5", UnrotatedPlanarCode(5, 5)),
    ("rotated d=3", RotatedPlanarCode(3, 3)),
    ("rotated d=5", RotatedPlanarCode(5, 5)),
]
for name, code in families:
    n = len(code.data_qubits)
    k = len(code.x_logical_operators)
    wz = sorted({len(op) for op in code.z_logical_operators})
    total = len(code.qubits)
    print(f"{name:12s} n={n:3d} k={k} Z_L weight {wz} qubits={total}")
toric L=3    n= 18 k=2 Z_L weight [3] qubits=36
planar L=3   n= 13 k=1 Z_L weight [3] qubits=25
planar L=5   n= 41 k=1 Z_L weight [5] qubits=81
rotated d=3  n=  9 k=1 Z_L weight [3] qubits=17
rotated d=5  n= 25 k=1 Z_L weight [5] qubits=49

The playground below is a distance-5 rotated patch with perfect measurements. Click a data qubit to cycle its error through , and ; the checks that light up are the syndrome, and Decode pairs them by minimum-weight matching. It is drawn turned by relative to Deltakit’s default, so here is a column and a row. Put errors on three qubits of one column and decode: the matching completes the column into . Three faults beat a distance-5 code, as promises.

Measuring a check with a circuit

A check is measured with one ancilla qubit. The circuit copies the parity of the data qubits onto the ancilla, using how Pauli operators move through a (control , target ):

For a check, prepare the ancilla in , apply a from each data qubit to it, and measure it in the basis. Pulled back through the four gates, the final on the ancilla becomes on the ancilla times the product of on the four data qubits, so the outcome is the check’s eigenvalue. For an check, prepare , apply s from the ancilla to the data, and measure . The same rules work against us when a gate fails. An error on an -check ancilla is copied by every later onto the data. The next section is about exactly that.

Deltakit writes both kinds of check the same way. Every ancilla is reset to (RX). An check uses CX from the ancilla, a check uses CZ between ancilla and data, and every ancilla is measured in the basis (MX). A maps on the ancilla to on the ancilla times on the data, so this is the textbook circuit with the Hadamards absorbed. The QPU of Lecture 4 compiles it into H, CX, R and M. Here is one round at , printed one time step (TICK) per line:

from collections import Counter
 
from deltakit.circuit.gates import PauliBasis
from deltakit.explorer.codes import css_code_memory_circuit
 
code = RotatedPlanarCode(3, 3)
circ = css_code_memory_circuit(
    code, num_rounds=1, logical_basis=PauliBasis.Z
)
sc = circ.as_stim_circuit()
step, counts = 0, Counter()
for inst in list(sc.flattened()) + [None]:
    if inst is None or inst.name == "TICK":
        items = [f"{g} x{n}" for g, n in counts.items()]
        print(f"step {step}:", ", ".join(items))
        step, counts = step + 1, Counter()
    elif inst.name in ("DETECTOR", "OBSERVABLE_INCLUDE"):
        counts[inst.name] += 1
    elif inst.name not in ("QUBIT_COORDS", "SHIFT_COORDS"):
        pair = 2 if inst.name in ("CX", "CZ") else 1
        counts[inst.name] += len(inst.targets_copy()) // pair
step 0: R x9, RX x8
step 1: I x9
step 2: CX x3, CZ x3
step 3: CX x3, CZ x3
step 4: CX x3, CZ x3
step 5: CX x3, CZ x3
step 6: MX x8, M x9, DETECTOR x8, OBSERVABLE_INCLUDE x1

Step 0 resets everything, step 1 is an explicit idle (I) on the data qubits, steps 2 to 5 are the four rounds of two-qubit gates, and step 6 measures. Each two-qubit layer has six gates, not eight: the weight-2 boundary checks sit out two of the four layers. In general a round has two-qubit gates.

The step-6 line also lists 8 detectors. In a -basis memory the data start in , so the first-round checks are deterministic and give a detector each, while the first-round checks are random and give none. Every later round compares each check with its previous value. The final data measurement reconstructs every check once more. That makes detectors for rounds:

print(" d  qubits  measurements  detectors  2q gates  ticks")
for d in (3, 5, 7):
    c = css_code_memory_circuit(
        RotatedPlanarCode(d, d), num_rounds=d, logical_basis=PauliBasis.Z
    ).as_stim_circuit()
    ops = Counter(i.name for i in c.flattened())
    n2q = sum(
        len(i.targets_copy()) // 2
        for i in c.flattened() if i.name in ("CX", "CZ")
    )
    print(f"{d:2d} {c.num_qubits:7d} {c.num_measurements:13d}"
          f" {c.num_detectors:10d} {n2q:9d} {ops['TICK']:6d}")
 d  qubits  measurements  detectors  2q gates  ticks
 3      17            33         24        72     18
 5      49           145        120       400     30
 7      97           385        336      1176     42

Measurements, detectors and two-qubit gates grow like for a -round experiment (qubits like , time steps like ), and so does the work of simulating and decoding them.

CNOT order and hook errors

A weight-4 check needs four time steps, one per data qubit, and the order matters twice. First, neighbouring and checks share two data qubits, and their gates must interleave so that the circuit still measures commuting operators. Otherwise the detectors stop being deterministic. The standard solution visits the four qubits of an check in the order top-left, bottom-left, top-right, bottom-right (an “N”), and those of a check in the order top-left, top-right, bottom-left, bottom-right (a “Z”; both names are ours). Deltakit’s default is exactly this. Second, the order decides what a single ancilla fault does.

Definition 3.3 (Hook error).

A hook error is a single fault on a check’s ancilla partway through the check, which the remaining two-qubit gates copy onto several data qubits. In a weight-4 check, an ancilla fault after the second gate becomes an error on the last two data qubits visited.

A fault after the first gate would spread to three data qubits, but three of the four qubits of a check equal one qubit times the check, so that is no worse than a single error. The pair is the real problem. A hook error (Definition 3.3) is harmless when its pair is perpendicular to the logical operator of the same type. If it lies along that operator, each fault builds two of the qubits a logical string needs, and faults are enough to complete it. The N order for checks ends on a vertical pair, perpendicular to the horizontal . The Z order for checks ends on a horizontal pair, perpendicular to the vertical .

an X fault on the ancilla after step 2 is copied onto the qubits of steps 3 and 4 1 2 3 4 1 2 3 4 direction of X_L direction of X_L N order (Deltakit default) hook pair across X_L: harmless Z order hook pair along X_L: distance ⌈d/2⌉

Deltakit does not offer a bad order. RotatedPlanarCode takes a schedule_type (SIMULTANEOUS, the default; Z_FIRST or X_FIRST, which measure one type after the other; Z_ONLY or X_ONLY) and a schedule_order (STANDARD and three reflections, with HORIZONTALLY_REFLECTED as the default). We tried every combination of the first three types with the four orders at and , in both memory bases: all keep the full distance. The separate-type schedules cost depth instead, about 11 time steps per round against 6 (55 against 30 over five rounds). To see a hook, you have to build the bad order yourself. The code below reorders the code’s own check objects and wraps them in a CSSCode. The check class Stabiliser is not exported in Deltakit 0.10.2, so the code borrows it from an existing check. It then asks Stim for the circuit distance: the fewest graphlike faults (Stim’s shortest_graphlike_error) that flip the observable without lighting a detector.

from deltakit.explorer.codes import CSSCode
from deltakit.explorer.qpu import QPU, SD6Noise
 
TL, TR, BL, BR = (-1, 1), (1, 1), (-1, -1), (1, -1)
N_ORDER, Z_ORDER = (TL, BL, TR, BR), (TL, TR, BL, BR)
 
 
def offset(stab, pauli):
    a = stab.ancilla_qubit.unique_identifier
    q = pauli.qubit.unique_identifier
    return (int(q[0] - a[0]), int(q[1] - a[1]))
 
 
def reorder(code, x_order, z_order):
    """Same checks and logicals, new CNOT order for each check type."""
    Stabiliser = type(code.stabilisers[0][0])  # not exported in 0.10.2
    checks = []
    for s in code.stabilisers[0]:
        terms = [p for p in s.paulis if p is not None]
        is_x = type(terms[0]).__name__.endswith("X")
        by_offset = {offset(s, p): p for p in terms}
        order = x_order if is_x else z_order
        checks.append(Stabiliser(
            paulis=[by_offset.get(o) for o in order],
            ancilla_qubit=s.ancilla_qubit,
        ))
    return CSSCode(
        stabilisers=[checks],
        x_logical_operators=code.x_logical_operators,
        z_logical_operators=code.z_logical_operators,
    )
 
 
def circuit_distance(code, basis, rounds):
    circ = css_code_memory_circuit(
        code, num_rounds=rounds, logical_basis=basis
    )
    qpu = QPU(circ.qubits, noise_model=SD6Noise(p=1e-3))
    noisy = qpu.compile_and_add_noise_to_circuit(circ)
    return len(noisy.as_stim_circuit().shortest_graphlike_error())
 
 
for d in (3, 5):
    for label, xo in (("X checks N", N_ORDER), ("X checks Z", Z_ORDER)):
        code = reorder(RotatedPlanarCode(d, d), xo, Z_ORDER)
        dz = circuit_distance(code, PauliBasis.Z, d)
        dx = circuit_distance(code, PauliBasis.X, d)
        print(f"d={d} {label}: Z memory {dz}, X memory {dx}")
d=3 X checks N: Z memory 3, X memory 3
d=3 X checks Z: Z memory 2, X memory 3
d=5 X checks N: Z memory 5, X memory 5
d=5 X checks Z: Z memory 3, X memory 5

The bad order costs exactly what the argument predicts. It hurts only the -basis memory, whose observable is flipped by strings, and leaves the -basis memory alone. At the same construction gives 4 instead of 7. The mirror-image mistake, checks in N order, hurts the -basis memory in the same way. Distance is a worst case, so Notebook 3 also counts failures: a 5-round memory with SI1000 noise at fails 547 times in 200,000 shots with the bad order and 185 times with the same helper in N order, in the basis. The -basis memory barely moves (214 against 192). At the reordered copy reads the data out in a different order than Deltakit’s own circuit, so the same seed assigns its random draws differently. Its DEM is identical, and the built-in default’s 177 -basis failures differ from 185 only by shot noise.

Memory and stability experiments

The memory experiment of Lecture 0 prepares a logical state, runs rounds and measures. In Deltakit it is css_code_memory_circuit(code, num_rounds, logical_basis). You need both bases. A -basis memory only checks that survives, which a classical repetition code could also do. Only the pair of experiments shows that a logical qubit survives. In the time direction a memory experiment is easy: a measurement error lights two detectors of the same check in consecutive rounds, and no chain of measurement errors can flip . The space direction carries the risk.

Definition 3.4 (Stability experiment).

A stability experiment (Gidney 2022) runs rounds of checks on a patch whose boundaries are all of one type, say , chosen so that its checks multiply to the identity. The patch stores no logical qubit. Each -check outcome is random, but their product in any round is fixed, and that product is the observable. A failure needs a chain of measurement errors that runs from the first round to the last, so the relevant distance is the number of rounds.

The stability experiment (Definition 3.4) is the time-like twin of the memory experiment. It matters because lattice surgery (Lecture 8) measures a product of logical operators by merging patches for some rounds and multiplying check outcomes. How reliable that product is is a stability question. Deltakit has the function, but it builds stability circuits through its cloud service:

from deltakit.explorer.codes import css_code_stability_circuit
 
css_code_stability_circuit(
    RotatedPlanarCode(3, 3), num_rounds=3, logical_basis=PauliBasis.Z
)

Without a client it raises NotImplementedError: A `client` is required to obtain a stability circuit. To run a stability experiment locally, write the circuit in Stim yourself, as in Gidney’s paper.

In Deltakit

conceptDeltakit 0.10.2
toric, planar and rotated codesUnrotatedToricCode(L, L), UnrotatedPlanarCode(L, L), RotatedPlanarCode(width, height) in deltakit.explorer.codes
the repetition codeRepetitionCode(distance); it has no draw_patch
checks and CNOT ordercode.stabilisers: groups of checks; each check’s paulis list is its schedule, with None for an idle step
schedule optionsschedule_type=ScheduleType.…, schedule_order=ScheduleOrder.…
logical operators, distancescode.x_logical_operators, code.z_logical_operators, code.x_distance, code.z_distance
memory experimentcss_code_memory_circuit(code, num_rounds, logical_basis)
stability experimentcss_code_stability_circuit(…): cloud only
a picturecode.draw_patch() returns (figure, axes)

The block below prints the CNOT order of every check in the patch, as offsets from its ancilla. -- marks an idle step of a boundary check:

code = RotatedPlanarCode(3, 3)
NAMES = {TL: "TL", TR: "TR", BL: "BL", BR: "BR"}
for s in code.stabilisers[0]:
    anc = tuple(int(v) for v in s.ancilla_qubit.unique_identifier)
    terms = [p for p in s.paulis if p is not None]
    kind = type(terms[0]).__name__[-1]
    steps = [
        "--" if p is None else NAMES[offset(s, p)] for p in s.paulis
    ]
    print(kind, anc, " ".join(steps))
X (6, 4) TL BL -- --
Z (4, 0) TL TR -- --
X (2, 4) TL BL TR BR
X (4, 2) TL BL TR BR
X (0, 2) -- -- TR BR
Z (4, 4) TL TR BL BR
Z (2, 6) -- -- BL BR
Z (2, 2) TL TR BL BR

Try this

  • In the playground, set and find the smallest error that the matching decoder gets wrong. Is it always qubits on one line?
  • Build RotatedPlanarCode(5, 3). Which distance is 3, and which memory basis should you run to see it?
  • Pass schedule_type=ScheduleType.Z_FIRST and count the ticks of a 3-round memory circuit. Predict the number from the five-round count above before you run it.
  • Use reorder to put the checks in N order and check that the -basis memory now loses distance.

Readings

  • A. Kitaev, Fault-tolerant quantum computation by anyons, Annals of Physics 303, 2 (2003). The toric code.
  • E. Dennis, A. Kitaev, A. Landahl and J. Preskill, Topological quantum memory, J. Math. Phys. 43, 4452 (2002). Planar codes, boundaries, measurement errors and the decoding problem in space-time.
  • A. G. Fowler, M. Mariantoni, J. M. Martinis and A. N. Cleland, Surface codes: Towards practical large-scale quantum computation, Phys. Rev. A 86, 032324 (2012). The standard reference for syndrome-extraction circuits.
  • Y. Tomita and K. M. Svore, Low-distance surface codes under realistic quantum noise, Phys. Rev. A 90, 062320 (2014). The rotated layout and the hook-avoiding CNOT order.
  • C. Gidney, Stability experiments: the overlooked dual of memory experiments, Quantum 6, 786 (2022).