Skip to main content
KetQat

Appearance

Lesson 92 h

Fault-tolerant quantum computing

Transversal gates, lattice surgery, magic states and distillation.

After this lesson you can

  • Propagate Pauli faults through Clifford circuits in binary symplectic form and identify hook errors in a syndrome-extraction circuit
  • State the single-fault definition of a fault-tolerant gadget and decide by exhaustive enumeration whether a given extraction circuit satisfies it
  • Explain how a flag qubit restores fault tolerance for weight-four checks of the Steane code
  • State the Eastin–Knill theorem and explain why it forces a non-transversal ingredient such as magic states
  • Derive the T-gate teleportation gadget and compute the exact output error, acceptance probability and cost of 15-to-1 distillation from a weight enumerator
  • Describe lattice surgery as joint logical Pauli measurement and verify the measurement-based CNOT including its Pauli corrections
  • State the threshold theorem with its assumptions and distinguish it from numerically observed code thresholds

Read first: The stabilizer formalism, The surface code, Syndrome extraction with Stim, Floquet codes

From memory to computation

A quantum memory only has to keep a state alive. A computer has to change the state while keeping it alive, and every operation it applies is itself noisy. Two new dangers appear. First, gates move errors around: a single fault on one qubit can become correlated errors on several qubits after a two-qubit gate. Second, no code lets you apply every gate in a simple, error-contained way, so at least one ingredient of a universal gate set has to be produced by another route.

This lesson treats both. We make "fault tolerant" precise, compute exactly how faults spread through a syndrome-extraction circuit, repair the circuit with a flag qubit, and then build a universal gate set from Clifford operations plus distilled magic states. The exercise turns each claim into an exhaustive or exact computation.

What fault tolerance means

Faults, locations and the single-fault model

A circuit has locations: preparations, gates, idle steps and measurements. A fault at a location replaces the ideal operation by the ideal operation followed by an arbitrary Pauli on the qubits it touches (for a stochastic Pauli noise model this loses no generality; general noise is reduced to it by standard arguments (Gottesman)). For a distance-3 code the relevant question is what one fault can do.

Definition (single-fault tolerance, distance-3 codes). A gadget, for example a syndrome-extraction round or an encoded gate, is fault tolerant if any single fault inside it leaves each output code block with an error that an ideal subsequent round of error correction removes, and if, without faults, it implements the intended operation. Rigorous versions, with separate conditions for preparation, gates, error correction and measurement and with tt faults for distance 2t+12t+1, are given by Aliferis, Gottesman and Preskill (AGP). The single-fault version is enough to see every phenomenon in this lesson.

How Paulis travel through Clifford gates

A Pauli error EE that occurs before a Clifford CC is equivalent to the error CEC†CEC^\dagger after it. In the binary symplectic form (x∣z)(x\mid z) of the previous lesson, three rules cover the gates we need:

Gate Effect on (x∣z)(x \mid z)
HH on qq swap xqx_q and zqz_q
SS on qq zq⊕=xqz_q \mathrel{\oplus}= x_q (so X↦YX\mapsto Y)
CXc→t\mathrm{CX}_{c\to t} xt⊕=xcx_t \mathrel{\oplus}= x_c and zc⊕=ztz_c \mathrel{\oplus}= z_t

So X errors flow forward from control to target, and Z errors flow backward from target to control. Stim implements the same conjugation as PauliString.after(circuit) (Gidney, Stim), which the exercise uses as an independent check of your own propagation code.

Hook errors: a worked example

The Steane code (Steane) on qubits 0,…,60,\dots,6 has X- and Z-type stabilizers given by the rows of the [7,4,3][7,4,3] Hamming parity check matrix, whose column jj is j+1j+1 in binary. One X stabilizer is X3X4X5X6X_3X_4X_5X_6. The obvious way to measure it uses one ancilla, qubit 7, prepared in ∣+⟩\ket{+}, four CNOTs from the ancilla to the data, and an X-basis readout.

Quantum circuit on 5 wires (d3, d4, d5, d6, a). step 1: CNOT, control a, target d3. step 2: CNOT, control a, target d4. step 3: CNOT, control a, target d5. step 4: CNOT, control a, target d6. step 5: measure a.d3d4d5d6a
Bare-ancilla measurement of X3 X4 X5 X6 (ancilla a starts in |+> and is read out in the X basis)

Now suppose the second CNOT fails and leaves an XX on the ancilla. By the CNOT rule, that XX is copied onto d5d_5 by the third CNOT and onto d6d_6 by the fourth. One fault has produced the weight-two data error X5X6X_5X_6. This is a hook error.

Is a weight-two error a problem? For the Steane code it is fatal. A weight-two X error has the same Hamming syndrome as some weight-one error (the syndrome of X5X6X_5X_6 is 6⊕7=16 \oplus 7 = 1 in binary, the syndrome of X0X_0), so ideal correction applies X0X_0 and leaves X0X5X6X_0X_5X_6. That has zero syndrome and odd weight, which for the Steane code means it is a logical operator. The decoder is not to blame: a distance-3 code can only guarantee to correct one error.

Enumerating every single fault exactly confirms the picture. With the fault model "any non-identity Pauli on the qubits of one operation, right after it", the bare circuit has 3+4×15=633 + 4\times 15 = 63 single faults. Running the reference solution of the exercise, 8 of them lead to a logical failure after ideal correction, and every one of them leaves the X error X5X6X_5X_6 on the data (sometimes with a harmless single Z). Four are faults on the second CNOT that put an X or Y on the ancilla and no X-type error on d4d_4; the other four are faults on the third CNOT that put an X on both the ancilla and d5d_5, so the ancilla's X still reaches d6d_6. Reordering the CNOTs only changes which pair is hit, and since every weight-two error is uncorrectable for this code, the count of failing faults stays at 8 for every order the exercise tries.

