{ "cells": [ { "cell_type": "markdown", "id": "2782e146", "metadata": {}, "source": [ "Generated from cosmiq's `docs/tutorials/06_qec_atom_loss.py` for Colab: the first cell installs cosmiq." ] }, { "cell_type": "code", "execution_count": null, "id": "ff23061f", "metadata": {}, "outputs": [], "source": [ "%pip install --quiet \"cosmiq[qec]\"" ] }, { "cell_type": "markdown", "id": "2fdd69c8", "metadata": {}, "source": [ "# Tutorial 6: error correction with atom loss\n", "\n", "An atom can be lost during a run, and the loss can be detected. cosmiq's `qec` package models\n", "it as a **heralded erasure**: the atom is replaced, a herald bit in the measurement record says\n", "where it happened, and the qubit gets I, X, Y or Z, each with probability 1/4. A decoder that\n", "reads the heralds knows where those errors can be. We'll\n", "\n", "1. build a repetition-code memory experiment, with loss on every qubit in every round;\n", "2. sample it, and check the heralds against the loss rate;\n", "3. decode the same shots twice, blind to the heralds and using them, and compare the two\n", " decoders;\n", "4. map a device's rates onto the noise: a modelling choice.\n", "\n", "It needs the extra: `pip install \"cosmiq[qec]\"` (Stim and networkx). Run it with\n", "`python docs/tutorials/06_qec_atom_loss.py`; `COSMIQ_TUTORIAL_QUICK=1` gives a quick version,\n", "which runs in a few seconds. docs/qec.md has the details." ] }, { "cell_type": "code", "execution_count": null, "id": "abaa0541", "metadata": {}, "outputs": [], "source": [ "import math\n", "import os\n", "\n", "import numpy as np\n", "\n", "import cosmiq as cq\n", "from cosmiq import qec\n", "\n", "QUICK = os.environ.get(\"COSMIQ_TUTORIAL_QUICK\") == \"1\"\n", "SHOTS = 20_000 if QUICK else 100_000\n", "CODE, DISTANCE = \"repetition\", 3\n", "NOISE = qec.Noise(p=1e-3, p_loss=0.02)\n", "SEED = 1" ] }, { "cell_type": "markdown", "id": "e1a0e6e7", "metadata": {}, "source": [ "## 1. The code, and where atoms can be lost\n", "\n", "Stim's repetition-code memory circuit at distance $d = 3$, with $d$ rounds of stabiliser\n", "measurements (the tested sizes are on the Claims and limits page). `qec.Noise` sets\n", "depolarising noise $p$ after every Clifford gate (and, by default, the same $p$ for readout,\n", "reset and idle errors), and a heralded erasure with probability $p_\\mathrm{loss}$ on every qubit\n", "in every round: on the data qubits as the round starts, on the ancillas just before they are\n", "measured." ] }, { "cell_type": "code", "execution_count": null, "id": "d35dfe1f", "metadata": {}, "outputs": [], "source": [ "code = qec.code(CODE, DISTANCE)\n", "circuit = code.circuit(NOISE, rounds=code.distance)\n", "erasures = code.erasure_locations()\n", "rounds = sorted({erasure.round for erasure in erasures})\n", "print(NOISE)\n", "print(f\"{CODE} code, d = {code.distance}: {circuit.num_qubits} qubits, {len(rounds)} rounds\")\n", "print(f\"{circuit.num_detectors} detectors, {len(erasures)} erasure locations\")\n", "assert len(rounds) == code.distance\n", "assert {erasure.qubit for erasure in erasures} == set(range(circuit.num_qubits))\n", "assert NOISE.p_measure == NOISE.p_reset == NOISE.p_idle == NOISE.p" ] }, { "cell_type": "markdown", "id": "4509e1b6", "metadata": {}, "source": [ "## 2. Sample, and count the heralds\n", "\n", "`qec.memory_experiment` samples the circuit and decodes it. We run it twice with one seed, once\n", "per decoder: the same seed gives the same shots on the same machine and Stim version, so both\n", "decoders see identical shots.\n", "\n", "Each of the $L$ erasure locations fires with probability $p_\\mathrm{loss}$, so a shot carries\n", "$L\\,p_\\mathrm{loss}$ heralds on average. Over $S$ shots, the mean's standard error is\n", "\n", "$$\n", "\\sigma = \\sqrt{L\\,p_\\mathrm{loss}\\,(1 - p_\\mathrm{loss}) / S}.\n", "$$\n", "\n", "We check the count within $4\\sigma$ of $L\\,p_\\mathrm{loss}$." ] }, { "cell_type": "code", "execution_count": null, "id": "7a8bc9f5", "metadata": {}, "outputs": [], "source": [ "blind = qec.memory_experiment(\n", " CODE, d=DISTANCE, noise=NOISE, shots=SHOTS, decoder=\"loss_blind\", seed=SEED\n", ")\n", "aware = qec.memory_experiment(\n", " CODE, d=DISTANCE, noise=NOISE, shots=SHOTS, decoder=\"loss_aware\", seed=SEED\n", ")\n", "for name in (\"detectors\", \"observables\", \"erased\"):\n", " assert np.array_equal(getattr(blind.samples, name), getattr(aware.samples, name)), name\n", "\n", "locations = len(erasures)\n", "expected = locations * NOISE.p_loss\n", "sigma = math.sqrt(locations * NOISE.p_loss * (1 - NOISE.p_loss) / SHOTS)\n", "heralds = aware.heralds_per_shot\n", "print(f\"{SHOTS} shots: {heralds:.4f} heralds a shot; expected {expected:.4f}, sigma {sigma:.4f}\")\n", "print(f\"the difference is {abs(heralds - expected) / sigma:.2f} sigma\")\n", "assert abs(heralds - expected) <= 4 * sigma" ] }, { "cell_type": "markdown", "id": "0fc3aad7", "metadata": {}, "source": [ "## 3. Two decoders on the same shots\n", "\n", "Both are minimum-weight perfect matching on the error model's graph. The loss-blind decoder\n", "weighs each edge by its probability, with the erasures averaged in, and ignores the heralds.\n", "The loss-aware decoder gives the edges of each erased location weight 0 in that shot.\n", "\n", "A shot fails when the decoder's predicted logical flip is wrong. On the same shots, only the\n", "shots where exactly one decoder fails tell the two apart: $b$ where only the loss-blind one\n", "fails, $c$ where only the loss-aware one does. McNemar's exact one-sided test asks how likely $b$\n", "or more of those $n = b + c$ shots would be if the decoders were equally good.\n", "\n", "cosmiq's own tests found the loss-aware decoder better in every case they graded, including\n", "this one (the Claims and limits page). Here we apply the same test to our own shots." ] }, { "cell_type": "code", "execution_count": null, "id": "db88e67f", "metadata": {}, "outputs": [], "source": [ "for result in (blind, aware):\n", " rate, error = result.logical_error_rate, result.sigma\n", " failed = int(result.failures.sum())\n", " print(f\"{result.decoder}: {failed} failed shots, logical error rate {rate:.5f} ± {error:.5f}\")\n", "b = int(np.sum(blind.failures & ~aware.failures))\n", "c = int(np.sum(aware.failures & ~blind.failures))\n", "n = b + c\n", "p_value = sum(math.comb(n, k) for k in range(b, n + 1)) / 2**n\n", "print(f\"only the loss-blind decoder failed: {b} shots; only the loss-aware one: {c}\")\n", "print(f\"McNemar's one-sided p = {p_value:.2e}\")\n", "assert p_value < 0.01" ] }, { "cell_type": "markdown", "id": "0d75b689", "metadata": {}, "source": [ "## 4. Rates from a device: a modelling choice\n", "\n", "`qec.noise_from_device` maps a device's digital profile and calibration onto these rates, and\n", "`qec.DEVICE_MAPPING` says how. It is a modelling choice, not the device's QEC performance: for\n", "one, the analog loss rate per sequence becomes a loss rate per qubit and round. A device that\n", "lacks a value the mapping reads is refused by name: a missing value is never taken as 0." ] }, { "cell_type": "code", "execution_count": null, "id": "4780a564", "metadata": {}, "outputs": [], "source": [ "device_noise = qec.noise_from_device(\"cosmiq-ref-1\")\n", "for name, source, _ in qec.DEVICE_MAPPING:\n", " print(f\"{name:9s} = {getattr(device_noise, name):.4g}, from {source}\")\n", "profile = cq.digital.profile(\"cosmiq-ref-1\")\n", "assert device_noise.p == profile.depol_cz\n", "assert device_noise.p_measure == (profile.spam_false_01 + profile.spam_false_10) / 2\n", "\n", "try:\n", " qec.noise_from_device(\"cosmiq-ref-1-ideal\")\n", "except cq.CapabilityError as error:\n", " refusal = str(error)\n", "else:\n", " raise RuntimeError(\"cosmiq-ref-1-ideal has no calibration, yet it was mapped\")\n", "print(refusal)\n", "assert refusal.startswith(\"[QEC_CALIBRATION]\")" ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "main_language": "python", "notebook_metadata_filter": "-all", "text_representation": { "extension": ".py", "format_name": "percent" } }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }