Skip to main content
KetQat

Appearance

Lesson 71 h 20 min

Logical error rates and thresholds

Estimating logical error rates with uncertainty, threshold crossings and finite-size effects.

After this lesson you can

  • Convert between per-shot and per-round logical error rates and state the assumptions of the conversion
  • Compute Wilson score intervals, including the upper bound when no failure is observed, and explain why the Wald interval fails
  • Estimate the number of shots needed for a target relative uncertainty
  • Run a seeded surface-code sweep with Stim and PyMatching and estimate where the d = 3 and d = 5 curves cross, with a bootstrap uncertainty
  • Explain why a crossing estimate from small distances is not the threshold, and how the choice of metric moves it
  • Report published threshold and below-threshold results with their noise models, decoders and units

Read first: Minimum-weight perfect matching decoding

From failure counts to claims

A memory simulation returns a count: kk logical failures in nn shots. Turning that count into a statement others can rely on takes three more steps. We must say what unit the rate refers to (one shot of rr rounds, or one round), how uncertain it is, and, when comparing code sizes, what the comparison does and does not establish. Most mistakes in published and unpublished QEC benchmarks happen in exactly these steps, not in the simulation. This lesson develops the tools and applies them to a small threshold sweep that you run yourself.

Throughout, "uniform circuit-level noise with parameter pp" means Stim's rotated surface-code generator with after_clifford_depolarization, before_round_data_depolarization, before_measure_flip_probability and after_reset_flip_probability all equal to pp (see the Stim lesson), a ZZ-basis memory with dd rounds, decoded by PyMatching (Higgott 2022) from the decomposed detector error model produced by Stim (Gidney 2021).

Per shot and per round

The natural estimate is the per-shot logical error rate p^shot=k/n\hat p_{\text{shot}} = k/n: the probability that one complete experiment of rr rounds ends with the wrong logical value. It depends on rr, so it cannot be compared across experiments with different numbers of rounds, and in a sweep with r=dr = d the larger code is penalised simply for running longer.

The per-round rate ε\varepsilon removes that dependence under a model. Assume that each round independently flips the logical value with the same probability ε\varepsilon. As for the repetition-code memory, the experiment fails when an odd number of rounds failed:

pshot=1−(1−2ε)r2⟺ε=1−(1−2pshot)1/r2.p_{\text{shot}} = \frac{1 - (1-2\varepsilon)^r}{2} \quad\Longleftrightarrow\quad \varepsilon = \frac{1 - (1 - 2p_{\text{shot}})^{1/r}}{2}.

For rε≪1r\varepsilon \ll 1 this is close to ε≈pshot/r\varepsilon \approx p_{\text{shot}}/r, and the exact form matters as pshotp_{\text{shot}} grows: it saturates at 1/21/2, where the conversion breaks down. Worked example. pshot=0.05p_{\text{shot}} = 0.05 over r=5r = 5 rounds gives ε=(1−0.90.2)/2=0.01043\varepsilon = (1 - 0.9^{0.2})/2 = 0.01043, slightly more than 0.05/5=0.010.05/5 = 0.01.

The assumptions are real assumptions. The first and last rounds of a memory experiment differ from the middle ones (the time boundaries), so the per-round rate of a short experiment is biased; experiments therefore often fit pshot(r)p_{\text{shot}}(r) over several rr instead of converting a single point. In this course we convert single points and say so.

How uncertain is k/nk/n?

If every shot fails independently with probability pp, kk is binomially distributed, with standard error p(1−p)/n\sqrt{p(1-p)/n}. The textbook "Wald" interval p^±1.96p^(1−p^)/n\hat p \pm 1.96\sqrt{\hat p(1-\hat p)/n} plugs in the estimate. It is badly behaved exactly where QEC lives, at small kk: for k=0k = 0 it has zero width, claiming certainty that the rate is 0, and for small kk its actual coverage is well below 95%.

The Wilson score interval (Wilson 1927) instead asks which values of pp are consistent with the observation at the stated level. With z=1.95996z = 1.95996 for 95%,

k+z2/2n+z2  ±  zn+z2k(n−k)n+z24.\frac{k + z^2/2}{n + z^2} \;\pm\; \frac{z}{n + z^2}\sqrt{\frac{k(n-k)}{n} + \frac{z^2}{4}}.