You can reproduce the propagation step in two lines of Stim:

import stim

# Ancilla 7 has an X error after the CNOT to qubit 4; propagate it through the rest.
rest = stim.Circuit("CX 7 5\nCX 7 6")
error = stim.PauliString("_______X")   # X on qubit 7
print(error.after(rest))               # +_____XXX: X on data 5 and 6, and on the ancilla

For the surface code the story is different. Its weight-four checks also produce two-qubit hooks, but a distance-dd surface code can absorb some weight-two errors, and the CNOT order can be chosen so that each hook lies across the direction of the logical operator it could shorten (Dennis et al.) (Fowler et al.). Stim's generated rotated surface-code circuits use such an order: for circuit-level depolarizing noise, len(circuit.shortest_graphlike_error()) returns 3, 5 and 7 for d=3,5,7d = 3, 5, 7, so the hook errors do not reduce the circuit-level distance below dd (computed with Stim 1.16 on surface_code:rotated_memory_x).

Flags: catching the dangerous faults

Chao and Reichardt showed that one extra qubit is enough to make such measurements fault tolerant for several distance-3 codes, including the Steane code (Chao and Reichardt). A flag qubit in ∣0⟩\ket{0} receives a CNOT from the ancilla after the first data CNOT and again after the third:

Quantum circuit on 6 wires (d3, d4, d5, d6, a, f). step 1: CNOT, control a, target d3. step 2: CNOT, control a, target f. step 3: CNOT, control a, target d4. step 4: CNOT, control a, target d5. step 5: CNOT, control a, target f. step 6: CNOT, control a, target d6. step 7: measure a. step 8: measure f.d3d4d5d6af
Flagged measurement of X3 X4 X5 X6: the flag f starts in |0> and is measured in Z

An X error on the ancilla before the first flag CNOT reaches the flag twice, and the two copies cancel; one after the second flag CNOT never reaches it. Every ancilla X fault that would leave a data error of effective weight two or more (up to stabilizers) occurs between the two flag CNOTs, so the flag measurement reads 1; faults outside that window leave errors equivalent to weight at most one. When the flag fires, the decoder switches to a lookup table built for the small set of errors a single flagged fault can cause.

The exercise checks this exhaustively over the 96 single faults of the flagged circuit: no fault that leaves the flag at 0 causes a logical failure, and no two data errors that a flagged fault can produce share a syndrome while differing by a logical operator, so a flag-aware table corrects all of them. That is the single- fault definition of fault tolerance, verified rather than argued.

Transversal gates and the Eastin–Knill theorem

A transversal gate acts as U1⊗U2⊗⋯U_1\otimes U_2\otimes\cdots across the qubits of a block (or as gates pairing qubit ii of one block with qubit ii of another). It never couples two qubits of the same block, so one fault stays one error per block. For the Steane code, CNOT, HH and SS are all transversal (the bitwise S⊗7S^{\otimes 7} implements the logical S†S^\dagger, because the logical ∣1⟩\ket{1} is a superposition of Hamming words of weights 3 and 7), so the whole Clifford group is available transversally.

Why not a universal transversal set? Eastin and Knill answered this.

Theorem (Eastin and Knill, 2009). If a quantum code can detect an arbitrary error on any single physical subsystem, then its transversal encoded gates do not form a universal set (Eastin and Knill).

Every code we care about detects single-qubit errors, so some gate must come from elsewhere. Codes differ in which gates they get for free: the Steane code has the Clifford group, while the 15-qubit quantum Reed–Muller code has a transversal TT but no transversal HH. The standard escape is to keep the Clifford group cheap and supply the missing gate through states.

Clifford + T and magic states

Clifford circuits alone can be simulated efficiently on a classical computer (the Gottesman–Knill theorem), and adding the single gate T=diag(1,eiπ/4)T = \mathrm{diag}(1, e^{i\pi/4}) yields an approximately universal set (Nielsen and Chuang). Arbitrary single-qubit rotations then have to be synthesised from Clifford and TT gates; Ross and Selinger give an algorithm that, in the typical case, uses 3log⁡2(1/ε)+O(log⁡log⁡(1/ε))3\log_2(1/\varepsilon) + O(\log\log(1/\varepsilon)) TT gates for a zz-rotation to precision ε\varepsilon (Ross and Selinger). The TT count is therefore the currency of fault-tolerant cost estimates.

Teleporting a T gate

Let ∣ψ⟩=a∣0⟩+b∣1⟩\ket\psi = a\ket0 + b\ket1 and let the magic state be ∣A⟩=T∣+⟩=(∣0⟩+ω∣1⟩)/2\ket{A} = T\ket{+} = (\ket0 + \omega\ket1)/\sqrt2 with ω=eiπ/4\omega = e^{i\pi/4}. Apply CX\mathrm{CX} with ∣ψ⟩\ket\psi as control and ∣A⟩\ket{A} as target:

12[a∣0⟩(∣0⟩+ω∣1⟩)+b∣1⟩(∣1⟩+ω∣0⟩)]=12[(a∣0⟩+ωb∣1⟩)∣0⟩+(ωa∣0⟩+b∣1⟩)∣1⟩].\tfrac{1}{\sqrt2}\big[a\ket0(\ket0+\omega\ket1) + b\ket1(\ket1+\omega\ket0)\big] = \tfrac{1}{\sqrt2}\big[(a\ket0 + \omega b\ket1)\ket0 + (\omega a\ket0 + b\ket1)\ket1\big].

