Skip to main content
KetQat

Appearance

Lesson 102 h

Resource estimation for fault-tolerant computers

Code distance, space-time volume, factories and run time for a target computation.

After this lesson you can

  • Convert per-experiment logical failure rates from memory simulations into per-round rates and fit a logical-error ansatz to your own seeded data
  • Derive the code distance required by an error budget and explain why it grows only logarithmically with the size of the computation
  • Build a space-time resource estimator that separates simulated, fitted and assumed quantities, including distillation levels, factory count and wall-clock time
  • Perform a one-at-a-time sensitivity analysis and identify which assumptions dominate qubit count and run time
  • Quote published resource estimates together with the physical and architectural assumptions they rest on

Read first: Logical error rates and thresholds, Fault-tolerant quantum computing

What a resource estimate is

"How many qubits does it take?" has no answer without a list of assumptions. A resource estimate is a model that takes a computation (how many logical qubits, how many TT gates, how much failure probability you can tolerate) and a description of the hardware and the error-correction scheme, and returns physical qubit counts and run times. Its value lies less in the headline numbers than in making every assumption explicit and showing which of them matter.

This lesson builds such a model from pieces you have already met: a logical error rate you measure yourself, lattice-surgery time steps, and magic-state distillation. Throughout, each quantity carries one of three labels:

  • Simulated: computed in this course from a stated noise model, decoder and seed.
  • Fitted: a parameter of an ansatz, fitted to simulated data, with the data range stated.
  • Assumed: a modelling choice (cycle time, routing overhead, factory footprint). Assumed values are inputs, not findings, and must be reported as such.

Step 1: a logical error model from your own data

The ansatz

Below threshold, the logical error rate of a distance-dd surface code is commonly modelled as

pL(d)≈A(ppth)(d+1)/2.p_L(d) \approx A\left(\frac{p}{p_\text{th}}\right)^{(d+1)/2}.

The exponent (d+1)/2(d+1)/2 reflects the smallest number of faults that can cause a logical error at odd distance dd, and the form is a standard heuristic in the surface-code literature (Fowler et al.). It is not a theorem. AA absorbs the number of minimum-weight failure paths and pthp_\text{th} plays the role of a threshold, but a value fitted this way is a parameter of the ansatz, not an independently measured threshold. The ansatz is reasonable well below threshold and poor near it, where higher-order fault paths dominate.

Per shot versus per round

A memory experiment of rr rounds reports a failure probability per experiment, PrP_r. A computation needs a rate per round (per code cycle). If each round independently flips the logical observable with probability ε\varepsilon, the observable is wrong after rr rounds when an odd number of flips occurred:

Pr=1−(1−2ε)r2⟺ε=1−(1−2Pr)1/r2.P_r = \frac{1-(1-2\varepsilon)^r}{2} \quad\Longleftrightarrow\quad \varepsilon = \frac{1-(1-2P_r)^{1/r}}{2}.

For small rates ε≈Pr/r\varepsilon \approx P_r/r. Mixing the two units is one of the easiest ways to be wrong by a factor of dd.

Fitting

Taking logarithms with x=(d+1)/2x = (d+1)/2,

ln⁡pL−xln⁡p=ln⁡A−xln⁡pth,\ln p_L - x\ln p = \ln A - x\ln p_\text{th},

which is linear in the unknowns (ln⁡A,ln⁡pth)(\ln A, \ln p_\text{th}). A weighted least-squares fit uses the failure count ff of each point as its weight, since the variance of ln⁡p^L\ln\hat p_L is approximately 1/f1/f for a binomial estimate with few failures. Points with zero failures carry no information about the logarithm and must be left out (or treated with an upper-bound method).

A seeded study

The exercise's default_study(seed=2026) simulates Stim's rotated surface-code Z memory with dd rounds, depolarizing noise of strength pp after every Clifford gate, on idle data qubits before each round, before every measurement and after every reset, and decodes with PyMatching (Gidney, Stim) (Higgott and Gidney), 20,000 shots per point. A few of its simulated points (per-round rates after conversion):

dd pp failures / 20,000 per-round rate
3 0.003 130 2.18×10−32.18\times10^{-3}
5 0.003 76 7.62×10−47.62\times10^{-4}
7 0.003 33 2.36×10−42.36\times10^{-4}
7 0.002 3 2.14×10−52.14\times10^{-5}

The full twelve-point grid (d∈{3,5,7}d\in\{3,5,7\}, p∈{0.002,0.003,0.004,0.005}p\in\{0.002,0.003,0.004,0.005\}) gives the fitted values A≈0.021A \approx 0.021 and pth≈0.0096p_\text{th}\approx 0.0096 (per round). The point with 3 failures shows why weights matter: its relative uncertainty is of order 1/31/\sqrt3, and an unweighted fit would let it pull the parameters as hard as a point with 300 failures. The exercise also asks you to refit on a subset of distances; how far the parameters move is a useful, if crude, measure of the ansatz's systematic error.

