Skip to content

qndk.quantum_error_correction

The fault-tolerant path. Lays logical qubits out as real surface-code patches, models what happens when a patch is split across QPUs, and prices a completed run as a Total Logical Error Rate.

This is the package that moves the SDK from how long does this take to and can I trust the answer.

Why this exists

Error correction only pays off below a break-even physical error rate — the threshold. Below it, more code distance lowers the logical error rate exponentially. Above it, a larger code is worse: more physical qubits means more places for an error to start, faster than the extra redundancy corrects them.

Distributing a computation drags that threshold down, because a logical qubit's patch split across two QPUs has a seam — ancillas on the cut that cannot be measured locally, and need a Bell pair delivered across the gap every single error-correction round.

So the network stops being a latency question and becomes part of the physics. That coupling is what this package models.

The four-line workflow

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.simulator.dqc import DQCScheduler
from qndk.quantum_error_correction import (
    fault_tolerant_encode, tler, SurfaceCode, FixedIdleEpr)

circuit = QiskitCircuit("tfim", num_qubits=8, num_trotter_steps=1).circuit
circuit.t(3)                       # one T gate -> one magic state

network = build_clos(
    ports_per_switch=4, qpus_per_rack=1,
    qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"),
    num_magic_factories=1,         # required: T gates need a factory
)

code = SurfaceCode(d=15)
partition = fault_tolerant_encode(circuit, network, code=code,
                                  num_ancilla=1)
result = DQCScheduler(partition).run_simulation()
budget = tler(result, code=code, epr=FixedIdleEpr(k_idle=4))

print(f"TLER at p=1e-4: {budget.total[0]:.3e}")

One code object goes to both the encode stage and the pricing stage, so the two cannot disagree about the physics. That is the whole reason it is an object rather than a number passed twice.

fault_tolerant_encode()

Not itself a partitioning strategy. It takes a partitioner= (defaulting to KernighanLinPartitioner) to decide which circuit qubits go where, and does only the QEC-specific work on top:

  1. Rewrites every T gate into a magic-state consumption event.
  2. Places ancilla qubits, which mediate lattice-surgery operations.
  3. Identifies seams where a patch crosses a QPU boundary.
from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.partition.wbcp import WindowBasedCircuitPartitioner
from qndk.quantum_error_correction import fault_tolerant_encode, SurfaceCode
from qndk.simulator.dqc import DQCScheduler

circuit = QiskitCircuit("tfim", num_qubits=8, num_trotter_steps=1).circuit
circuit.t(2)
network = build_clos(ports_per_switch=4, qpus_per_rack=1,
                     qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"),
                     num_magic_factories=1)

partition = fault_tolerant_encode(
    circuit, network,
    partitioner=WindowBasedCircuitPartitioner,   # swap the layout strategy
    code=SurfaceCode(d=9),
    num_ancilla=2,
)
result = DQCScheduler(partition).run_simulation()
print("magic states consumed:", result.gate_counts()["num_magic"])
print("network unchanged    :", partition.network is network)

It never copies or augments the network it is handed, so partition.network is network always holds — the value cannot be silently dropped the way a returned network could be.

Provision factories at construction time

num_magic_factories belongs to the network because a factory is hardware. Calling fault_tolerant_encode() on a network without one raises, naming the fix. How many T gates round-robin across is however many factories exist, not a separate argument that could disagree.

The two EPR delivery models

Entanglement does not arrive instantly, and how you model the wait changes the answer. Both models put the same question at two fidelities.

FixedIdleEpr PoissonEpr
Parameter k_idle — idle noise multiplier mu — pairs per syndrome round
Mechanism The wait is charged as extra idling; the circuit is untouched Pairs arrive as a Poisson process; some rounds cannot measure the seam at all
Fidelity A conservative fudge factor Faithful — the circuit's behaviour changes
Off-table rows Computed on demand via Stim (minutes to hours) Raises; extending means re-running the sweep
Fast path k_idle ∈ {1,2,4,8,16}, lam_seam ∈ mu ∈ {0.2,0.4,0.6,0.8,1.0}, lam_seam ∈
from qndk.quantum_error_correction import FixedIdleEpr, PoissonEpr

models = [FixedIdleEpr(k_idle=1), FixedIdleEpr(k_idle=16),
          PoissonEpr(mu=1.0, policy="async"),
          PoissonEpr(mu=0.2, policy="sync")]