Measure the second qubit in the Z basis. Outcome 0 leaves a∣0⟩+ωb∣1⟩=T∣ψ⟩a\ket0 + \omega b\ket1 = T\ket\psi. Outcome 1 leaves ωa∣0⟩+b∣1⟩∝a∣0⟩+ω−1b∣1⟩=T†∣ψ⟩\omega a\ket0 + b\ket1 \propto a\ket0 + \omega^{-1}b\ket1 = T^\dagger\ket\psi, and applying SS gives ST†=TST^\dagger = T. Every operation besides the magic state is Clifford, so a fault-tolerant Clifford layer plus a supply of good ∣A⟩\ket A states gives a fault-tolerant TT.

Quantum circuit on 2 wires (psi, magic). step 1: CNOT, control psi, target magic. step 2: measure magic. step 3: S if outcome 1 on psi.psimagicS if outcome 1
T-gate teleportation: CNOT into the magic state, Z measurement, and an S correction when the outcome is 1

15-to-1 distillation

Magic states can be prepared on a logical patch only with an error comparable to the physical error rate, far too high for a long computation. Bravyi and Kitaev showed how to purify them using only Clifford operations (Bravyi and Kitaev). In the 15-to-1 protocol, fifteen noisy copies are consumed to apply a transversal TT on the 15-qubit Reed–Muller code; measuring the code's four X-type stabilizers checks for errors, and the output is kept only if all four are trivial.

Model each input, after twirling, as having an independent ZZ error with probability pp, and assume the Clifford part is perfect. A ZZ-error pattern e∈F215e\in\F_2^{15} is undetected exactly when it is a codeword of the [15,11,3][15,11,3] Hamming code (the X stabilizers form its parity-check matrix, with columns 1,…,151,\dots,15 in binary). An undetected pattern of even weight is a Z stabilizer; one of odd weight is a logical error. With AwA_w the number of Hamming codewords of weight ww,

paccept=∑wAw pw(1−p)15−w,pout=1paccept∑w oddAw pw(1−p)15−w.p_\text{accept} = \sum_{w} A_w\, p^w (1-p)^{15-w}, \qquad p_\text{out} = \frac{1}{p_\text{accept}} \sum_{w\ \text{odd}} A_w\, p^w (1-p)^{15-w}.

The smallest odd weight with Aw≠0A_w \neq 0 is 3, and A3A_3 counts triples of distinct non-zero 4-bit vectors that sum to zero: 15⋅14/6=3515\cdot 14/6 = 35. Hence pout=35p3+O(p4)p_\text{out} = 35p^3 + O(p^4), the leading-order result of Bravyi and Kitaev.

Worked example. Enumerating all 2152^{15} patterns gives the full enumerator, and at p=10−3p = 10^{-3} the exact formulas give pout=3.51×10−8p_\text{out} = 3.51\times10^{-8} and paccept=0.985p_\text{accept} = 0.985:

import numpy as np

H = np.array([[(j + 1) >> b & 1 for j in range(15)] for b in range(4)])
words = (np.arange(2**15)[:, None] >> np.arange(15)) & 1
A = np.bincount(words[~((words @ H.T) % 2).any(axis=1)].sum(axis=1), minlength=16)
p = 1e-3
terms = A * p ** np.arange(16) * (1 - p) ** (15 - np.arange(16))
print(A[:4], f"p_out = {terms[1::2].sum() / terms.sum():.3e}", f"accept = {terms.sum():.4f}")

This prints [ 1 0 0 35] p_out = 3.511e-08 accept = 0.9851. Two levels in sequence take 10−310^{-3} to about 1.5×10−211.5\times10^{-21} and consume on average about 228 raw states per output (the exercise computes this as 15/paccept15/p_\text{accept} per level, multiplied over levels). These numbers are exact for the stated model. Real factories also suffer from errors in their own Clifford operations, which depend on the code distance of the factory; Litinski's analysis shows that careful layouts make distillation much cheaper than early estimates suggested (Litinski, magic states). Above some input error p∗p^\ast one level makes things worse; the exercise finds p∗p^\ast exactly and compares it with the leading-order estimate 1/351/\sqrt{35}.

Lattice surgery

Transversal two-qubit gates between surface-code patches would need long-range interactions. Lattice surgery instead acts on patch boundaries with nearest-neighbour operations only (Horsman et al.). Two patches placed side by side are merged by measuring, for dd rounds, the stabilizers of the combined patch along the seam. The product of the new seam stabilizers equals a joint logical operator such as ZAZBZ_AZ_B, so its value is learned while the individual logical ZAZ_A and ZBZ_B are not. A split then measures the seam qubits individually and returns two patches. A merge costs about dd code cycles of time, because the seam's syndrome has to be repeated to be reliable against measurement errors.

Joint Pauli measurements are enough for Clifford logic. A CNOT from control cc to target tt with an ancilla patch aa in ∣+⟩\ket{+}: measure ZcZaZ_cZ_a (outcome m1m_1), then XaXtX_aX_t (m2m_2), then ZaZ_a (m3m_3); apply ZcZ_c if m2=1m_2 = 1 and XtX_t if m1⊕m3=1m_1\oplus m_3 = 1. The corrections are Pauli operators, so in practice they are tracked in software (the Pauli frame) rather than applied. The snippet checks all eight outcome combinations with state vectors:

import itertools
import numpy as np