Worked examples (computed by the snippet below and by your exercise code):

  • k=7k = 7, n=1000n = 1000: p^=0.007\hat p = 0.007, Wilson interval [0.00339,0.01438][0.00339, 0.01438]. Note the asymmetry: the interval extends further up than down.
  • k=0k = 0, n=10 000n = 10\,000: the interval is [0,3.84×10−4][0, 3.84\times10^{-4}], the upper end being z2/(n+z2)z^2/(n+z^2). Zero observed failures is an upper bound, never a rate of zero. The KetQat SDK products report such results with an explicit is_upper_bound_only flag.
import math
from scipy.stats import binomtest

def wilson(k, n, z=1.959963984540054):
    centre = (k + z * z / 2) / (n + z * z)
    half = z / (n + z * z) * math.sqrt(k * (n - k) / n + z * z / 4)
    return max(0.0, centre - half), min(1.0, centre + half)

for k, n in [(7, 1000), (0, 10_000)]:
    ref = binomtest(k, n).proportion_ci(confidence_level=0.95, method="wilson")
    print(k, n, [round(x, 6) for x in wilson(k, n)], [round(float(ref.low), 6), round(float(ref.high), 6)])

This prints [0.003395, 0.014378] and [0.0, 0.000384] for both implementations; SciPy is an independent check of the formula, and the exercise uses it the same way.

How many shots?

To estimate pp with relative standard error δ\delta you need p(1−p)/n≤δp\sqrt{p(1-p)/n} \le \delta p, that is

n≥1−pp δ2≈1p δ2.n \ge \frac{1-p}{p\,\delta^2} \approx \frac{1}{p\,\delta^2}.

Since npnp is the expected number of failures, this says: you need about 1/δ21/\delta^2 failures, roughly 100 for 10% relative precision, whatever pp is. At p=10−3p = 10^{-3} that is 99,900 shots; at p=10−9p = 10^{-9}, 101110^{11}. This is why simulations of very low logical error rates rely on extrapolation from higher pp or on specialised rare-event methods, and why such numbers must be labelled as extrapolations.

Thresholds

For a code family, a noise model and a decoder, the threshold pthp_{\text{th}} is the physical error rate below which the logical error rate goes to zero as the code distance grows, and above which it does not. For the surface code under independent noise, Dennis et al. related it to a phase transition in a statistical-mechanics model (Dennis et al. 2002); for general fault-tolerance schemes its existence is a theorem (Aharonov and Ben-Or 1999). Its value is not a theorem: it is estimated numerically.

In practice one plots pLp_L against pp for several distances. Below threshold the larger code is better, above it worse, so the curves cross. The crossing of curves for increasing dd approaches the threshold. Three effects keep a crossing of small codes from being the threshold:

  1. Finite-size drift. The crossing of d=3d = 3 and d=5d = 5 generally differs from that of d=5d = 5 and d=7d = 7, and so on. Only the limit is the threshold; serious estimates use several distances and fit a scaling form.
  2. The metric moves it. Per-shot and per-round curves cross at different places when the number of rounds grows with dd (computed below).
  3. Statistics. Near the crossing the two curves are close by definition, so their difference is the hardest quantity in the sweep to measure.

Below threshold, the useful quantity is often the suppression factor Λ=εd/εd+2\Lambda = \varepsilon_d / \varepsilon_{d+2}, the factor gained per step of 2 in distance. Far below threshold Λ\Lambda is large; at threshold it is 1.

Your sweep

The exercise runs d∈{3,5}d \in \{3, 5\} at p∈{0.004,0.006,…,0.014}p \in \{0.004, 0.006, \dots, 0.014\} with 40,000 shots per point and seed 2026 (point seeds derived with numpy.random.SeedSequence). The reference solution gives (failures, per-shot rate with 95% Wilson interval, per-round rate):