Step 2: from an error budget to a code distance

Suppose the computation keeps NtilesN_\text{tiles} logical patches alive for SS logical time steps of dd code cycles each, and we allow a total memory failure probability εmem\varepsilon_\text{mem}. Using a union bound (failures are rare, so probabilities add), we need

Ntiles⋅S⋅d⋅A(ppth)(d+1)/2≤εmem.N_\text{tiles}\cdot S\cdot d\cdot A\left(\frac{p}{p_\text{th}}\right)^{(d+1)/2} \le \varepsilon_\text{mem}.

Solving for dd (ignoring the slowly varying factor dd on the left),

d+12≳ln⁡ ⁣(Ntiles S d A/εmem)ln⁡(pth/p).\frac{d+1}{2} \gtrsim \frac{\ln\!\big(N_\text{tiles}\, S\, d\, A/\varepsilon_\text{mem}\big)}{\ln(p_\text{th}/p)}.

Two consequences follow. The distance grows only logarithmically with the size of the computation NtilesSN_\text{tiles}S, which is why fault tolerance scales at all. And it is inversely proportional to ln⁡(pth/p)\ln(p_\text{th}/p), so improving the physical error rate pays off most when pp is close to threshold.

Worked example (by hand). Take A=0.03A = 0.03, p=10−3p = 10^{-3} and pth=10−2p_\text{th} = 10^{-2} (all assumed for the example), so p/pth=0.1p/p_\text{th} = 0.1. Let Ntiles=200N_\text{tiles} = 200, S=108S = 10^8 steps and εmem=0.005\varepsilon_\text{mem} = 0.005. The condition becomes 200⋅108⋅d⋅0.03⋅10−(d+1)/2≤0.005200\cdot10^8\cdot d\cdot 0.03\cdot 10^{-(d+1)/2}\le 0.005, that is d⋅10−(d+1)/2≤8.3×10−12d\cdot 10^{-(d+1)/2}\le 8.3\times10^{-12}:

  • d=23d=23: 23×10−12=2.3×10−1123\times10^{-12} = 2.3\times10^{-11}, too large;
  • d=25d=25: 25×10−13=2.5×10−1225\times10^{-13} = 2.5\times10^{-12}, which satisfies it.

So d=25d = 25, and the memory failure probability is 200⋅108⋅25⋅0.03⋅10−13=1.5×10−3200\cdot10^8\cdot25\cdot0.03\cdot10^{-13} = 1.5\times10^{-3}. The exercise's estimator reproduces both numbers.

Step 3: space

A rotated surface-code patch of distance dd uses d2d^2 data qubits and d2−1d^2-1 measurement qubits, so about 2d22d^2 physical qubits per tile (Horsman et al.). The algorithm's QQ logical qubits need more than QQ tiles, because lattice surgery requires free tiles for routing joint measurements between patches. Litinski's layouts trade space for speed, from compact blocks that need extra time steps to fast blocks that use roughly twice the tiles (Litinski, game of surface codes). Our model collapses this into one assumed routing factor: tiles =⌈routing factor×Q⌉= \lceil \text{routing factor}\times Q\rceil.

Magic-state factories add their own tiles. How many factories are needed depends on how fast the computation consumes TT states. If the algorithm uses RR states per logical time step and one factory produces an accepted state every tft_f steps, about R tf/pacceptR\,t_f/p_\text{accept} factories are needed. A factory's footprint and duration are again assumed inputs; published factory designs vary widely, and careful designs are much cheaper than early ones (Litinski, magic states).

Step 4: distillation level and time

With a TT count NTN_T and a fraction ff of the budget reserved for TT states, each state may fail with probability at most fε/NTf\varepsilon/N_T. The number of 15-to-1 levels follows from the exact formula of the previous lesson (Bravyi and Kitaev). For raw states with error 10−310^{-3} and a per-state target of 5×10−115\times10^{-11}, one level gives 3.5×10−83.5\times10^{-8}, not enough, and two levels give about 1.5×10−211.5\times10^{-21}, far more than enough; the discreteness of the level count is typical.

Time follows from the step count. If TT states are the bottleneck, the computation takes S=⌈NT/R⌉S = \lceil N_T/R\rceil logical steps of dd code cycles, and the wall-clock time is S⋅d⋅tcycleS\cdot d\cdot t_\text{cycle} with the code-cycle time tcyclet_\text{cycle} an assumed hardware parameter. Real estimates also model the reaction time, the latency of decoding and feeding forward the measurement outcome that decides the SS correction of a TT gadget, which can bound the speed of sequential TT gates.