for epr in models:
    params = epr.predictor().params_for(epr)
    print(f"{epr.label:12s} policy={getattr(epr, 'policy', '-'):6s} "
          f"p_th={params['p_th']:.5f} alpha={params['alpha']:.3f}")

Those p_th values are the measured result the package exists to surface. At the default lam_seam=4, the threshold falls from 0.801% at k_idle=1 to 0.272% at k_idle=16 — and at lam_seam=1, from 0.775% to 0.272%. Either way it is close to a threefold reduction: slow entanglement does not just add latency, it shrinks the window of hardware quality in which error correction works at all.

Note that lam_seam moves the number too, so quote both parameters when you report a threshold:

from qndk.quantum_error_correction import FixedIdleEpr

for lam_seam in (1, 4, 8):
    row = []
    for k_idle in (1, 4, 16):
        epr = FixedIdleEpr(k_idle=k_idle, lam_seam=lam_seam)
        p_th = epr.predictor().params_for(epr)["p_th"]
        row.append(f"k={k_idle:<2d} {p_th * 100:.3f}%")
    print(f"lam_seam={lam_seam}:  " + "   ".join(row))

They are not interchangeable

k_idle=4 and mu=0.2 are not two spellings of the same physical situation, and each model owns a threshold table fitted against its own notion of the seam. A slow FixedIdleEpr setting can land more than an order of magnitude more pessimistic than Poisson at a comparable nominal speed, because it cannot tell "somewhat slower" from "structurally broken".

Seam scheduling policy

PoissonEpr takes a policy:

  • "sync" — every seam ancilla waits for the slowest, on a shared clock.
  • "async" — each measures on whichever round its own pair lands in.

async is better nearly everywhere in the shipped sweep. It is a scheduling decision that recovers real hardware margin.

from qndk.quantum_error_correction import PoissonEpr

for policy in ("sync", "async"):
    epr = PoissonEpr(mu=0.2, lam_seam=1, policy=policy)
    p_th = epr.predictor().params_for(epr)["p_th"]
    print(f"{policy:6s} p_th={p_th:.5f}")

Where the model stops

Below mu = 0.2 the fitted scaling law collapses — code distance stops suppressing error at all — so there is no threshold to extrapolate from. The package raises rather than returning a confident-looking number built on a dead fit. That refusal is a measured result, not missing data.

tler() and the four terms

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.simulator.dqc import DQCScheduler
from qndk.quantum_error_correction import (
    fault_tolerant_encode, tler, SurfaceCode, FixedIdleEpr)

circuit = QiskitCircuit("tfim", num_qubits=8, num_trotter_steps=1).circuit
circuit.t(3)
network = build_clos(ports_per_switch=4, qpus_per_rack=1,
                     qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"),
                     num_magic_factories=1)
code = SurfaceCode(d=15)
partition = fault_tolerant_encode(circuit, network, code=code,
                                  num_ancilla=1)
result = DQCScheduler(partition).run_simulation()
budget = tler(result, code=code, epr=FixedIdleEpr(k_idle=4))

print(f"at p = {budget.p_array[0]:.1e}")
for term in ("local", "remote", "mem", "magic", "total"):
    print(f"  LER_{term:7s} {getattr(budget, term)[0]:.3e}")
print(f"gate counts: local={budget.num_local} remote={budget.num_remote} "
      f"magic={budget.num_magic}")
Term Source
local Gates that ran inside one QPU
remote Gates that crossed the network, carrying the seam penalty
mem Qubits idling and decohering, including all waiting
magic A faulty magic state

Each is an array over a physical-error-rate sweep, so [0] is the value at the lowest p. The flat p_min/p_max/n_p_points keywords control the sweep range.

Why the split matters

The terms do not scale together, and that difference drives engineering decisions. The three code terms fall off as p^((d+1)/2) — at d=15 that is p⁸, very steep. One round of distillation gives 35p³, much shallower. And d does not appear in the magic term at all.

Two lines of different steepness must cross. To the left of the crossing the shallow magic line is the only error left standing, so the total error curve develops a knee — and past that knee, a larger code improves a term that had already stopped mattering.

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import MagicFactorySpec, QPUSpec, build_clos
from qndk.simulator.dqc import DQCScheduler
from qndk.quantum_error_correction import (
    fault_tolerant_encode, tler, SurfaceCode, FixedIdleEpr)


