Why the surface code
The codes of the introductory lessons have checks that act on qubits far apart
(IIIXXXX in the Steane code touches qubits 3 to 6, Shor's XXXXXXIII six
qubits). On hardware where qubits interact only with near neighbours on a chip,
measuring such checks needs long-range gates or many SWAPs, and every extra
gate adds noise. The surface code makes a different trade: every check acts on
at most four qubits that are neighbours on a square grid, the code family
scales simply by enlarging the grid, and under circuit-level noise it tolerates
much higher physical error rates than earlier constructions. The price is a low
encoding rate: one logical qubit per data qubits.
This lesson builds the code from the toric code, adds boundaries, and then works with the rotated layout used by Stim, by Google's experiments and in the rest of this course. Everything is checked by computation: the exercise constructs the check matrices for any distance and verifies and the distance by brute force.
Intuition first: the toric code
Kitaev's toric code (Kitaev 2003) places one qubit on each edge of an square lattice with periodic boundaries, so . There are two kinds of checks:
- for every vertex , the star on the four edges meeting at ;
- for every face , the plaquette on the four edges around .
A star and a plaquette share either zero or two edges, so all checks commute. The product of all stars is the identity (each edge belongs to exactly two stars), and likewise for plaquettes, so each family has independent generators and
Errors are strings. A error on one edge anticommutes with the stars at its two endpoints. A chain of errors along a path flips only the stars at the two ends of the path: inside the path each vertex touches two error edges, and the two sign flips cancel. The syndrome therefore shows only the endpoints of error strings, called defects. errors behave the same way on the dual lattice (faces joined across edges), flipping the plaquettes at their ends.
Logical operators are non-contractible loops. A closed string of 's has no endpoints, so it commutes with every star. If the loop is the boundary of a region, it equals the product of the plaquettes inside, a stabilizer. If it wraps around the torus, it is not a product of plaquettes: it is a logical operator. Two independent directions give , and dual loops of 's give . The shortest non-contractible loop has length , so the distance is .
Decoding is pairing. Given the defects, the decoder must join them in pairs by correction strings. If error and correction together form a contractible loop, the result is a stabilizer and correction succeeded; if they form a non-contractible loop, a logical error occurred. Choosing the most likely pairing for independent errors means choosing the shortest total length, the problem solved by minimum-weight perfect matching. This geometric picture, and its connection with a statistical-mechanics phase transition, is developed in Dennis et al. (2002).
Boundaries: the planar code
A torus is not a chip. Bravyi and Kitaev showed how to cut the lattice open and keep one logical qubit (Bravyi and Kitaev 1998). The new ingredient is the boundary. Along one kind of boundary the checks are chosen so that a string can end there without flipping any star: the boundary absorbs -type defects. Along the other kind, strings end silently. A planar patch with two boundaries of each kind, alternating around the edge, encodes one logical qubit: is a string joining the two boundaries that absorb strings, an string joining the other two. A defect near a boundary can now also be explained by a short string to that boundary, so the decoder may match a defect either to another defect or to the boundary.
The original unrotated planar code of distance has data
qubits and checks, so qubits in total with one measure
qubit per check (25 for ; Stim's surface_code:unrotated_memory_z
generator uses exactly 25, 81 and 169 qubits for ). Rotating the
lattice by 45 degrees and trimming the corners gives the same distance with
fewer qubits, as the next section shows; discussions of both layouts and of
their small-distance performance can be found in
Fowler et al. (2012) and
Tomita and Svore (2014).
The rotated surface code
In the rotated code the data qubits sit on the vertices of a grid and every check sits on a face. We fix one concrete convention, used in the exercise:
- data qubit , , has index ;
- the face with top-left corner , , touches the data qubits that exist;
- a face is -type when is even and -type when is odd;
- every face with four qubits is a check; a two-qubit face on the top or bottom edge is a check only if it is -type, and on the left or right edge only if it is -type; corner faces with one qubit are never checks.
For this gives the checks , , , and the checks , , , .
Counting. There are four-qubit faces, half of each type because is even and the types alternate like a chessboard. Each type also gets two-qubit checks: on each of its two edges. So each type has
checks, in total. With one measure qubit per check, a distance- patch uses data and measure qubits, in total: 17 for , 49 for , 97 for . Compare 25, 81 and 169 for the unrotated layout.
Commutation. Two faces that share a side of a grid square overlap in two qubits, and they always have different types. Two faces that touch only at a corner overlap in one qubit, but they have the same type, and checks of the same type always commute. A boundary half-face overlaps in two qubits with the single adjacent four-qubit face of the other type. So every - overlap is even and .
One logical qubit. The checks are independent: the exercise confirms for , so
Logical operators and the distance
Take , the top row, and , the left column.
- commutes with every check: a four-qubit face meets the top row in 0 or 2 qubits, and the top-edge checks lie entirely inside it.
- commutes with every check, by the same argument with columns and the left-edge checks.
- They anticommute: they overlap in the single qubit .
So the left and right edges, which carry only checks, are where strings can end undetected, and the top and bottom edges play that role for strings. This assignment of boundary types is what makes the code work.
Theorem (distance). Every logical operator of the rotated surface code has weight at least , so its distance is exactly .
Proof. The same argument that showed commutes with all checks applies to the string on any column : every face meets a column in 0 or 2 qubits and the left and right checks are vertical pairs. So each column string commutes with all checks, and it anticommutes with (one shared qubit), so it is not a stabilizer: it is a representative of . A non-trivial -type logical operator must anticommute with , and hence with every , which requires an odd, hence non-zero, overlap with every one of the columns: weight at least . The same argument with rows bounds -type logical operators. A general logical operator of a CSS code commutes with all checks only if commutes with the checks and with the checks, and since is not a stabilizer at least one of the two parts is a non-trivial logical operator of weight at most that of . So the bound holds for every logical operator, and the row and column strings reach it.
The exercise confirms this by brute force for and : no -type or -type logical of weight exists. It also counts the minimum-weight logicals: for there are 8 of type, not just the 3 rows, because a minimum-weight string may step diagonally through a four-qubit face.
Why boundary types matter
What happens if the boundary checks are assigned wrongly? The following script builds variants of the patch: the correct one, one with -type two-qubit checks on all four edges, one with -type checks on all four edges, and one with no boundary checks at all.
import numpy as np
def checks(d, x_edges, z_edges):
"""Bulk faces plus two-qubit checks of each type on the named edges."""
xs, zs = [], []
for r in range(-1, d):
for c in range(-1, d):
s = [i * d + j for i in (r, r + 1) for j in (c, c + 1) if 0 <= i < d and 0 <= j < d]
kind = "X" if (r + c) % 2 == 0 else "Z"
edge = {r == -1: "top", r == d - 1: "bottom", c == -1: "left", c == d - 1: "right"}.get(True)
keep = len(s) == 4 or (len(s) == 2 and edge in (x_edges if kind == "X" else z_edges))
if keep:
(xs if kind == "X" else zs).append(s)
return xs, zs
def gf2_rank(m):
m = m.copy() % 2
rank = 0
for col in range(m.shape[1]):
rows = [r for r in range(rank, m.shape[0]) if m[r, col]]
if rows:
m[[rank, rows[0]]] = m[[rows[0], rank]]
for r in range(m.shape[0]):
if r != rank and m[r, col]:
m[r] ^= m[rank]
rank += 1
return rank
def describe(d, x_edges, z_edges):
xs, zs = checks(d, x_edges, z_edges)
hx = np.zeros((len(xs), d * d), dtype=np.uint8)
hz = np.zeros((len(zs), d * d), dtype=np.uint8)
for i, s in enumerate(xs):
hx[i, s] = 1
for i, s in enumerate(zs):
hz[i, s] = 1
commute = not ((hx.astype(int) @ hz.T) % 2).any()
return len(xs), len(zs), commute, d * d - gf2_rank(hx) - gf2_rank(hz)
d = 5
print("standard ", describe(d, ("top", "bottom"), ("left", "right")))
print("X on 4 edges ", describe(d, ("top", "bottom", "left", "right"), ()))
print("Z on 4 edges ", describe(d, (), ("top", "bottom", "left", "right")))
print("no boundaries", describe(d, (), ()))
It prints (number of checks, number of checks, commute, ):
| Variant | checks | checks | Commute | Distance (-type / -type) | |
|---|---|---|---|---|---|
| standard | 12 | 12 | yes | 1 | 5 / 5 |
| checks on all four edges | 16 | 8 | yes | 1 | 5 / 1 |
| checks on all four edges | 8 | 16 | yes | 1 | 1 / 5 |
| no boundary checks | 8 | 8 | yes | 9 | not computed |
The distances in the last column come from the brute-force search you write in the exercise. The lesson is that and commuting checks are not enough. In the "all edges" variant a single on a corner qubit commutes with every check (no face touches the corner any more) and is not a stabilizer: an undetectable logical error of weight 1. Correct boundaries are what force logical strings to cross the whole patch.
Relation to the repetition code
The repetition code is a one-dimensional version of the same picture. On a line
of qubits with checks , a block of consecutive errors is
detected only at its two ends, the two ends of the line act as boundaries, and a
logical error is a string that spans the line. The surface code adds a second
dimension so that both error types are strings with detected endpoints:
strings must span the patch from top to bottom and strings from left to
right. The bit-flip repetition code has distance against errors and 1
against errors; the surface code has distance against both, at the cost
of instead of data qubits.
Stim's repetition_code:memory and surface_code:rotated_memory_z circuits
share the same structure, which is why the repetition code is the standard
first test of any surface-code pipeline.
From checks to circuits
Each check is measured by a dedicated measure qubit at the centre of its face, coupled to its two or four data qubits by CNOTs, as in the circuits of the introductory lessons. A single or error on a data qubit flips at most two checks of the opposite type (one if it is next to the appropriate boundary). This is exactly the property that makes the decoding problem a graph problem: every elementary error is an edge between two checks or between a check and the boundary. In the next lesson these circuits are simulated in Stim, where the order of the CNOTs turns out to change the effective distance.
Stim lays out the same code on doubled integer coordinates (data qubits at odd positions, measure qubits at even positions) and may assign the boundary types differently from our convention; the exercise checks that its four-qubit and two-qubit checks match ours in number for each type.
Common mistakes
- Counting checks as independent without checking the rank. In the toric code the product of all stars is the identity; , not 0.
- Assigning boundary types by symmetry. Commuting checks and can hide a weight-1 logical operator at a corner. Always compute the distance.
- Treating "the" logical operator as unique. has many representatives (8 of minimum weight already for ); decoders care about equivalence classes, not strings.
- Confusing rotated and unrotated qubit counts. For distance the rotated layout uses qubits and the unrotated .
- Mixing conventions between tools. Qubit indices, coordinates and which edges carry which checks differ between Stim, papers and this course. Map them explicitly before comparing.
Summary
- The toric code on qubits has star and plaquette checks, , distance ; errors are strings detected at their endpoints.
- Boundaries turn the torus into a planar patch with one logical qubit; each boundary type absorbs one type of string.
- The rotated code has data qubits, checks of each type, qubits in total, and distance , proved by the column and row argument.
- Wrong boundary assignments can keep yet reduce the distance to 1.
Exercise
In the exercise you implement the construction above, verify commutation, check counts and for up to 9, find the distance by brute force for , build the toric code and confirm , and compare the check weight profile with Stim's generated circuit. Next, syndrome extraction with Stim turns these checks into noisy circuits.