Putting it together

The estimator in the exercise combines these steps. Here is its core logic in a self-contained form, applied to the worked example:

import math

def estimate(Q, t_count, R, eps, p, A, p_th, cycle_s, routing, f_T, fac_tiles, fac_steps, accept):
    steps = math.ceil(t_count / R)
    tiles = math.ceil(routing * Q)
    factories = math.ceil(R * fac_steps / accept)
    d = 3
    while tiles * steps * d * A * (p / p_th) ** ((d + 1) / 2) > (1 - f_T) * eps:
        d += 2
    qubits = (tiles + factories * fac_tiles) * 2 * d * d
    return d, factories, qubits, steps * d * cycle_s

# Assumed inputs; accept = product of two levels' acceptance at p_raw = 1e-3.
print(estimate(Q=100, t_count=10**8, R=1, eps=0.01, p=1e-3, A=0.03, p_th=1e-2,
               cycle_s=1e-6, routing=2.0, f_T=0.5, fac_tiles=20, fac_steps=6, accept=0.985))

It prints (25, 7, 425000, 2500.0): distance 25, seven factories, 425,000 physical qubits and 2,500 s. Every one of those numbers is conditional on the assumed inputs on the last lines; none is a prediction about a machine.

With the fitted parameters of the seeded study (A≈0.021A\approx0.021, pth≈0.0096p_\text{th}\approx0.0096) instead of the round example values, the estimator also chooses d=25d = 25 for this toy workload. Note what that step involved: the study simulated p≥0.002p\ge 0.002 and the estimate uses p=10−3p = 10^{-3}, an extrapolation of the ansatz outside the data. Published estimates extrapolate too, which is exactly why they must state their models.

Sensitivity analysis