I2, X, Z = np.eye(2), np.array([[0, 1], [1, 0]]), np.diag([1.0, -1.0])
kron = lambda *ms: np.kron(np.kron(ms[0], ms[1]), ms[2])          # order: c, a, t
proj = lambda P, m: (np.eye(8) + (-1) ** m * P) / 2
CX = np.eye(4)[[0, 1, 3, 2]]
rng = np.random.default_rng(1)
psi = rng.normal(size=4) + 1j * rng.normal(size=4)
psi /= np.linalg.norm(psi)
start = np.einsum("ct,a->cat", psi.reshape(2, 2), np.ones(2) / np.sqrt(2)).reshape(8)
for m1, m2, m3 in itertools.product((0, 1), repeat=3):
    s = proj(kron(I2, Z, I2), m3) @ proj(kron(I2, X, X), m2) @ proj(kron(Z, Z, I2), m1) @ start
    out = s.reshape(2, 2, 2)[:, m3, :].reshape(4)
    out = np.kron(np.linalg.matrix_power(Z, m2), np.linalg.matrix_power(X, m1 ^ m3)) @ out
    assert abs(abs(np.vdot(CX @ psi, out / np.linalg.norm(out))) - 1) < 1e-12
print("measurement-based CNOT verified for all 8 outcomes")

Litinski's "game of surface codes" turns this into a compilation framework: a computation becomes a sequence of multi-patch Pauli product measurements, each costing about dd cycles, with TT gates consumed from factories at the edge of the layout (Litinski, game of surface codes). The next lesson prices such layouts.

The threshold theorem

Theorem (threshold theorem; Aharonov and Ben-Or; Aliferis, Gottesman and Preskill, among others). Consider noise that is local and stochastic (each set of rr locations is faulty with probability at most εr\varepsilon^r), and assume that operations can be applied in parallel, that fresh ancilla qubits can be supplied throughout, and that classical computation is fast and reliable. There is a constant ε0>0\varepsilon_0 > 0 such that, for ε<ε0\varepsilon < \varepsilon_0, any ideal circuit of size LL can be simulated with failure probability at most δ\delta by a noisy circuit of size O(L⋅polylog(L/δ))O\big(L\cdot\mathrm{polylog}(L/\delta)\big) (Aharonov and Ben-Or) (AGP).

For concatenated distance-3 codes the mechanism is visible in one line: if one level turns a fault rate ε\varepsilon into roughly cε2c\varepsilon^2, then kk levels give ε0(ε/ε0)2k\varepsilon_0(\varepsilon/\varepsilon_0)^{2^k} with ε0=1/c\varepsilon_0 = 1/c, a doubly exponential suppression bought with an exponential (in kk), hence polylogarithmic (in L/δL/\delta), overhead. AGP proved ε0>2.73×10−5\varepsilon_0 > 2.73\times10^{-5} for an adversarial independent stochastic noise model in their scheme; that is a rigorous lower bound, not an estimate of what real codes achieve.

Keep two kinds of "threshold" apart. The theorem's ε0\varepsilon_0 is a proven existence statement with conservative constants. The surface-code values near 1% (the published circuit-level estimates, and the distance-3 versus distance-5 crossings you computed in the lesson on logical error rates and thresholds, which are not themselves thresholds) are numerical observations for a specific code, noise model and decoder. Both are useful; neither substitutes for the other.

Common mistakes

  • Counting physical weight instead of effective weight. An error is dangerous if its minimum weight over the stabilizer coset exceeds what the code corrects. An ancilla X error right after preparation spreads to all four data qubits, but that is the stabilizer itself and does no harm.
  • Assuming a better decoder fixes hooks. For the Steane code every weight-two error is uncorrectable; the circuit must change (flags, cat states, or Steane- or Knill-style extraction), not the decoder.
  • Applying Pauli corrections physically. Corrections from teleportation and lattice surgery are tracked in the Pauli frame. Only the Clifford correction SS in the TT gadget must be applied before the next non-Clifford gate.
  • Quoting 35p335p^3 without its assumptions. It is the leading order for independent ZZ errors on the inputs and perfect Clifford operations. Clifford errors inside a real factory add terms that depend on the factory's code distance.
  • Reading Eastin–Knill as "no fault-tolerant universal gate set". The theorem rules out transversal universality only. Magic states, code switching and other non-transversal techniques remain available.
  • Confusing the threshold theorem with a surface-code threshold value. The theorem's assumptions (parallelism, fresh ancillas, fast classical control, weakly correlated noise) are part of its statement.

Summary

  • A gadget is fault tolerant (for distance 3) when every single fault leaves an error that ideal correction removes. Checking this is a finite enumeration over fault locations and Paulis, propagated with the symplectic rules.
  • A bare-ancilla measurement of a weight-four Steane stabilizer is not fault tolerant: 8 of its 63 single faults are hook errors that cause logical failures. A Chao–Reichardt flag catches all of them.
  • Eastin–Knill forbids a universal transversal gate set. The usual answer is Clifford operations plus magic states, with TT applied by teleportation.
  • 15-to-1 distillation suppresses ZZ errors from pp to 35p335p^3 at leading order. Its exact output error and cost follow from the Hamming code's weight enumerator.
  • Lattice surgery implements Clifford logic as joint Pauli measurements on patch boundaries, each costing about dd code cycles.
  • The threshold theorem is a proven statement with explicit assumptions; code thresholds from simulation are numerical observations.

What next

Resource estimation for fault-tolerant computers combines a fitted logical error model, lattice-surgery time steps and distillation costs into qubit counts and run times for a target computation.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Hook errors, flag qubits and the cost of magic-state distillation