def price(distill_rounds):
    circuit = QiskitCircuit("gf2m", m=4, operation="multiply").circuit
    for q in (1, 2, 3):
        circuit.t(q)
    network = build_clos(
        num_levels=3, ports_per_switch=2, qpus_per_rack=4,
        qpu_spec=QPUSpec(comp_qubits=6, connectivity="all2all"),
        magic_factory_spec=MagicFactorySpec(distill_rounds=distill_rounds),
        num_magic_factories=1)
    partition = fault_tolerant_encode(circuit, network, num_ancilla=2)
    return DQCScheduler(partition).run_simulation()


for rounds in (1, 2):
    result = price(rounds)
    row = " ".join(
        f"d={d}: {tler(result, code=SurfaceCode(d=d), epr=FixedIdleEpr(k_idle=4)).total[0]:.2e}"
        for d in (15, 21))
    print(f"{rounds}-round factory -> {row}")

With a one-round factory, d=15 and d=21 land on the same total — doubling the physical qubit count improves the answer by nothing, because magic states were the limit. A second distillation round cubes the magic exponent again (3 → 9, now steeper than the code's 8), the knee disappears, and code distance starts paying again.

min_distill_rounds() computes how many rounds are needed to keep magic states from being the limit.

TlerSweep

Runs the budget over a grid of code distances and delivery parameters, and owns the comparison plots.

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.simulator.dqc import DQCScheduler
from qndk.quantum_error_correction import (
    fault_tolerant_encode, FixedIdleEpr, SurfaceCode, TlerSweep)

circuit = QiskitCircuit("tfim", num_qubits=8, num_trotter_steps=1).circuit
circuit.t(2)
network = build_clos(ports_per_switch=4, qpus_per_rack=1,
                     qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"),
                     num_magic_factories=1)
partition = fault_tolerant_encode(circuit, network,
                                  code=SurfaceCode(d=9), num_ancilla=1)
result = DQCScheduler(partition).run_simulation()

sweep = TlerSweep(result, code=[SurfaceCode(d=d) for d in (5, 9, 15, 21)],
                  epr=[FixedIdleEpr(k_idle=k) for k in (1, 4, 16)])
print(f"{len(sweep.results)} curves")
for r in sweep.results[:4]:
    print(f"  d={r.d:2d} {r.epr.label:12s} total={r.total[0]:.3e}")
# fragment: opens windows
sweep.plot_comparison()          # every curve on shared axes
sweep.plot_vs_distance(p=1e-4)   # does more distance keep helping?
sweep.plot_threshold_vs_k()      # the fitted threshold, from the table
sweep.plot_threshold_grid()      # per-k panel grid

Validity

The additive form TLER ≈ Σ LER_gate + Σ LER_mem holds only while N · LER ≪ 1. validity() says where it stops:

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.simulator.dqc import DQCScheduler
from qndk.quantum_error_correction import (
    fault_tolerant_encode, tler, SurfaceCode, FixedIdleEpr)

circuit = QiskitCircuit("tfim", num_qubits=6, num_trotter_steps=1).circuit
circuit.t(1)
network = build_clos(ports_per_switch=4, qpus_per_rack=1,
                     qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"),
                     num_magic_factories=1)
code = SurfaceCode(d=9)
partition = fault_tolerant_encode(circuit, network, code=code,
                                  num_ancilla=1)
result = DQCScheduler(partition).run_simulation()

budget = tler(result, code=code, epr=FixedIdleEpr(k_idle=4, lam_seam=4),
              p_min=1e-4, p_max=3e-3, n_p_points=100)
print(budget.validity()["summary"])

Plots can shade the invalid region with show_validity=True.

The surface code itself

from qndk.quantum_error_correction import SurfaceCode

for d in (3, 5, 9):
    code = SurfaceCode(d=d)
    print(f"d={d}: {d * d} data qubits, "
          f"{d * (d - 1)} X-ancillas, {d * (d - 1)} Z-ancillas")

Data qubits sit on integer grid coordinates; X-ancillas are centred between vertical neighbours, Z-ancillas between horizontal ones.

Structure

Everything specific to one code family sits behind a single interface, so the error budget, the threshold predictor and the bridge from a SimulationResult do not depend on which family is in use.

The shipped threshold tables were produced by large-scale Stim sweeps, which is why they are measured rather than analytic. The tables ship with the wheel.

Grounded in the paper

This package implements Impact of Network Constraints on Fault-Tolerant Distributed Quantum Computing (arXiv:2606.17495). Where the paper is silent — it defers magic states entirely — the SDK uses a rule of its own and says so. TlerConfig.magic_budget_fraction is the worked example: no published model backs it.

Next

Results go to analysis, or straight into your own plots.