pp d=3d=3 failures d=3d=3 p^shot\hat p_{\text{shot}} [95% CI] d=3d=3 ε^\hat\varepsilon d=5d=5 failures d=5d=5 p^shot\hat p_{\text{shot}} [95% CI] d=5d=5 ε^\hat\varepsilon
0.004 410 0.01025 [0.00931, 0.01129] 0.00344 306 0.00765 [0.00684, 0.00855] 0.00154
0.006 997 0.02492 [0.02344, 0.02650] 0.00845 957 0.02392 [0.02247, 0.02547] 0.00488
0.008 1621 0.04052 [0.03864, 0.04250] 0.01389 1917 0.04793 [0.04587, 0.05006] 0.00998
0.010 2359 0.05897 [0.05671, 0.06133] 0.02049 3358 0.08395 [0.08127, 0.08671] 0.01805
0.012 3226 0.08065 [0.07802, 0.08336] 0.02847 4981 0.12452 [0.12133, 0.12780] 0.02784
0.014 4108 0.10270 [0.09976, 0.10571] 0.03689 6886 0.17215 [0.16848, 0.17588] 0.04047

Log-log interpolation between neighbouring points puts the per-shot crossing at p≈0.00635p \approx 0.00635 and the per-round crossing at p≈0.0124p \approx 0.0124. A parametric bootstrap (redraw every count from a binomial at its observed rate, recompute the crossing, 2,000 times) gives 95% ranges of about [0.0056,0.0069][0.0056, 0.0069] and [0.0116,0.0129][0.0116, 0.0129]:

import math
import numpy as np

ps = [0.004, 0.006, 0.008, 0.010, 0.012, 0.014]
shots = 40_000
failures = {3: [410, 997, 1621, 2359, 3226, 4108],   # from the exercise sweep, seed 2026
            5: [306, 957, 1917, 3358, 4981, 6886]}

def per_round(p_shot, rounds):
    return (1 - (1 - 2 * p_shot) ** (1 / rounds)) / 2

def crossing(ps, small, large):
    g = [math.log(b) - math.log(a) for a, b in zip(small, large)]
    for i in range(len(ps) - 1):
        if g[i] < 0 <= g[i + 1]:
            t = -g[i] / (g[i + 1] - g[i])
            return math.exp(math.log(ps[i]) + t * (math.log(ps[i + 1]) - math.log(ps[i])))
    return None

def estimate(counts, per_round_rates):
    rates = {d: [k / shots for k in counts[d]] for d in counts}
    if per_round_rates:
        rates = {d: [per_round(r, d) for r in rates[d]] for d in rates}
    return crossing(ps, rates[3], rates[5])

print("per shot :", round(estimate(failures, False), 5))
print("per round:", round(estimate(failures, True), 5))

# Parametric bootstrap: redraw every count from a binomial at its observed rate.
rng = np.random.default_rng(1)
for per_round_rates in (False, True):
    values = []
    for _ in range(2000):
        counts = {d: [rng.binomial(shots, k / shots) for k in failures[d]] for d in failures}
        x = estimate(counts, per_round_rates)
        if x is not None:
            values.append(x)
    lo, hi = np.percentile(values, [2.5, 97.5])
    print("per round" if per_round_rates else "per shot ", len(values), round(lo, 5), round(hi, 5))

How to read this honestly:

  • These are crossing estimates for d=3d = 3 versus d=5d = 5, for this noise model, this decoder, memory in the ZZ basis with dd rounds, and the stated metric. They are not "the threshold of the surface code".
  • The metric changes the answer by a factor of two. With r=dr = d, the d=5d = 5 experiment runs 5 rounds against 3, so per shot it looks worse earlier. Per round removes that penalty, but its crossing lies where pshotp_{\text{shot}} for d=5d = 5 exceeds 0.1 and the independent-rounds model is strained. Neither number is wrong; each answers a different question, which must be stated.
  • The bootstrap range is statistical only. It says nothing about finite-size drift, which you would see by adding d=7,9d = 7, 9, or about the interpolation model.
  • Look at the neighbouring points. At p=0.006p = 0.006 the per-shot intervals of d=3d = 3 and d=5d = 5 overlap; that is what "near the crossing" looks like. At p=0.004p = 0.004 and 0.0140.014 they are cleanly separated, which is what the exercise's tests check instead of hard-coded numbers.
  • Seeds fix numbers, not truths. Running the same sweep with another seed moves every count by about a standard error or two. Try it: rerun one point with eight different seeds and look at the spread. Conclusions should survive that.

Published results, labelled as such