advanced · about 2 h · needs numpy, scipy, stim, pytest

Two halves, one theme: what a single fault does to an encoded computation, and what it costs to make the one non-Clifford ingredient reliable.

Part A propagates every single fault through a syndrome-extraction circuit for the Steane code and shows, by exhaustive enumeration, that a bare ancilla is not fault tolerant while a Chao–Reichardt flag qubit repairs it. Part B computes the exact output error of 15-to-1 magic-state distillation from the weight enumerator of the 15-bit Hamming code and turns it into a plan for a target error rate.

What you implement (starter.py)

Part A: Pauli propagation and hook errors

Function Contract
propagate_pauli(x, z, ops) Conjugate a Pauli through H, S and CX operations in binary symplectic form. R/RX leave it unchanged.
steane_x_check_circuit(support, flag=False) The circuit measuring X⊗4X^{\otimes 4} on support with ancilla 7 in ∣+⟩\ket{+}; with flag=True, flag qubit 8 in ∣0⟩\ket{0} and CNOTs 7→8 after the first and third data CNOTs.
single_fault_outcomes(ops, n_qubits) Every non-identity Pauli on the qubits of each operation, inserted right after it and propagated to the end.
steane_decode(bits) Ideal Hamming-syndrome correction of one error type; returns the residual.
is_logical_failure(x7, z7) Whether ideal correction leaves an odd-weight Hamming codeword (a logical operator) in the X or the Z part.
analyse_extraction(flag) Counts: faults, logical failures, unflagged failures, flagged faults, and whether the flagged data errors are correctable by a flag-aware table.
t_gadget_output(psi, outcome) State-vector simulation of TT-gate teleportation with the magic state T∣+⟩T\ket{+}, including the SS correction.

The fault model is the standard single-fault model: one operation fails and applies an arbitrary non-identity Pauli to the qubits it acts on, and everything afterwards is perfect, including one ideal round of Steane error correction. This is the model in which the definition of fault tolerance for a distance-3 code is stated.

Part B: distillation

Function Contract
hamming15_weight_enumerator() Number of codewords of each weight in the [15,11,3] Hamming code.
distill_15_to_1(p) Exact (p_out, p_accept) when each of the 15 inputs has an independent ZZ error with probability pp and the Clifford part of the protocol is perfect.
distillation_plan(p_in, target, max_levels=4) Number of concatenated levels, the error after each level, and the expected raw states per output.
break_even_error_rate() The input error p∗p^\ast where one level gives pout=pp_\text{out} = p.

What the checks verify

