Tutorial 6: error correction with atom loss#

An atom can be lost during a run, and the loss can be detected. cosmiq’s qec package models it as a heralded erasure: the atom is replaced, a herald bit in the measurement record says where it happened, and the qubit gets I, X, Y or Z, each with probability 1/4. A decoder that reads the heralds knows where those errors can be. We’ll

  1. build a repetition-code memory experiment, with loss on every qubit in every round;

  2. sample it, and check the heralds against the loss rate;

  3. decode the same shots twice, blind to the heralds and using them, and compare the two decoders;

  4. map a device’s rates onto the noise: a modelling choice.

It needs the extra: pip install "cosmiq[qec]" (Stim and networkx). Run it with python docs/tutorials/06_qec_atom_loss.py; COSMIQ_TUTORIAL_QUICK=1 gives a quick version, which runs in a few seconds. docs/qec.md has the details.

import math
import os

import numpy as np

import cosmiq as cq
from cosmiq import qec

QUICK = os.environ.get("COSMIQ_TUTORIAL_QUICK") == "1"
SHOTS = 20_000 if QUICK else 100_000
CODE, DISTANCE = "repetition", 3
NOISE = qec.Noise(p=1e-3, p_loss=0.02)
SEED = 1

1. The code, and where atoms can be lost#

Stim’s repetition-code memory circuit at distance \(d = 3\), with \(d\) rounds of stabiliser measurements (the tested sizes are on the Claims and limits page). qec.Noise sets depolarising noise \(p\) after every Clifford gate (and, by default, the same \(p\) for readout, reset and idle errors), and a heralded erasure with probability \(p_\mathrm{loss}\) on every qubit in every round: on the data qubits as the round starts, on the ancillas just before they are measured.

code = qec.code(CODE, DISTANCE)
circuit = code.circuit(NOISE, rounds=code.distance)
erasures = code.erasure_locations()
rounds = sorted({erasure.round for erasure in erasures})
print(NOISE)
print(f"{CODE} code, d = {code.distance}: {circuit.num_qubits} qubits, {len(rounds)} rounds")
print(f"{circuit.num_detectors} detectors, {len(erasures)} erasure locations")
assert len(rounds) == code.distance
assert {erasure.qubit for erasure in erasures} == set(range(circuit.num_qubits))
assert NOISE.p_measure == NOISE.p_reset == NOISE.p_idle == NOISE.p
Noise(p=0.001, p_loss=0.02, p_measure=0.001, p_reset=0.001, p_idle=0.001, sources=())
repetition code, d = 3: 5 qubits, 3 rounds
8 detectors, 15 erasure locations

2. Sample, and count the heralds#

qec.memory_experiment samples the circuit and decodes it. We run it twice with one seed, once per decoder: the same seed gives the same shots on the same machine and Stim version, so both decoders see identical shots.

Each of the \(L\) erasure locations fires with probability \(p_\mathrm{loss}\), so a shot carries \(L\,p_\mathrm{loss}\) heralds on average. Over \(S\) shots, the mean’s standard error is

\[\sigma = \sqrt{L\,p_\mathrm{loss}\,(1 - p_\mathrm{loss}) / S}.\]

We check the count within \(4\sigma\) of \(L\,p_\mathrm{loss}\).

blind = qec.memory_experiment(
    CODE, d=DISTANCE, noise=NOISE, shots=SHOTS, decoder="loss_blind", seed=SEED
)
aware = qec.memory_experiment(
    CODE, d=DISTANCE, noise=NOISE, shots=SHOTS, decoder="loss_aware", seed=SEED
)
for name in ("detectors", "observables", "erased"):
    assert np.array_equal(getattr(blind.samples, name), getattr(aware.samples, name)), name

locations = len(erasures)
expected = locations * NOISE.p_loss
sigma = math.sqrt(locations * NOISE.p_loss * (1 - NOISE.p_loss) / SHOTS)
heralds = aware.heralds_per_shot
print(f"{SHOTS} shots: {heralds:.4f} heralds a shot; expected {expected:.4f}, sigma {sigma:.4f}")
print(f"the difference is {abs(heralds - expected) / sigma:.2f} sigma")
assert abs(heralds - expected) <= 4 * sigma
100000 shots: 0.2994 heralds a shot; expected 0.3000, sigma 0.0017
the difference is 0.37 sigma

3. Two decoders on the same shots#

Both are minimum-weight perfect matching on the error model’s graph. The loss-blind decoder weighs each edge by its probability, with the erasures averaged in, and ignores the heralds. The loss-aware decoder gives the edges of each erased location weight 0 in that shot.

A shot fails when the decoder’s predicted logical flip is wrong. On the same shots, only the shots where exactly one decoder fails tell the two apart: \(b\) where only the loss-blind one fails, \(c\) where only the loss-aware one does. McNemar’s exact one-sided test asks how likely \(b\) or more of those \(n = b + c\) shots would be if the decoders were equally good.

cosmiq’s own tests found the loss-aware decoder better in every case they graded, including this one (the Claims and limits page). Here we apply the same test to our own shots.

for result in (blind, aware):
    rate, error = result.logical_error_rate, result.sigma
    failed = int(result.failures.sum())
    print(f"{result.decoder}: {failed} failed shots, logical error rate {rate:.5f} ± {error:.5f}")
b = int(np.sum(blind.failures & ~aware.failures))
c = int(np.sum(aware.failures & ~blind.failures))
n = b + c
p_value = sum(math.comb(n, k) for k in range(b, n + 1)) / 2**n
print(f"only the loss-blind decoder failed: {b} shots; only the loss-aware one: {c}")
print(f"McNemar's one-sided p = {p_value:.2e}")
assert p_value < 0.01
loss_blind: 294 failed shots, logical error rate 0.00294 ± 0.00017
loss_aware: 47 failed shots, logical error rate 0.00047 ± 0.00007
only the loss-blind decoder failed: 261 shots; only the loss-aware one: 14
McNemar's one-sided p = 2.02e-60

4. Rates from a device: a modelling choice#

qec.noise_from_device maps a device’s digital profile and calibration onto these rates, and qec.DEVICE_MAPPING says how. It is a modelling choice, not the device’s QEC performance: for one, the analog loss rate per sequence becomes a loss rate per qubit and round. A device that lacks a value the mapping reads is refused by name: a missing value is never taken as 0.

device_noise = qec.noise_from_device("cosmiq-ref-1")
for name, source, _ in qec.DEVICE_MAPPING:
    print(f"{name:9s} = {getattr(device_noise, name):.4g}, from {source}")
profile = cq.digital.profile("cosmiq-ref-1")
assert device_noise.p == profile.depol_cz
assert device_noise.p_measure == (profile.spam_false_01 + profile.spam_false_10) / 2

try:
    qec.noise_from_device("cosmiq-ref-1-ideal")
except cq.CapabilityError as error:
    refusal = str(error)
else:
    raise RuntimeError("cosmiq-ref-1-ideal has no calibration, yet it was mapped")
print(refusal)
assert refusal.startswith("[QEC_CALIBRATION]")
p         = 0.005, from digital profile rates.depol_cz
p_idle    = 0.001, from digital profile rates.depol_1q_local
p_measure = 0.0075, from digital profile rates.spam_false_01 and rates.spam_false_10
p_reset   = 0.005, from device calibration spam.preparation_error
p_loss    = 0.005, from device calibration loss.sequence_probability
[QEC_CALIBRATION] device cosmiq-ref-1-ideal has no calibration value spam.preparation_error, which qec.noise_from_device maps (qec.DEVICE_MAPPING); a missing value is never taken as 0; fix: build qec.Noise(...) yourself