The following are published values. They were obtained under the stated conditions; we have not reproduced them, and they are not comparable with the crossings above without accounting for every difference in model, decoder and metric.

  • Circuit-level threshold near 1%. Wang, Fowler and Hollenberg (2011) simulated the surface code on a nearest-neighbour square lattice with two-qubit depolarizing noise of probability pp after two-qubit gates, single-qubit depolarizing noise of probability pp on idle (identity) steps, and measurements reporting the wrong result with probability pp, decoded by minimum-weight perfect matching with edge weights derived from the error model. They reported a threshold of about 1.1% per operation for that model (distances 3 to 9, estimated from the average number of rounds before a logical failure), and 1.2% and 1.4% for two variants with different idle and measurement error ratios. Our uniform model also has reset errors and data depolarization before every round, our decoder uses Stim's error model directly, and our crossing compares only d=3d = 3 and d=5d = 5, so our 0.6% (per shot) and 1.2% (per round) are not comparable with their 1.1%: different model, metric and distances, not a contradiction.
  • Scaling a logical qubit (2023). Google Quantum AI reported that, on their superconducting processor, a distance-5 surface code logical qubit had a logical error per cycle of 2.914%±0.016%2.914\% \pm 0.016\%, compared with 3.028%±0.023%3.028\% \pm 0.023\% averaged over distance-3 codes, over 25 cycles, decoded with an approximate maximum-likelihood (tensor-network) decoder; the faster belief-matching decoder gave 3.056%3.056\% and 3.118%3.118\% (Google Quantum AI 2023): a modest improvement with distance on real hardware noise.
  • Below threshold (2024/2025). Google Quantum AI reported surface-code memories with a suppression factor Λ=2.14±0.02\Lambda = 2.14 \pm 0.02 per increase of the distance by two with their neural-network decoder (2.04±0.022.04 \pm 0.02 with ensembled matching synthesis), a distance-7 code (101 qubits) with 0.143%±0.003%0.143\% \pm 0.003\% error per cycle of error correction, and, in repetition-code experiments up to distance 29, logical performance limited by rare correlated error events (Google Quantum AI and Collaborators 2025). These are per-cycle rates on a specific device with its own noise and decoders.

Note the units: "per cycle" in these papers corresponds to per round here.

Common mistakes

  • Quoting k/nk/n with no unit. Per shot of how many rounds? Per round under which conversion?
  • Reporting zero failures as zero. It is an upper bound, about 3.84/n3.84/n at 95% (two-sided Wilson).
  • Using the Wald interval at small kk. It undercovers, and at k=0k = 0 it collapses to a point.
  • Calling a two-distance crossing "the threshold". It is a finite-size estimate for a stated model, decoder and metric, with a statistical uncertainty that you should report.
  • Comparing with published thresholds across models. Different noise models, decoders and metrics give different numbers by design.
  • Sharing seeds across sweep points. Identical seeds make neighbouring points correlated; derive one seed per point.
  • Too few failures. Fewer than about 100 failures per point gives more than 10% relative uncertainty.

Summary

  • Per-shot and per-round rates are related by pshot=(1−(1−2ε)r)/2p_{\text{shot}} = \bigl(1-(1-2\varepsilon)^r\bigr)/2 under independent rounds.
  • Use Wilson intervals; zero failures gives an upper bound ≈3.84/n\approx 3.84/n.
  • About 1/δ21/\delta^2 failures are needed for relative precision δ\delta.
  • Thresholds are limits over increasing dd; a crossing of d=3d = 3 and d=5d = 5 is an estimate whose value depends on the metric and carries statistical and finite-size uncertainty. In our sweep the per-shot and per-round crossings differ by a factor of two.
  • Published thresholds and hardware results must be cited with their noise model, decoder, distances, rounds and units.

Exercise

You implement Wilson intervals (checked against SciPy and by a coverage simulation), the per-round conversion (checked against an explicit composition of rounds), the shot budget, the seeded sweep and the crossing estimator. Tests check statistical consistency: the pipeline must reproduce the exact repetition-code rate within a 99.99% interval, and the sweep must show d=5d = 5 better than d=3d = 3 at p=0.004p = 0.004 and worse at p=0.014p = 0.014 with non-overlapping intervals. The quiz asks for the crossing estimates of the reference sweep, which your implementation reproduces exactly with the stated seed.

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.