python -m pytest test_exercise.py (about 2 s):

  1. propagate_pauli agrees with Stim's PauliString.after on random circuits.
  2. The extraction circuits have the right shape; your fault enumeration agrees, fault by fault, with an enumeration the test performs with Stim.
  3. The Steane decoder corrects every weight-1 error and fails on every weight-2 error (this is forced by the Hamming code's structure, not a decoder choice).
  4. Without a flag, some single faults cause logical failures, and every one of them leaves a data error of effective weight 2 (minimum over the stabilizer coset): these are the hook errors.
  5. With a flag, no unflagged fault causes a logical failure, and the flagged data errors never collide in syndrome while differing by a logical operator.
  6. The TT gadget reproduces T∣ψ⟩T\ket\psi up to global phase for both outcomes.
  7. The weight enumerator equals the MacWilliams transform of the simplex code (the dual code, whose 15 non-zero words all have weight 8).
  8. pout/p3→35p_\text{out}/p^3 \to 35 and paccept≈1−15pp_\text{accept} \approx 1 - 15p as p→0p\to 0, the leading-order behaviour stated by Bravyi and Kitaev.
  9. The plan for p=10−3p = 10^{-3} and target 10−1510^{-15} uses two levels, and p∗p^\ast lies below the leading-order estimate 1/351/\sqrt{35}.

Comparison and debugging tasks (not graded, but the quiz uses them)

  • Print the failing faults of the unflagged circuit. Which locations and Paulis are they? Move the ancilla's CNOT order to [6, 5, 4, 3] and check whether the number of failures changes. Explain why reordering cannot help for the Steane code, although it does help for the surface code.
  • Compute break_even_error_rate() and compare it with 1/351/\sqrt{35}. Which terms of the enumerator account for the difference?
  • For pin∈{10−2,10−3,10−4}p_\text{in} \in \{10^{-2}, 10^{-3}, 10^{-4}\} and target 10−1510^{-15}, tabulate levels and raw states per output. Note how weakly the cost depends on pinp_\text{in} once the level count is fixed.

All results in this exercise are exact (no random sampling), so they are the same on every machine.

Terminal
python -m pip install numpy scipy stim pytest

starter.py

Python
"""Starter: hook errors, flag qubits and 15-to-1 distillation.

Circuits are lists of operations:
    ("RX", q)   prepare q in |+>          ("R", q)    prepare q in |0>
    ("H", q)    Hadamard                  ("S", q)    phase gate
    ("CX", c, t) CNOT, control c, target t
Measurements are implicit: the X-check ancilla is read out in the X basis and the
flag qubit in the Z basis after the last operation.

A Pauli error on n qubits is a pair of uint8 arrays (x, z); signs are ignored.
Qubits 0-6 are the Steane code's data qubits, 7 the syndrome ancilla, 8 the flag.

Implement every function, then run `python -m pytest test_exercise.py`.
"""

from __future__ import annotations

import itertools

import numpy as np
from scipy.optimize import brentq

#: Parity-check matrix of the [7,4,3] Hamming code: column j is j+1 in binary.
HAMMING_7 = np.array([[(j + 1) >> b & 1 for j in range(7)] for b in (2, 1, 0)], dtype=np.uint8)
ANCILLA, FLAG = 7, 8


def propagate_pauli(x, z, ops):
    """Conjugate the Pauli (x, z) through the Clifford operations in ops (in order).

    H swaps x and z on its qubit; S maps X -> Y (z ^= x); CX copies x from control to
    target and z from target to control. Preparations do not change a Pauli that is
    already present (the fault model inserts errors after them)."""
    raise NotImplementedError


def steane_x_check_circuit(support, flag: bool = False):
    """Measure X on the four data qubits in `support` with ancilla 7 prepared in |+>.

    Without a flag: RX 7, then CX 7->d for d in support, in order.
    With a flag (Chao-Reichardt): also R 8 after RX 7, and CX 7->8 after the first and
    after the third data CNOT, so the flag sees X errors on the ancilla that occur
    between those two points."""
    raise NotImplementedError


def single_fault_outcomes(ops, n_qubits: int = 9):
    """Insert every non-identity Pauli on the qubits of each operation, right after that
    operation, and propagate it to the end of the circuit.

    Returns a list of dicts {"location": index, "pauli": "XZ"-style string over the
    operation's qubits, "x": array, "z": array}. A k-qubit operation contributes 4**k - 1
    faults."""
    raise NotImplementedError


def steane_decode(error_bits):
    """Ideal Steane-code correction of one error type (X or Z part, seven bits): flip
    the qubit whose index+1 is the Hamming syndrome. Returns the residual error."""
    raise NotImplementedError


def is_logical_failure(x7, z7) -> bool:
    """True when ideal correction of the data error (x7, z7) leaves a logical operator.

    After correction each residual has zero syndrome, so it is a Hamming codeword;
    even-weight codewords are stabilizers, odd-weight codewords are logical."""
    raise NotImplementedError


def analyse_extraction(flag: bool, support=(3, 4, 5, 6)) -> dict:
    """Classify every single fault of steane_x_check_circuit(support, flag).

    Returns {"faults", "logical_failures", "unflagged_failures", "flagged",
    "flagged_correctable"}. A fault is flagged when its propagated error has an X on
    the flag qubit (the Z-basis flag measurement flips). It is a logical failure when
    the data part of its error is not corrected by an ideal round of Steane
    correction. flagged_correctable is True when no two flagged data errors with the
    same (X, Z) syndromes differ by a logical operator, so a flag-aware lookup table
    can correct all of them."""
    raise NotImplementedError


def t_gadget_output(psi, outcome: int):
    """State-vector check of T-gate teleportation.

    Input qubit psi (length-2 complex array) and the magic state T|+> are combined by a
    CNOT (control psi, target magic); the magic qubit is measured in the Z basis with
    the given outcome (0 or 1). Returns the normalised state of the first qubit after
    applying S when the outcome is 1."""
    raise NotImplementedError


def hamming15_weight_enumerator():
    """A[w] = number of codewords of weight w in the [15,11,3] Hamming code (kernel of
    the 4x15 matrix whose columns are 1..15 in binary), for w = 0..15."""
    raise NotImplementedError


def distill_15_to_1(p: float):
    """Exact output error and acceptance probability of 15-to-1 distillation when each
    input has an independent Z error with probability p and all Clifford operations are
    perfect. Accepted patterns are Hamming codewords; odd-weight ones are logical.
    Returns (p_out, p_accept)."""
    raise NotImplementedError


def distillation_plan(p_in: float, target: float, max_levels: int = 4) -> dict:
    """Concatenate 15-to-1 levels until the output error is at most target.

    Returns {"levels", "error_per_level" (after each level), "inputs_per_output"}, where
    inputs_per_output is the expected number of raw magic states consumed per accepted
    output, 15 / p_accept at each level, multiplied across levels. Raises ValueError if
    max_levels is not enough."""
    raise NotImplementedError


def break_even_error_rate() -> float:
    """The input error p* in (0, 0.5) at which one 15-to-1 level neither helps nor
    hurts: distill_15_to_1(p*)[0] == p*."""
    raise NotImplementedError

test_exercise.py

Python
"""Checks for the hook-error and distillation exercise.

Independent references: Stim's PauliString.after (Clifford conjugation), a
fault enumeration done here with Stim instead of your propagation code, exhaustive
enumeration of weight-1, -2 and -3 errors of the Steane code, explicit 2x2 matrix
algebra for the T gadget, the MacWilliams identity applied to the dual (simplex)
code for the weight enumerator, and the leading-order result 35 p^3 of Bravyi and
Kitaev (Phys. Rev. A 71, 022316 (2005)).
"""

import importlib.util
import itertools
import os
from math import comb
from pathlib import Path

import numpy as np
import pytest
import stim


def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


target = _load_target()

H7 = np.array([[(j + 1) >> b & 1 for j in range(7)] for b in (2, 1, 0)], dtype=np.uint8)


def _stim_circuit(ops):
    c = stim.Circuit()
    for op in ops:
        if op[0] in ("H", "S", "CX"):
            c.append(op[0], list(op[1:]))
    return c


def _pauli(x, z):
    return stim.PauliString.from_numpy(xs=np.asarray(x, bool), zs=np.asarray(z, bool))


def test_propagation_matches_stim():
    rng = np.random.default_rng(7)
    gates = [("H", 0), ("S", 1), ("CX", 0, 2), ("CX", 3, 1), ("H", 2), ("S", 3), ("CX", 2, 3), ("RX", 0), ("CX", 1, 0)]
    for _ in range(200):
        ops = [gates[i] for i in rng.integers(len(gates), size=8)]
        x = rng.integers(0, 2, 4).astype(np.uint8)
        z = rng.integers(0, 2, 4).astype(np.uint8)
        x2, z2 = target.propagate_pauli(x, z, ops)
        xs, zs = _pauli(x, z).after(_stim_circuit(ops)).to_numpy()
        assert np.array_equal(np.asarray(x2, bool), xs) and np.array_equal(np.asarray(z2, bool), zs)


@pytest.mark.parametrize("flag", [False, True])
def test_circuit_shape_and_fault_enumeration(flag):
    ops = target.steane_x_check_circuit([3, 4, 5, 6], flag)
    cx_data = [op for op in ops if op[0] == "CX" and op[2] < 7]
    assert [op[2] for op in cx_data] == [3, 4, 5, 6] and all(op[1] == 7 for op in cx_data)
    assert sum(op[0] == "CX" and op[2] == 8 for op in ops) == (2 if flag else 0)
    # The check measured is X3 X4 X5 X6: an X error on the ancilla right after
    # preparation propagates to exactly that operator on the data.
    x, _ = target.propagate_pauli(np.eye(9, dtype=np.uint8)[7], np.zeros(9, np.uint8), ops[1:])
    assert list(np.flatnonzero(x[:7])) == [3, 4, 5, 6]
    faults = target.single_fault_outcomes(ops, 9)
    expected = sum(4 ** (len(op) - 1) - 1 for op in ops)
    assert len(faults) == expected
    circuit = _stim_circuit(ops)
    for f in faults:
        op = ops[f["location"]]
        start = stim.PauliString(9)
        for q, p in zip(op[1:], f["pauli"]):
            start[q] = p if p != "I" else 0
        rest = _stim_circuit(ops[f["location"] + 1:])
        xs, zs = start.after(rest).to_numpy() if len(rest) else start.to_numpy()
        assert np.array_equal(np.asarray(f["x"], bool), xs) and np.array_equal(np.asarray(f["z"], bool), zs)
    assert circuit.num_qubits <= 9


def test_steane_decoder_on_all_low_weight_errors():
    zero = np.zeros(7, np.uint8)
    for w in (1, 2, 3):
        for support in itertools.combinations(range(7), w):
            e = np.zeros(7, np.uint8)
            e[list(support)] = 1
            residual = target.steane_decode(e)
            assert not (H7 @ residual % 2).any(), "residual must have zero syndrome"
            is_codeword = not (H7 @ e % 2).any()
            fail = target.is_logical_failure(e, zero)
            assert fail == target.is_logical_failure(zero, e), "CSS symmetry"
            if w == 1:
                assert not fail
            elif w == 2:
                assert fail, "every weight-2 error is mis-corrected by a distance-3 Hamming decoder"
            elif is_codeword:
                assert fail, "a weight-3 codeword is a logical operator"


def test_hook_errors_without_flag():
    result = target.analyse_extraction(flag=False)
    assert result["faults"] == 1 * 3 + 4 * 15
    assert result["logical_failures"] > 0
    assert result["unflagged_failures"] == result["logical_failures"]
    # Independent: every failing fault must leave a data error of effective weight 2
    # (minimum weight over the coset of X stabilizers, the even-weight Hamming words).
    stabilizers = [np.array(v, np.uint8) for v in itertools.product((0, 1), repeat=7)
                   if not (H7 @ np.array(v) % 2).any() and sum(v) % 2 == 0]
    ops = target.steane_x_check_circuit([3, 4, 5, 6], False)
    for f in target.single_fault_outcomes(ops, 9):
        if target.is_logical_failure(f["x"][:7], f["z"][:7]):
            eff = min(int(((f["x"][:7] + s) % 2).sum()) for s in stabilizers)
            assert eff == 2


def test_flag_catches_every_dangerous_fault():
    result = target.analyse_extraction(flag=True)
    assert result["faults"] == 2 * 3 + 6 * 15
    assert result["unflagged_failures"] == 0
    assert result["flagged"] > 0
    assert result["flagged_correctable"] is True


def test_t_gadget_teleports_a_t_gate():
    rng = np.random.default_rng(3)
    T = np.diag([1, np.exp(1j * np.pi / 4)])
    for _ in range(20):
        psi = rng.normal(size=2) + 1j * rng.normal(size=2)
        psi /= np.linalg.norm(psi)
        for m in (0, 1):
            out = target.t_gadget_output(psi, m)
            assert abs(abs(np.vdot(T @ psi, out)) - 1) < 1e-12


def test_weight_enumerator_matches_macwilliams():
    A = np.asarray(target.hamming15_weight_enumerator())
    assert A.shape == (16,) and A.sum() == 2 ** 11
    # Dual code: the [15,4] simplex code, every non-zero word of weight 8.
    # MacWilliams: A_w = (1/16) * sum_j B_j K_w(j), Krawtchouk K_w(j) = sum_i (-1)^i C(j,i) C(15-j, w-i).
    def kraw(w, j):
        return sum((-1) ** i * comb(j, i) * comb(15 - j, w - i) for i in range(w + 1))
    expected = [(kraw(w, 0) + 15 * kraw(w, 8)) // 16 for w in range(16)]
    assert list(A) == expected


def test_distillation_leading_order():
    for p in (1e-3, 1e-4, 1e-5):
        p_out, accept = target.distill_15_to_1(p)
        assert abs(p_out / p**3 - 35) < 35 * 20 * p, "Bravyi-Kitaev: p_out = 35 p^3 + O(p^4)"
        assert abs(accept - (1 - 15 * p)) < 200 * p**2
    p_out, accept = target.distill_15_to_1(0.0)
    assert p_out == 0 and accept == 1


def test_distillation_plan_and_break_even():
    plan = target.distillation_plan(1e-3, 1e-15)
    assert plan["levels"] == 2
    p1 = target.distill_15_to_1(1e-3)[0]
    assert np.isclose(plan["error_per_level"][0], p1)
    assert np.isclose(plan["error_per_level"][1], target.distill_15_to_1(p1)[0])
    assert 225 < plan["inputs_per_output"] < 240
    with pytest.raises(ValueError):
        target.distillation_plan(0.2, 1e-10, max_levels=3)
    p_star = target.break_even_error_rate()
    assert abs(target.distill_15_to_1(p_star)[0] - p_star) < 1e-10
    assert 0.10 < p_star < 0.1690308509457033, "higher orders pull p* below the leading-order 1/sqrt(35)"
    assert target.distill_15_to_1(0.9 * p_star)[0] < 0.9 * p_star

Check your understanding

8 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. A single fault in a bare-ancilla measurement of X3X4X5X6X_3X_4X_5X_6 on the Steane code leaves X5X6X_5X_6 on the data. Why does an ideal round of Steane correction then fail?

    1 pt
  2. Which statements about the Eastin–Knill theorem are correct? Select all that apply.

    1 pt

    Select all that apply.

  3. In T-gate teleportation with the magic state T∣+⟩T\ket{+} (CNOT from the data qubit into the magic state, then a Z measurement of the magic qubit), what must be applied to the data qubit when the outcome is 1?

    1 pt
  4. Using only the leading-order formula pout≈35p3p_\text{out} \approx 35p^3, what output error does one round of 15-to-1 distillation give for input error p=5×10−3p = 5\times10^{-3}? Enter the value in units of 10−610^{-6}.

    1 pt
  5. Run break_even_error_rate() from the exercise: the input error p∗p^\ast at which one level of 15-to-1 distillation (independent Z errors, perfect Cliffords) gives exactly pout=p∗p_\text{out} = p^\ast. Enter p∗p^\ast.

    1 pt

    Computed by running exercise “hook-errors-and-distillation” on your computer.

  6. Run distillation_plan(1e-4, 1e-15) from the exercise. How many raw magic states are consumed on average per accepted output state (inputs_per_output)?

    1 pt

    Computed by running exercise “hook-errors-and-distillation” on your computer.

  7. Two surface-code patches A and B are merged along their Z boundaries for d rounds. What logical information does the merge reveal?

    1 pt
  8. Aliferis, Gottesman and Preskill prove ε0>2.73×10−5\varepsilon_0 > 2.73\times10^{-5}. How should this number be read?

    1 pt

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Daniel Gottesman (2009). An Introduction to Quantum Error Correction and Fault-Tolerant Quantum Computation. arXiv:0904.2557
  2. Panos Aliferis, Daniel Gottesman, John Preskill (2006). Quantum accuracy threshold for concatenated distance-3 codes. Quantum Information and Computation 6, 97-165. arXiv:quant-ph/0504218
  3. Dorit Aharonov, Michael Ben-Or (1999). Fault-Tolerant Quantum Computation With Constant Error Rate. arXiv:quant-ph/9906129
  4. Eric Dennis et al. (2002). Topological quantum memory. Journal of Mathematical Physics 43, 4452-4505. doi:10.1063/1.1499754
  5. Andrew Steane (1996). Multiple Particle Interference and Quantum Error Correction. Proceedings of the Royal Society A 452, 2551. doi:10.1098/rspa.1996.0136
  6. Rui Chao, Ben W. Reichardt (2018). Quantum error correction with only two extra qubits. Physical Review Letters 121, 050502. doi:10.1103/PhysRevLett.121.050502
  7. Bryan Eastin, Emanuel Knill (2009). Restrictions on Transversal Encoded Quantum Gate Sets. Physical Review Letters 102, 110502. doi:10.1103/PhysRevLett.102.110502
  8. Sergei Bravyi, Alexei Kitaev (2005). Universal quantum computation with ideal Clifford gates and noisy ancillas. Physical Review A 71, 022316. doi:10.1103/PhysRevA.71.022316
  9. Dominic Horsman et al. (2012). Surface code quantum computing by lattice surgery. New Journal of Physics 14, 123011. doi:10.1088/1367-2630/14/12/123011
  10. Daniel Litinski (2019). A Game of Surface Codes: Large-Scale Quantum Computing with Lattice Surgery. Quantum 3, 128. doi:10.22331/q-2019-03-05-128
  11. Daniel Litinski (2019). Magic State Distillation: Not as Costly as You Think. Quantum 3, 205. doi:10.22331/q-2019-12-02-205
  12. Neil J. Ross, Peter Selinger (2016). Optimal ancilla-free Clifford+T approximation of z-rotations. Quantum Information and Computation 16(11-12), 901-953. arXiv:1403.2975
  13. Austin G. Fowler et al. (2012). Surface codes: Towards practical large-scale quantum computation. Physical Review A 86, 032324. doi:10.1103/PhysRevA.86.032324
  14. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667
  15. Craig Gidney (2021). Stim: a fast stabilizer circuit simulator. Quantum 5, 497. doi:10.22331/q-2021-07-06-497