Change one assumption at a time and watch the outputs. For the toy workload with the fitted parameters (results from the exercise's reference solution):

Parameter scaled Factor Distance Physical qubits Run time
(baseline) 1 25 425,000 2,500 s
physical error rate pp 0.5 / 2 19 / 37 245,480 / 930,920 1,900 / 3,700 s
fitted pthp_\text{th} 0.5 / 2 37 / 19 930,920 / 245,480 3,700 / 1,900 s
fitted AA 0.1 / 10 23 / 27 359,720 / 495,720 2,300 / 2,700 s
routing factor 0.5 / 2 25 / 25 300,000 / 675,000 2,500 s
factory tiles 0.5 / 2 25 / 25 337,500 / 600,000 2,500 s
cycle time 0.5 / 2 25 / 25 425,000 1,250 / 5,000 s

Three lessons stand out. The ratio p/pthp/p_\text{th} dominates: a factor of two in either moves the distance by six and the qubit count by more than a factor of two, because qubits scale as d2d^2. The prefactor AA barely matters: a factor of ten changes dd by only two, because it enters through a logarithm. And the cycle time changes nothing but the run time in this model, while routing and factory footprints change nothing but the qubit count. A sensitivity table like this tells a reader which of your assumptions deserves scrutiny.

Published estimates and their assumptions

Published estimates differ by orders of magnitude, mostly because their assumptions and algorithms differ. Quote them only together with those assumptions:

  • Gidney and Ekerå estimated that 2048-bit RSA integers could be factored in about 8 hours with about 20 million noisy qubits, assuming a planar grid with nearest-neighbour connectivity, a physical gate error rate of 10−310^{-3}, a surface-code cycle time of 1 µs and a reaction time of 10 µs (Gidney and Ekerå).
  • Gidney later estimated, under the same physical assumptions, that the same task could take less than a week with less than a million noisy qubits, the reduction coming mainly from approximate residue arithmetic, yoked surface codes for idle qubits and magic-state cultivation instead of distillation; the longer run time comes from more Toffoli gates and fewer factories (Gidney, 2025). The two estimates illustrate a space-time trade-off, not a contradiction.
  • Beverland and co-authors built a layered resource-estimation framework and, for three application workloads and a range of qubit parameter sets, found that hundreds of thousands to millions of physical qubits are needed; they identify qubit size, speed and controllability as critical parameters (Beverland et al.).

None of these is a measurement of an existing device, and none transfers to a different error rate, connectivity or cycle time without redoing the estimate.

Common mistakes

  • Mixing per-shot and per-round rates. A memory experiment with dd rounds reports a per-experiment probability; convert it before multiplying by the number of rounds in a computation.
  • Treating a fitted pthp_\text{th} as a measured threshold. It is a parameter of an ansatz with a fixed exponent. Report the data range it came from, and expect it to move if you refit on other distances.
  • Fitting zero-failure points in log space. ln⁡0\ln 0 is undefined; leave them out or use an upper-bound method, and say which.
  • Extrapolating silently. Using a fit at pp outside the simulated range is sometimes necessary; doing it without saying so is not acceptable.
  • Reporting a single number. An estimate without its sensitivity to pp, pthp_\text{th} and the layout assumptions hides its own uncertainty.
  • Leaving things out without saying so. Our model ignores routing congestion, factory-internal Clifford errors, decoder latency and throughput, leakage and correlated noise. Each can matter; a careful report lists them.

Summary

  • A resource estimate turns a workload and stated assumptions into physical qubits and time. Label every quantity as simulated, fitted or assumed.
  • Fit pL=A(p/pth)(d+1)/2p_L = A(p/p_\text{th})^{(d+1)/2} to per-round rates from your own seeded simulations, weighting by failure counts.
  • The required distance grows logarithmically with the size of the computation and inversely with ln⁡(pth/p)\ln(p_\text{th}/p). Qubits scale as 2d22d^2 per tile.
  • Time is steps × dd × cycle time. TT-state supply often sets the step count, and factories add space.
  • Sensitivity analysis shows that p/pthp/p_\text{th} dominates and AA hardly matters. Published estimates are meaningful only with their assumptions.

What next

The capstone asks you to implement a decoder of your own, benchmark it against PyMatching with honest statistics, and publish a reproducible report of the kind whose numbers could feed an estimate like this one.

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 resource estimator fitted to your own surface-code simulations

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

You will build, end to end, the kind of estimate that papers summarise as "N physical qubits and T hours": simulate surface-code memories with Stim and PyMatching, fit a logical-error model to your data, choose a code distance for an error budget, count tiles and factories, convert to wall-clock time, and see which assumptions dominate the answer.

Every number your estimator produces is conditional on inputs you choose. The README and the lesson label each one: simulated (you computed it), fitted (a parameter of an ansatz fitted to your simulations) or assumed (a modelling choice you must state).

What you implement (starter.py)

Simulation and fit

Function Contract
memory_circuit(distance, p, rounds=None) Stim's surface_code:rotated_memory_z with the uniform noise model in the module docstring; rounds defaults to distance.
dem_arrays(dem) Mechanism probabilities and sparse detector/observable incidence matrices, in the order of dem.flattened().
sample_dem(dem, shots, seed, chunk=4096) Platform-independent sampling with NumPy, following the exact recipe in the docstring.
logical_failures(distance, p, shots, seed, rounds=None) Failures of PyMatching on sample_dem data.
per_round_rate(p_shot, rounds) Converts a per-experiment failure probability into a per-round one, assuming independent rounds.
fit_ansatz(distances, error_rates, rates, weights=None) Weighted least squares for pL=A (p/pth)(d+1)/2p_L = A\,(p/p_\text{th})^{(d+1)/2} in log space.
default_study(seed=2026, ...) Runs the grid d∈{3,5,7}d\in\{3,5,7\}, p∈{0.002,…,0.005}p\in\{0.002,\dots,0.005\}, 20,000 shots per point, and fits the per-round ansatz (about 6 s).

Estimation

Function Contract
required_distance(p, A, p_th, target_per_round) Smallest odd dd meeting a per-round target.
distill_15_to_1(p) The exact 15-to-1 formula from the previous lesson's exercise.
estimate_resources(workload, params) The model in the docstring: distillation levels, steps, tiles, factories, distance, physical qubits, run time, and the two failure contributions.
sensitivity(workload, params, name, factors) Re-runs the estimate with one parameter scaled.

What the checks verify

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

  1. The circuit has the expected detector count, (d2−1)×rounds(d^2-1)\times\text{rounds}, and no detection events without noise.
  2. sample_dem follows the recipe exactly (chunking does not change samples).
  3. Your DEM sampler and Stim's circuit sampler agree statistically (per-detector rates and PyMatching failure counts within 5 standard errors). This is the independent check that the DEM route samples the same distribution.
  4. per_round_rate inverts the closed form for independent rounds.
  5. fit_ansatz recovers known AA and pthp_\text{th} exactly from synthetic data and refuses zero rates.
  6. A small seeded study reproduces exactly when rerun, larger dd helps below threshold, and the fitted pthp_\text{th} lies in a broad sanity range.
  7. required_distance matches hand-computed cases.
  8. The estimator's distance is the smallest odd one meeting the memory budget, and its qubit count and run time follow the stated formulas.
  9. Sensitivities move in the expected directions.

Tasks after the checks pass

  1. Run default_study() and record the fitted AA and pthp_\text{th} (the quiz asks for pthp_\text{th}). Plot per-round rates against pp on log axes for each dd together with the fitted lines. Where does the fixed-exponent ansatz fit worst, and why?
  2. Refit using only d∈{5,7}d \in \{5, 7\}. How much do the parameters move? Treat that change as a crude systematic uncertainty of the fit.
  3. Use your fit in estimate_resources for the toy workload {"logical_qubits": 100, "t_count": 10**8, "t_per_step": 1, "error_budget": 0.01} with assumed parameters p = 1e-3, cycle_time_s = 1e-6, routing_factor = 2, distillation_fraction = 0.5, factory_tiles = 20, factory_steps = 6. Note that p=10−3p = 10^{-3} lies below your simulated range: the ansatz is being extrapolated, which is exactly how published estimates work and exactly why they state their assumptions.
  4. Produce a sensitivity table for p, p_th, A, routing_factor, factory_tiles and cycle_time_s. Which single assumption changes the qubit count most? Which changes nothing but the run time?
  5. Write three sentences that state your estimate the way a careful paper would: noise model, decoder, fitted parameters with the data they came from, every assumed parameter, and what the model leaves out (routing congestion, factory-internal errors, decoder latency, leakage, correlated noise).

Reproducibility

sample_dem uses NumPy's default_rng (PCG64), which is platform independent, on top of Stim's detector error model, which is deterministic. With the pinned versions (Stim 1.16.0, PyMatching 2.4.0, NumPy 2.5.5) a given seed is designed to give the same failure counts on every machine; the reference values were produced on one machine (Apple silicon, macOS), so report any mismatch you observe. Stim's built-in sampler is faster but, as its documentation states, seeded results may differ across Stim versions and across machines with different SIMD widths.

Terminal
python -m pip install numpy scipy stim pymatching pytest

starter.py

Python
"""Starter: a surface-code resource estimator fitted to your own simulations.

Noise model used throughout (state it whenever you quote a number): Stim's
generated rotated surface-code Z-memory circuit with
    after_clifford_depolarization = p, before_round_data_depolarization = p,
    before_measure_flip_probability = p, after_reset_flip_probability = p,
and d rounds of syndrome extraction for distance d. Decoder: PyMatching (MWPM)
built from the circuit's detector error model.

Sampling is done from the detector error model with NumPy's PCG64 generator, so a
seed gives the same samples on every machine with the same Stim, NumPy and
PyMatching versions (Stim's own sampler is reproducible only on the same machine
and Stim version).

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

from __future__ import annotations

import math

import numpy as np
import pymatching
import scipy.sparse as sp
import stim

#: Weight enumerator of the [15,11,3] Hamming code (see the previous lesson's exercise).
HAMMING15_ENUMERATOR = (1, 0, 0, 35, 105, 168, 280, 435, 435, 280, 168, 105, 35, 0, 0, 1)


def memory_circuit(distance: int, p: float, rounds: int | None = None) -> stim.Circuit:
    """Rotated surface-code Z-memory circuit with the module's uniform noise model."""
    raise NotImplementedError


def dem_arrays(dem: stim.DetectorErrorModel):
    """(probabilities, detector matrix, observable matrix) of a detector error model.

    Mechanisms are the `error` instructions of dem.flattened(), in order. The detector
    matrix has shape (num_detectors, num_mechanisms) and the observable matrix
    (num_observables, num_mechanisms); entry 1 when the mechanism flips it. Decomposition
    separators (^) are ignored: a mechanism flips the XOR of all its components."""
    raise NotImplementedError


def sample_dem(dem: stim.DetectorErrorModel, shots: int, seed: int, chunk: int = 4096):
    """Sample (detection events, observable flips) as boolean arrays.

    Recipe (follow it exactly so seeds reproduce): rng = numpy.random.default_rng(seed);
    for row blocks of at most `chunk` shots, u = rng.random((rows, num_mechanisms));
    mechanism j fires in a shot iff u[shot, j] < p_j. Drawing in row blocks gives the
    same numbers as one rng.random((shots, num_mechanisms)) call."""
    raise NotImplementedError


def logical_failures(distance: int, p: float, shots: int, seed: int, rounds: int | None = None) -> int:
    """Number of shots whose PyMatching prediction of the logical observable is wrong."""
    raise NotImplementedError


def per_round_rate(p_shot: float, rounds: int) -> float:
    """Per-round logical flip probability e such that an odd number of flips in
    `rounds` independent rounds has probability p_shot: (1 - (1 - 2 p_shot)^(1/rounds)) / 2."""
    raise NotImplementedError


def fit_ansatz(distances, error_rates, rates, weights=None) -> dict:
    """Weighted least-squares fit of rate = A * (p / p_th) ** ((d + 1) / 2).

    Taking logs, ln(rate) - x ln(p) = ln(A) - x ln(p_th) with x = (d + 1) / 2, which is
    linear in (ln A, ln p_th). weights (default: all 1) should be the failure counts,
    which approximate the inverse variance of ln(rate). Points with rate 0 must be
    removed by the caller. Returns {"A", "p_th"}."""
    raise NotImplementedError


def default_study(seed: int = 2026, distances=(3, 5, 7), error_rates=(0.002, 0.003, 0.004, 0.005), shots: int = 20000) -> dict:
    """Simulate every (d, p) point with seed + 1000 * d + round(p * 1e6) and fit the
    per-round ansatz. Returns {"points": [{"distance", "p", "shots", "failures",
    "per_shot", "per_round"}], "fit": {"A", "p_th"}}; points with zero failures are
    reported but excluded from the fit."""
    raise NotImplementedError


def required_distance(p: float, A: float, p_th: float, target_per_round: float, d_max: int = 151) -> int:
    """Smallest odd d >= 3 with A * (p / p_th) ** ((d + 1) / 2) <= target_per_round.
    Raises ValueError when p >= p_th or when d_max is not enough."""
    raise NotImplementedError


def distill_15_to_1(p: float):
    """(p_out, p_accept) of one 15-to-1 level: independent Z errors, perfect Cliffords."""
    raise NotImplementedError


def estimate_resources(workload: dict, params: dict) -> dict:
    """Space-time resource estimate. Every input is an assumption the caller states.

    workload: logical_qubits Q, t_count N_T, t_per_step R (T states consumed per
              logical time step), error_budget eps (total failure probability).
    params:   p, A, p_th (per-round ansatz), cycle_time_s, routing_factor (tiles per
              algorithmic qubit, >= 1), distillation_fraction f (share of eps given to
              T states), factory_tiles and factory_steps (footprint in tiles and duration
              in logical steps of one factory producing one output state),
              p_inject (raw magic-state error; defaults to p).

    Model:
      levels     smallest number of 15-to-1 levels with p_out <= f * eps / N_T
      steps      ceil(N_T / R) logical time steps of d code cycles each
      data_tiles ceil(routing_factor * Q)
      factories  ceil(R * factory_steps / accept), accept = product of the levels'
                 acceptance probabilities (a conservative simplification)
      d          smallest odd d with data_tiles * steps * d * p_round(d) <= (1 - f) * eps
      qubits     (data_tiles + factories * factory_tiles) * 2 * d**2, rounded up
      runtime_s  steps * d * cycle_time_s
    Factory-internal Clifford errors are not modelled (assumed suppressed by the
    factory's own distance)."""
    raise NotImplementedError


def sensitivity(workload: dict, params: dict, name: str, factors=(0.5, 2.0)) -> list:
    """Re-run estimate_resources with params[name] multiplied by each factor. Returns
    [{"factor", "value", "distance", "physical_qubits", "runtime_s"}]."""
    raise NotImplementedError

test_exercise.py

Python
"""Checks for the resource-estimator exercise.

Independent references: Stim's own circuit sampler (a different sampling method
from your detector-error-model sampler), exact synthetic data for the fit, closed
forms for the per-round conversion and the required distance, and invariants of
the estimator (the chosen distance meets the budget and the next smaller one
does not; the qubit count follows the stated footprint).
"""

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

import numpy as np
import pymatching
import pytest


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

WORKLOAD = {"logical_qubits": 100, "t_count": 10**8, "t_per_step": 1, "error_budget": 0.01}
PARAMS = {"p": 1e-3, "A": 0.03, "p_th": 0.01, "cycle_time_s": 1e-6, "routing_factor": 2.0,
          "distillation_fraction": 0.5, "factory_tiles": 20, "factory_steps": 6}


def test_circuit_and_noise_model():
    c = target.memory_circuit(3, 0.001)
    assert c.num_observables == 1
    # Z memory: (d^2-1)/2 Z checks in round 1 and in the final data readout, all d^2-1 checks in between
    assert c.num_detectors == (3 * 3 - 1) * 3
    noiseless = target.memory_circuit(3, 0.0)
    assert not noiseless.compile_detector_sampler(seed=1).sample(100).any()
    assert target.memory_circuit(5, 0.001, rounds=2).num_detectors == (5 * 5 - 1) * 2


def test_dem_sampler_follows_the_recipe():
    dem = target.memory_circuit(3, 0.004).detector_error_model(decompose_errors=True)
    probs, H, L = target.dem_arrays(dem)
    errors = [inst for inst in dem.flattened() if inst.type == "error"]
    assert len(probs) == len(errors) and H.shape == (dem.num_detectors, len(errors)) and L.shape[0] == 1
    assert np.allclose(probs, [e.args_copy()[0] for e in errors])
    d1, o1 = target.sample_dem(dem, 3000, seed=9, chunk=700)
    d2, o2 = target.sample_dem(dem, 3000, seed=9)
    assert np.array_equal(d1, d2) and np.array_equal(o1, o2), "chunking must not change the samples"
    u = np.random.default_rng(9).random((3000, len(probs)))
    fired = (u < probs).astype(np.int64)
    assert np.array_equal(d1, (fired @ H.T.toarray().astype(np.int64)) % 2 == 1)


def test_dem_sampling_agrees_with_stim_circuit_sampling():
    circuit = target.memory_circuit(3, 0.006)
    dem = circuit.detector_error_model(decompose_errors=True)
    shots = 40000
    dets, obs = target.sample_dem(dem, shots, seed=1)
    sd, so = circuit.compile_detector_sampler(seed=2).sample(shots, separate_observables=True)
    for a, b in ((dets.mean(axis=0), sd.mean(axis=0)), (obs.mean(axis=0), so.mean(axis=0))):
        se = np.sqrt((a * (1 - a) + b * (1 - b)) / shots) + 1e-12
        assert np.all(np.abs(a - b) < 5 * se)
    matcher = pymatching.Matching.from_detector_error_model(dem)
    f_mine = target.logical_failures(3, 0.006, shots, seed=1)
    f_stim = int(np.any(matcher.decode_batch(sd) != so, axis=1).sum())
    p_pool = (f_mine + f_stim) / (2 * shots)
    assert abs(f_mine - f_stim) / shots < 5 * math.sqrt(2 * p_pool * (1 - p_pool) / shots)


def test_per_round_rate():
    assert target.per_round_rate(0.1, 1) == pytest.approx(0.1)
    for e, r in ((1e-3, 5), (0.02, 9)):
        p_shot = (1 - (1 - 2 * e) ** r) / 2
        assert target.per_round_rate(p_shot, r) == pytest.approx(e, rel=1e-10)
    assert target.per_round_rate(0.01, 7) < 0.01 / 7 * 1.01


def test_fit_recovers_known_parameters():
    A, p_th = 0.07, 0.008
    ds = [3, 5, 7, 3, 5, 7]
    ps = [0.002, 0.002, 0.002, 0.004, 0.004, 0.004]
    rates = [A * (p / p_th) ** ((d + 1) / 2) for d, p in zip(ds, ps)]
    fit = target.fit_ansatz(ds, ps, rates, weights=[10, 20, 30, 40, 50, 60])
    assert fit["A"] == pytest.approx(A, rel=1e-9) and fit["p_th"] == pytest.approx(p_th, rel=1e-9)
    with pytest.raises(ValueError):
        target.fit_ansatz([3, 5], [0.003, 0.003], [0.01, 0.0])


def test_small_study_is_sane():
    study = target.default_study(seed=7, distances=(3, 5), error_rates=(0.003, 0.005), shots=6000)
    assert len(study["points"]) == 4
    rate = {(pt["distance"], pt["p"]): pt["per_round"] for pt in study["points"]}
    assert rate[(5, 0.003)] < rate[(3, 0.003)], "below threshold, larger d must help"
    for pt in study["points"]:
        assert pt["per_shot"] == pt["failures"] / pt["shots"]
    assert 0.003 < study["fit"]["p_th"] < 0.03, "a broad sanity range, not a precise threshold claim"
    again = target.default_study(seed=7, distances=(3, 5), error_rates=(0.003, 0.005), shots=6000)
    assert again["points"] == study["points"], "seeded runs must reproduce exactly"


def test_required_distance():
    # A (p/p_th)^((d+1)/2) with p/p_th = 0.1 and A = 0.1 is 10^-(1 + (d+1)/2):
    # 1e-11 at d = 19 and 1e-12 at d = 21, so a target of 2e-12 needs d = 21.
    assert target.required_distance(1e-3, 0.1, 1e-2, 2e-12) == 21
    assert target.required_distance(1e-3, 0.1, 1e-2, 2e-3) == 3
    with pytest.raises(ValueError):
        target.required_distance(0.02, 0.1, 0.01, 1e-9)


def test_estimator_invariants():
    est = target.estimate_resources(WORKLOAD, PARAMS)
    d = est["distance"]
    assert d % 2 == 1 and d >= 3
    tiles = est["data_tiles"]
    assert tiles == 200
    p_round = lambda dd: PARAMS["A"] * (PARAMS["p"] / PARAMS["p_th"]) ** ((dd + 1) / 2)
    budget = (1 - PARAMS["distillation_fraction"]) * WORKLOAD["error_budget"]
    assert tiles * est["steps"] * d * p_round(d) <= budget
    if d > 3:
        assert tiles * est["steps"] * (d - 2) * p_round(d - 2) > budget
    assert est["physical_qubits"] == (tiles + est["factories"] * PARAMS["factory_tiles"]) * 2 * d * d
    assert est["runtime_s"] == pytest.approx(est["steps"] * d * PARAMS["cycle_time_s"])
    assert est["distillation_levels"] == 2  # raw 1e-3 -> 3.5e-8 > 5e-11 per T -> second level
    assert est["distillation_failure"] <= PARAMS["distillation_fraction"] * WORKLOAD["error_budget"]
    p_out, accept = target.distill_15_to_1(1e-4)
    assert p_out / 1e-12 == pytest.approx(35, rel=1e-2) and accept == pytest.approx(1 - 15e-4, rel=1e-4)


def test_sensitivity_directions():
    by_p = target.sensitivity(WORKLOAD, PARAMS, "p", factors=(0.5, 1.0, 2.0))
    assert [r["distance"] for r in by_p] == sorted(r["distance"] for r in by_p)
    by_cycle = target.sensitivity(WORKLOAD, PARAMS, "cycle_time_s", factors=(1.0, 3.0))
    assert by_cycle[1]["runtime_s"] == pytest.approx(3 * by_cycle[0]["runtime_s"])
    assert by_cycle[1]["physical_qubits"] == by_cycle[0]["physical_qubits"]
    by_route = target.sensitivity(WORKLOAD, PARAMS, "routing_factor", factors=(1.0, 2.0))
    assert by_route[1]["physical_qubits"] > by_route[0]["physical_qubits"]

Check your understanding

7 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. Run default_study(seed=2026) from the exercise with its default grid (d∈{3,5,7}d \in \{3,5,7\}, p∈{0.002,0.003,0.004,0.005}p\in\{0.002, 0.003, 0.004, 0.005\}, 20,000 shots per point, NumPy DEM sampling, PyMatching). Enter the fitted per-round parameter pthp_\text{th}.

    1 pt

    Computed by running exercise “surface-code-resource-estimator” on your computer.

  2. A distance-7 memory experiment with 7 rounds fails in 1.09% of shots (P7=0.0109P_7 = 0.0109). Assuming independent rounds, what is the per-round logical error rate ε\varepsilon, from Pr=(1−(1−2ε)r)/2P_r = (1-(1-2\varepsilon)^r)/2? Enter it in units of 10−310^{-3}.

    1 pt
  3. Using pL(d)=A(p/pth)(d+1)/2p_L(d) = A(p/p_\text{th})^{(d+1)/2} per round with A=0.03A = 0.03 and p/pth=0.2p/p_\text{th} = 0.2, what is the smallest odd distance with pL(d)≤10−15p_L(d)\le 10^{-15}?

    1 pt
  4. In the lesson's sensitivity table, which scaled input changed the code distance least for a given factor?

    1 pt
  5. You want to cite Gidney and Ekerå's estimate of 20 million noisy qubits and 8 hours for factoring 2048-bit RSA integers. Which of the following must accompany the numbers for the citation to be accurate? Select all that apply.

    1 pt

    Select all that apply.

  6. One point of your study, at d=7d=7 and p=0.002p=0.002, observed zero logical failures in 20,000 shots. How should the log-space weighted fit treat it?

    1 pt
  7. Why does the required code distance grow only logarithmically with the number of logical operations in the computation?

    1 pt

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

References

  1. 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
  2. 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
  3. 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
  4. Daniel Litinski (2019). Magic State Distillation: Not as Costly as You Think. Quantum 3, 205. doi:10.22331/q-2019-12-02-205
  5. 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
  6. Craig Gidney, Martin Ekerå (2021). How to factor 2048 bit RSA integers in 8 hours using 20 million noisy qubits. Quantum 5, 433 (arXiv preprint 2019). doi:10.22331/q-2021-04-15-433
  7. Craig Gidney (2025). How to factor 2048 bit RSA integers with less than a million noisy qubits. arXiv:2505.15917
  8. Michael E. Beverland et al. (2022). Assessing requirements to scale to practical quantum advantage. arXiv:2211.07629
  9. Craig Gidney (2021). Stim: a fast stabilizer circuit simulator. Quantum 5, 497. doi:10.22331/q-2021-07-06-497
  10. Oscar Higgott, Craig Gidney (2025). Sparse Blossom: correcting a million errors per core second with minimum-weight matching. Quantum 9, 1600. doi:10.22331/q-2025-01-20-1600