A threshold sweep with honest error bars

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

You will build the statistics layer of a QEC benchmark (Wilson intervals, per-shot to per-round conversion, shot budgets), run a small surface-code sweep with Stim and PyMatching, and estimate where the d=3d = 3 and d=5d = 5 curves cross, once per shot and once per round. The checks test your code against independent values (SciPy's Wilson interval, a Markov-chain composition, the exact repetition-code formula) and test the sweep with statistical statements, never against a stored copy of its output.

Noise model

"Uniform circuit-level depolarizing noise with parameter pp": Stim's surface_code:rotated_memory_z generator with after_clifford_depolarization, before_round_data_depolarization, before_measure_flip_probability and after_reset_flip_probability all equal to pp; dd rounds; decoded by PyMatching from the decomposed detector error model.

Functions to implement in starter.py

Function Contract
wilson_interval(k, n, z=1.96...) Wilson score interval, exactly 0 below when k=0k=0 and exactly 1 above when k=nk=n.
per_round_error(p_shot, rounds) Invert pshot=12(1−(1−2ε)r)p_{\text{shot}} = \tfrac12\bigl(1-(1-2\varepsilon)^{r}\bigr) for ε\varepsilon.
shots_for_relative_error(p, rel) Smallest nn with p(1−p)/n≤rel⋅p\sqrt{p(1-p)/n} \le \text{rel}\cdot p.
surface_memory_circuit(d, p, rounds=None) The circuit above.
logical_failures(circuit, shots, seed) Sample (seeded), decode, count wrong shots.
point_seed(seed, d, index) Provided: the seed of one sweep point.
sweep(distances, ps, shots, seed) One row per (d,p)(d, p) with keys d, p, rounds, shots, failures, p_shot, ci, p_round, seed.
crossing_estimate(ps, small, large) First upward crossing of the larger code's curve, by linear interpolation of ln⁡(rate)\ln(\text{rate}) against ln⁡p\ln p; None if there is none.

What the checks verify

  • Your Wilson interval equals SciPy's binomtest(...).proportion_ci(method="wilson") and covers the true rate about 95% of the time in a seeded simulation.
  • The per-round conversion inverts the composition of independent rounds, and reduces to pshot/rp_{\text{shot}}/r for small rates.
  • On a code-capacity repetition code your pipeline's failure rate is consistent with the exact binomial formula (99.99% interval).
  • The sweep is reproducible; at p=0.004p = 0.004 the d=5d = 5 code is better than d=3d = 3 and at p=0.014p = 0.014 it is worse, with non-overlapping intervals; the crossing lies between them.
  • The crossing estimator is exact on power laws.

The whole file runs in a few seconds.

Run the checks

python -m pytest test_exercise.py

The reference sweep for the quiz

import starter as s  # your implementation

ps = [0.004, 0.006, 0.008, 0.010, 0.012, 0.014]
rows = s.sweep([3, 5], ps, shots=40_000, seed=2026)
small = [r for r in rows if r["d"] == 3]
large = [r for r in rows if r["d"] == 5]
print(s.crossing_estimate(ps, [r["p_shot"] for r in small], [r["p_shot"] for r in large]))
print(s.crossing_estimate(ps, [r["p_round"] for r in small], [r["p_round"] for r in large]))

With a correct implementation (and the pinned Stim and PyMatching versions) these numbers are reproducible to every digit.

Terminal
python -m pip install numpy scipy stim pymatching pytest

starter.py

Python
"""Starter: logical error rates with honest uncertainty, and a small threshold sweep.

Noise model used throughout ("uniform circuit-level depolarizing", one parameter p):
Stim's rotated surface-code generator with after_clifford_depolarization = p,
before_round_data_depolarization = p, before_measure_flip_probability = p and
after_reset_flip_probability = p. Memory in the Z basis, rounds = d unless stated,
decoded by PyMatching from the decomposed detector error model.
"""

from __future__ import annotations

import math

import numpy as np
import pymatching
import stim

Z95 = 1.959963984540054  # two-sided 95% standard-normal quantile


def wilson_interval(failures: int, shots: int, z: float = Z95) -> tuple[float, float]:
    """Wilson score interval for a binomial proportion failures / shots.

    centre = (k + z^2/2) / (n + z^2), half = z / (n + z^2) * sqrt(k (n - k) / n + z^2 / 4).
    Clip to [0, 1]; the lower end is exactly 0 when failures == 0 and the upper end
    exactly 1 when failures == shots. Raise ValueError unless 0 <= failures <= shots and shots > 0.
    """
    raise NotImplementedError("wilson_interval: implement this function")


def per_round_error(p_shot: float, rounds: int) -> float:
    """Per-round logical error rate eps with (1 - (1 - 2 eps)^rounds) / 2 = p_shot.

    Assumes independent rounds with a constant rate. Raise ValueError unless
    0 <= p_shot < 1/2 and rounds >= 1.
    """
    raise NotImplementedError("per_round_error: implement this function")


def shots_for_relative_error(p: float, relative_error: float) -> int:
    """Smallest n with standard error sqrt(p (1 - p) / n) <= relative_error * p."""
    raise NotImplementedError("shots_for_relative_error: implement this function")


def surface_memory_circuit(d: int, p: float, rounds: int | None = None) -> stim.Circuit:
    """Rotated surface-code Z-memory with the uniform circuit-level noise in the module docstring."""
    raise NotImplementedError("surface_memory_circuit: implement this function")


def logical_failures(circuit: stim.Circuit, shots: int, seed: int) -> int:
    """Sample with compile_detector_sampler(seed=seed), decode with PyMatching, count wrong shots."""
    raise NotImplementedError("logical_failures: implement this function")


def point_seed(seed: int, d: int, index: int) -> int:
    """Sampler seed of one sweep point: SeedSequence([seed, d, index]).generate_state(1)[0]."""
    return int(np.random.SeedSequence([seed, d, index]).generate_state(1)[0])


def sweep(distances: list[int], ps: list[float], shots: int, seed: int) -> list[dict]:
    """One row per (d, p): surface_memory_circuit(d, p) with rounds = d.

    Row keys: d, p, rounds, shots, failures, p_shot, ci (Wilson 95% tuple),
    p_round (per_round_error of p_shot), seed (point_seed(seed, d, index of p)).
    Rows are ordered by d, then by p in the given order.
    """
    raise NotImplementedError("sweep: implement this function")


def crossing_estimate(ps: list[float], rates_small: list[float], rates_large: list[float]) -> float | None:
    """Where the larger code's curve crosses the smaller code's, by log-log interpolation.

    Let g_i = ln(rates_large[i]) - ln(rates_small[i]). At the first i with
    g_i < 0 <= g_{i+1} interpolate linearly in ln p and return the p with g = 0.
    Return None if there is no such sign change or a rate is zero.
    """
    raise NotImplementedError("crossing_estimate: implement this function")

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

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()

import math

import numpy as np
import pytest
import stim
from scipy.stats import binomtest


# --- statistics -----------------------------------------------------------

@pytest.mark.parametrize("k,n", [(0, 100), (1, 100), (7, 1000), (50, 100), (999, 1000), (1000, 1000)])
def test_wilson_matches_scipy(k, n):
    lo, hi = target.wilson_interval(k, n)
    ref = binomtest(k, n).proportion_ci(confidence_level=0.95, method="wilson")
    assert lo == pytest.approx(ref.low, abs=1e-9)
    assert hi == pytest.approx(ref.high, abs=1e-9)


def test_wilson_zero_failures_is_an_upper_bound():
    z = 1.959963984540054
    lo, hi = target.wilson_interval(0, 2000)
    assert lo == 0.0
    assert hi == pytest.approx(z * z / (2000 + z * z))
    with pytest.raises(ValueError):
        target.wilson_interval(5, 4)


def test_wilson_coverage_by_simulation():
    rng = np.random.default_rng(11)
    p, n, trials = 0.01, 400, 4000
    ks = rng.binomial(n, p, size=trials)
    covered = np.mean([lo <= p <= hi for lo, hi in (target.wilson_interval(int(k), n) for k in ks)])
    assert 0.92 <= covered <= 0.98  # nominal 95%; Wilson is close even for n p = 4


@pytest.mark.parametrize("eps,rounds", [(0.001, 1), (0.001, 10), (0.02, 7), (0.1, 25)])
def test_per_round_inverts_the_composition_law(eps, rounds):
    # Independent forward computation: compose `rounds` independent flips by
    # iterating the two-state Markov chain.
    p = 0.0
    for _ in range(rounds):
        p = p * (1 - eps) + (1 - p) * eps
    assert target.per_round_error(p, rounds) == pytest.approx(eps, rel=1e-9)


def test_per_round_limits_and_validation():
    assert target.per_round_error(0.123, 1) == pytest.approx(0.123)
    assert target.per_round_error(0.0, 5) == 0.0
    # For small rates the conversion is close to dividing by the number of rounds.
    assert target.per_round_error(1e-4, 10) == pytest.approx(1e-5, rel=1e-3)
    with pytest.raises(ValueError):
        target.per_round_error(0.5, 3)


@pytest.mark.parametrize("p,rel", [(1e-3, 0.1), (0.02, 0.05), (0.3, 0.2)])
def test_shots_for_relative_error(p, rel):
    n = target.shots_for_relative_error(p, rel)
    assert math.sqrt(p * (1 - p) / n) <= rel * p
    assert math.sqrt(p * (1 - p) / (n - 1)) > rel * p


# --- the simulation pipeline ----------------------------------------------

def code_capacity_repetition(d, p):
    """Bit flips on d data qubits, perfect readout: logical failure = more than d/2 flips."""
    c = stim.Circuit()
    c.append("R", range(d))
    c.append("X_ERROR", range(d), p)
    c.append("M", range(d))
    for i in range(d - 1):
        c.append("DETECTOR", [stim.target_rec(-d + i), stim.target_rec(-d + i + 1)])
    c.append("OBSERVABLE_INCLUDE", [stim.target_rec(-1)], 0)
    return c


@pytest.mark.parametrize("d,p", [(3, 0.1), (5, 0.1), (7, 0.15)])
def test_pipeline_reproduces_exact_repetition_code_rate(d, p):
    shots = 50_000
    failures = target.logical_failures(code_capacity_repetition(d, p), shots, seed=21)
    exact = sum(math.comb(d, k) * p**k * (1 - p) ** (d - k) for k in range(d // 2 + 1, d + 1))
    # A 99.99% Wilson interval (z = 3.89) must contain the exact value.
    lo, hi = target.wilson_interval(failures, shots, z=3.890591886413094)
    assert lo <= exact <= hi


def test_circuit_noise_model():
    c = target.surface_memory_circuit(3, 0.002)
    text = str(c)
    for channel in ("DEPOLARIZE1(0.002)", "DEPOLARIZE2(0.002)", "X_ERROR(0.002)"):
        assert channel in text
    # Z memory: (d^2-1)/2 Z detectors in round 1, d^2-1 per later round, (d^2-1)/2 at readout.
    assert c.num_detectors == (3 * 3 - 1) * 3
    assert len(c.shortest_graphlike_error()) == 3


def test_sweep_rows_and_reproducibility():
    ps = [0.004, 0.014]
    rows = target.sweep([3, 5], ps, 2_000, seed=5)
    assert [(r["d"], r["p"]) for r in rows] == [(3, 0.004), (3, 0.014), (5, 0.004), (5, 0.014)]
    assert len({r["seed"] for r in rows}) == 4
    for r in rows:
        assert r["rounds"] == r["d"] and r["shots"] == 2_000
        assert r["p_shot"] == r["failures"] / r["shots"]
        assert r["ci"][0] <= r["p_shot"] <= r["ci"][1]
        assert r["p_round"] == pytest.approx(target.per_round_error(r["p_shot"], r["d"]))
        assert r["seed"] == target.point_seed(5, r["d"], ps.index(r["p"]))
    again = target.sweep([3, 5], ps, 2_000, seed=5)
    assert [r["failures"] for r in again] == [r["failures"] for r in rows]


def test_curves_cross_between_the_end_points():
    ps = [0.004, 0.009, 0.014]
    rows = target.sweep([3, 5], ps, 20_000, seed=2026)
    small = [r for r in rows if r["d"] == 3]
    large = [r for r in rows if r["d"] == 5]
    # Statistical statements, not hard-coded numbers: at the lowest p the larger code is
    # better and at the highest p it is worse, with non-overlapping 95% intervals.
    assert large[0]["ci"][1] < small[0]["ci"][0]
    assert large[-1]["ci"][0] > small[-1]["ci"][1]
    crossing = target.crossing_estimate(ps, [r["p_shot"] for r in small], [r["p_shot"] for r in large])
    assert crossing is not None and ps[0] < crossing < ps[-1]
    # Rates rise with p for each distance (end points well separated).
    for curve in (small, large):
        assert curve[0]["ci"][1] < curve[-1]["ci"][0]


def test_crossing_estimate_on_exact_power_laws():
    ps = [0.002, 0.005, 0.02, 0.05]
    small = [0.3 * (p / 0.01) ** 2 for p in ps]
    large = [0.3 * (p / 0.01) ** 3 for p in ps]
    assert target.crossing_estimate(ps, small, large) == pytest.approx(0.01, rel=1e-12)
    assert target.crossing_estimate(ps, large, small) is None  # never crosses upward
    assert target.crossing_estimate(ps, [0.0] + small[1:], large) is None

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 7-round memory experiment has per-shot logical error rate pshot=0.08p_{\text{shot}} = 0.08. Assuming independent rounds with a constant rate, what is the per-round logical error rate ε\varepsilon?

    1 pt
  2. A simulation observes 0 logical failures in 5,000 shots. What is the upper end of the two-sided 95% Wilson interval?

    1 pt
  3. How many shots are needed to estimate a logical error rate of p=2×10−4p = 2\times10^{-4} with a relative standard error of at most 5% (smallest nn with p(1−p)/n≤0.05 p\sqrt{p(1-p)/n} \le 0.05\,p)?

    1 pt
  4. Run the reference sweep from the exercise README with your implementation: sweep([3, 5], [0.004, 0.006, 0.008, 0.010, 0.012, 0.014], shots=40_000, seed=2026), then crossing_estimate on the per-shot rates (p_shot). Enter the estimate.

    2 pts

    Computed by running exercise “threshold-sweep” on your computer.

  5. From the same sweep, apply crossing_estimate to the per-round rates (p_round). Enter the estimate.

    2 pts

    Computed by running exercise “threshold-sweep” on your computer.

  6. Why is the crossing of the d=3d = 3 and d=5d = 5 curves not 'the surface-code threshold'? Select every valid reason.

    1 pt

    Select all that apply.

  7. Which description of the threshold reported by Wang, Fowler and Hollenberg (2011) is accurate?

    1 pt
  8. A colleague's table lists pL=0p_L = 0 for d=7d = 7 at p=0.001p = 0.001 from 10,000 shots. What should the entry say?

    1 pt

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

References

  1. Edwin B. Wilson (1927). Probable Inference, the Law of Succession, and Statistical Inference. Journal of the American Statistical Association 22(158), 209-212. doi:10.1080/01621459.1927.10502953
  2. Eric Dennis et al. (2002). Topological quantum memory. Journal of Mathematical Physics 43, 4452-4505. doi:10.1063/1.1499754
  3. David S. Wang, Austin G. Fowler, Lloyd C. L. Hollenberg (2011). Surface code quantum computing with error rates over 1%. Physical Review A 83, 020302(R). doi:10.1103/PhysRevA.83.020302
  4. Google Quantum AI (2023). Suppressing quantum errors by scaling a surface code logical qubit. Nature 614, 676-681. doi:10.1038/s41586-022-05434-1
  5. Google Quantum AI and Collaborators (2025). Quantum error correction below the surface code threshold. Nature 638, 920-926. doi:10.1038/s41586-024-08449-y
  6. Dorit Aharonov, Michael Ben-Or (1999). Fault-Tolerant Quantum Computation With Constant Error Rate. arXiv:quant-ph/9906129
  7. Craig Gidney (2021). Stim: a fast stabilizer circuit simulator. Quantum 5, 497. doi:10.22331/q-2021-07-06-497
  8. Oscar Higgott (2022). PyMatching: A Python Package for Decoding Quantum Codes with Minimum-Weight Perfect Matching. ACM Transactions on Quantum Computing 3, 16. doi:10.1145/3505637