diff --git a/Cargo.lock b/Cargo.lock index 80c5f4d06..de899fe54 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2353,6 +2353,19 @@ dependencies = [ "smallvec", ] +[[package]] +name = "ppvm-tableau-2" +version = "0.0.0" +dependencies = [ + "num-complex", + "ppvm-pauli-kernels", + "ppvm-pauli-word-2", + "ppvm-phased-pauli-word-2", + "ppvm-traits-2", + "rand 0.10.3", + "stim-parser", +] + [[package]] name = "ppvm-tableau-sum" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index ff106b1a7..dc401b399 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,7 +30,7 @@ members = [ # Built by `cargo build --workspace --all-targets` in CI so the skill # can't silently drift away from the public API. "crates/ppvm-tui", - "skills/ppvm-usage/examples/rust", "crates/ppvm-lossy-pauli-word-2", "crates/ppvm-phased-pauli-word-2", "crates/ppvm-pauli-kernels", + "skills/ppvm-usage/examples/rust", "crates/ppvm-lossy-pauli-word-2", "crates/ppvm-phased-pauli-word-2", "crates/ppvm-pauli-kernels", "crates/ppvm-tableau-2", ] # Single version for every crate and the `bloqade-ppvm` Python package diff --git a/crates/ppvm-tableau-2/Cargo.toml b/crates/ppvm-tableau-2/Cargo.toml new file mode 100644 index 000000000..5af4001dc --- /dev/null +++ b/crates/ppvm-tableau-2/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "ppvm-tableau-2" +edition.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[dependencies] +num-complex = "0.4.6" +ppvm-pauli-kernels = { path = "../ppvm-pauli-kernels" } +ppvm-traits-2 = { path = "../ppvm-traits-2" } +rand = "0.10.1" + +[dev-dependencies] +ppvm-pauli-word-2 = { path = "../ppvm-pauli-word-2" } +ppvm-phased-pauli-word-2 = { path = "../ppvm-phased-pauli-word-2" } +stim-parser = { path = "../stim-parser" } diff --git a/crates/ppvm-tableau-2/benches/circuits/.gitignore b/crates/ppvm-tableau-2/benches/circuits/.gitignore new file mode 100644 index 000000000..11f7e0b31 --- /dev/null +++ b/crates/ppvm-tableau-2/benches/circuits/.gitignore @@ -0,0 +1 @@ +*.stim diff --git a/crates/ppvm-tableau-2/benches/circuits/gen.py b/crates/ppvm-tableau-2/benches/circuits/gen.py new file mode 100644 index 000000000..55a8e75a7 --- /dev/null +++ b/crates/ppvm-tableau-2/benches/circuits/gen.py @@ -0,0 +1,52 @@ +"""Microbenchmark circuits for the inverse tableau, at the d=7 surface code's +size (118 qubits). Run with the `run_stim` example; per-operation cost is +(time per shot - base) / count. + +- base: H on all qubits (per-shot overhead). +- cx: base plus 4096 random CX, in instructions of 16 disjoint pairs. +- gates: base plus 4096 gates drawn uniformly from all 13 Clifford gates, so + no single gate dominates. +- mr_batched: 10 rounds of H on all, 128 random CX, one MR over all qubits + (random collapses with fan-outs). +- mr_split: the same with one MR per instruction. Stim's parser merges + consecutive same-gate instructions back into one, so for Stim this equals + mr_batched. +- mr_unfused: mr_split with a TICK after each MR, which Stim cannot merge: + really one target per instruction. + +Generate with `python3 gen.py` in this directory (seeded, deterministic); the +output is not tracked. +""" +import random +n = 118 +rng = random.Random(1) +h_all = "H " + " ".join(map(str, range(n))) +def cx_layer(pairs): + lines = [] + for _ in range(pairs // 16): + qs = rng.sample(range(n), 32) + lines.append("CX " + " ".join(map(str, qs))) + return lines +def write(name, lines): + open(f"{name}.stim", "w").write("\n".join(lines) + "\n") +write("base", [h_all]) +write("cx", [h_all] + cx_layer(4096)) +one_qubit = ["X", "Y", "Z", "H", "S", "S_DAG", "SQRT_X", "SQRT_X_DAG", "SQRT_Y", "SQRT_Y_DAG"] +two_qubit = ["CX", "CZ", "CY"] +gates_rng = random.Random(2) # own seed, so the other circuits stay unchanged +mixed = [] +for _ in range(4096): + g = gates_rng.choice(one_qubit + two_qubit) + if g in two_qubit: + a, b = gates_rng.sample(range(n), 2) + mixed.append(f"{g} {a} {b}") + else: + mixed.append(f"{g} {gates_rng.randrange(n)}") +write("gates", [h_all] + mixed) +rounds = [] +for _ in range(10): + rounds += [h_all] + cx_layer(128) + rounds.append("MR " + " ".join(map(str, range(n)))) +write("mr_batched", rounds) +write("mr_split", [l if not l.startswith("MR") else "\n".join(f"MR {q}" for q in range(n)) for l in rounds]) +write("mr_unfused", [l if not l.startswith("MR") else "\n".join(f"MR {q}\nTICK" for q in range(n)) for l in rounds]) diff --git a/crates/ppvm-tableau-2/benches/stim-compare/circuits.py b/crates/ppvm-tableau-2/benches/stim-compare/circuits.py new file mode 100644 index 000000000..868164704 --- /dev/null +++ b/crates/ppvm-tableau-2/benches/stim-compare/circuits.py @@ -0,0 +1,56 @@ +"""Stim-generated Clifford memory circuits, as both simulators run them: noise +removed, and the two instructions ppvm's harness lacks rewritten. + +- `C_XYZ` is `H` then `SQRT_X_DAG` (checked with `stim.Tableau`). +- `MX` and `MY` (only the color code's final data measurements) are `H`, `M` + and `S_DAG`, `H`, `M`: they map X or Y to Z first; the state afterwards is + not used. +""" + +import re + +import stim + +# (family, Stim generator task, distances); rounds = distance. +FAMILIES = [ + ("surface", "surface_code:rotated_memory_z", [3, 5, 7, 9, 11, 15, 19, 23, 27, 31]), + ("repetition", "repetition_code:memory", [3, 9, 25, 75, 225, 675]), + ("color", "color_code:memory_xyz", [3, 5, 7, 9, 13, 17, 21, 25, 31, 37, 43]), +] + + +def generate(task: str, distance: int) -> str: + """The circuit text for `task` at `distance`, noise-free and rewritten.""" + noise = 0.001 # only so the generator emits the full structure; removed below + circuit = stim.Circuit.generated( + task, + distance=distance, + rounds=distance, + after_clifford_depolarization=noise, + before_round_data_depolarization=noise, + before_measure_flip_probability=noise, + after_reset_flip_probability=noise, + ).without_noise() + return rewrite(str(circuit)) + + +def rewrite(text: str) -> str: + def c_xyz(m: re.Match) -> str: + targets = m.group(1) + return f"H {targets}\nSQRT_X_DAG {targets}" + + def mx(m: re.Match) -> str: + targets = m.group(1) + return f"H {targets}\nM {targets}" + + def my(m: re.Match) -> str: + targets = m.group(1) + return f"S_DAG {targets}\nH {targets}\nM {targets}" + + text = re.sub(r"^\s*C_XYZ ([\d ]+)$", c_xyz, text, flags=re.MULTILINE) + text = re.sub(r"^\s*MX ([\d ]+)$", mx, text, flags=re.MULTILINE) + return re.sub(r"^\s*MY ([\d ]+)$", my, text, flags=re.MULTILINE) + + +def num_qubits(text: str) -> int: + return stim.Circuit(text).num_qubits diff --git a/crates/ppvm-tableau-2/benches/stim-compare/clifft.py b/crates/ppvm-tableau-2/benches/stim-compare/clifft.py new file mode 100644 index 000000000..f50e634cd --- /dev/null +++ b/crates/ppvm-tableau-2/benches/stim-compare/clifft.py @@ -0,0 +1,84 @@ +"""clifft-bench workloads, noise included, on ppvm-tableau-2's `run_clifft` and +on reference binaries with the same CLI. Follows clifft-bench's probe contract +loosely: per tool and workload, a calibration run (also the warmup) picks the +shots for about `--seconds`, then `--probes` timed runs alternate over the +tools; the median is reported. A probe is at least one shot, so on slow +workloads it runs longer than `--seconds`. Writes `clifft.csv` to +`target/stim-compare/`. + + python clifft.py --reference NAME=PATH... [--workloads DIR] [--case NAME]... + [--skip NAME]... [--seconds 1] [--probes 3] + +Workloads are clifft-bench's `.stim` files (`scripts/fetch_clifft_bench.sh` +fetches them into `target/clifft-bench/`). Every tool reads the original file: +the ppvm runners rewrite Clifft's rotation and `U3` lines themselves. + +Stim merges consecutive instructions with the same gate and arguments, and +shares setup across an instruction's targets; ppvm's `stim-parser` does not, so +ppvm runs one instruction per line. See the design doc's Benchmarks section. +""" + +import argparse +import csv +import pathlib +import statistics + +import common + + +def calibrated_shots(cmd: list[str], circuit: pathlib.Path, seconds: float) -> int: + """Shots for about `seconds`: one shot, then a ~10% run if that is fast.""" + estimate = common.time_per_shot(cmd, circuit, 1) + if estimate * 1e-6 < seconds / 20: + shots = max(1, int(seconds / 10 * 1e6 / estimate)) + estimate = common.time_per_shot(cmd, circuit, shots) + return max(1, int(seconds * 1e6 / estimate)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference", action="append", default=[]) + parser.add_argument( + "--workloads", type=pathlib.Path, default=common.REPO / "target" / "clifft-bench" + ) + parser.add_argument("--case", action="append", help="workload name, e.g. coherent_d3_r1") + parser.add_argument("--skip", action="append", default=[], help="workload name to leave out") + parser.add_argument("--seconds", type=float, default=1.0, help="target time per probe") + parser.add_argument("--probes", type=int, default=3) + args = parser.parse_args() + + common.build_ppvm("run_clifft") + tools = common.tools(args.reference, "run_clifft") + references = list(tools)[1:] + paths = sorted(args.workloads.glob("*.stim")) + if args.case: + paths = [p for p in paths if p.stem in args.case] + paths = [p for p in paths if p.stem not in args.skip] + if not paths: + raise SystemExit(f"no workloads in {args.workloads}") + rows = [] + for path in paths: + shots = {name: calibrated_shots(cmd, path, args.seconds) for name, cmd in tools.items()} + times = {name: [] for name in tools} + for _ in range(args.probes): + for name, cmd in tools.items(): + times[name].append(common.time_per_shot(cmd, path, shots[name])) + row = {"workload": path.stem} + row |= {f"{name}_us": round(statistics.median(ts), 3) for name, ts in times.items()} + row |= {f"{name}_shots": shots[name] for name in tools} + for ref in references: + row[f"ppvm_over_{ref}"] = round(row["ppvm_us"] / row[f"{ref}_us"], 3) + rows.append(row) + cells = " ".join(f"{name} {row[f'{name}_us']:12.1f} µs" for name in tools) + ratios = " ".join(f"ppvm/{ref} {row[f'ppvm_over_{ref}']:.2f}" for ref in references) + print(f"{path.stem:32} {cells} {ratios}", flush=True) + common.OUT.mkdir(parents=True, exist_ok=True) + with open(common.OUT / "clifft.csv", "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + print(f"wrote {common.OUT / 'clifft.csv'}") + + +if __name__ == "__main__": + main() diff --git a/crates/ppvm-tableau-2/benches/stim-compare/common.py b/crates/ppvm-tableau-2/benches/stim-compare/common.py new file mode 100644 index 000000000..98a7f0782 --- /dev/null +++ b/crates/ppvm-tableau-2/benches/stim-compare/common.py @@ -0,0 +1,58 @@ +"""Running the timing tools: a ppvm example (`run_stim`, `run_clifft`) and +reference binaries with the same CLI (` `, printing +` µs/shot` or ` us/shot`), such as a native Stim build.""" + +import pathlib +import re +import subprocess +import sys + +HERE = pathlib.Path(__file__).resolve().parent +REPO = HERE.parents[3] +OUT = REPO / "target" / "stim-compare" +EXAMPLES = REPO / "target" / "release" / "examples" + + +def build_ppvm(example: str = "run_stim") -> None: + subprocess.run( + [ + "cargo", + "build", + "--release", + "-q", + "-p", + "ppvm-tableau-2", + "--example", + example, + ], + cwd=REPO, + check=True, + ) + + +def tools(references: list[str], example: str = "run_stim") -> dict[str, list[str]]: + """`ppvm` (the example), then the `NAME=PATH` references in order.""" + if not references: + sys.exit("give at least one --reference NAME=PATH") + found = {"ppvm": [str(EXAMPLES / example)]} + for reference in references: + name, path = reference.split("=", 1) + found[name] = [path] + return found + + +def time_per_shot(cmd: list[str], circuit: pathlib.Path, shots: int) -> float: + """µs per shot.""" + out = subprocess.run( + [*cmd, str(circuit), str(shots)], capture_output=True, text=True, check=True + ).stdout + match = re.search(r"([\d.]+) (?:µs|us)/shot", out) + if not match: + raise RuntimeError(f"no timing in output of {cmd}: {out!r}") + return float(match.group(1)) + + +def calibrated_shots(cmd: list[str], circuit: pathlib.Path, seconds: float) -> int: + """Shots for about `seconds` of runtime.""" + estimate = time_per_shot(cmd, circuit, 3) + return max(3, min(50_000, int(seconds * 1e6 / max(estimate, 1e-3)))) diff --git a/crates/ppvm-tableau-2/benches/stim-compare/gates.py b/crates/ppvm-tableau-2/benches/stim-compare/gates.py new file mode 100644 index 000000000..c995e1bc2 --- /dev/null +++ b/crates/ppvm-tableau-2/benches/stim-compare/gates.py @@ -0,0 +1,62 @@ +"""Per-gate cost over size: a brickwork `CX` layer and a full `H` layer, on +ppvm-tableau-2's `run_stim` and on reference binaries. Each circuit is timed at +two repeat counts; the difference removes per-shot overhead (simulator +construction). + + python gates.py --reference stim=PATH [--size 64]... [--rounds 3] +""" + +import argparse +import statistics + +import common + +SIZES = [32, 64, 128, 274, 512, 1024, 2048] +REPEATS = (50, 150) + + +def layer(gate: str, n: int) -> tuple[str, int]: + """(one layer, gates in it).""" + if gate == "CX": + pairs = [(q, q + 1) for q in range(0, n - 1, 2)] + [ + (q, q + 1) for q in range(1, n - 1, 2) + ] + even, odd = pairs[: (n // 2)], pairs[(n // 2) :] + lines = [ + f"CX {' '.join(f'{a} {b}' for a, b in even)}", + f"CX {' '.join(f'{a} {b}' for a, b in odd)}", + ] + return "\n".join(lines), len(pairs) + return f"H {' '.join(map(str, range(n)))}", n + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference", action="append", default=[]) + parser.add_argument("--size", action="append", type=int) + parser.add_argument("--rounds", type=int, default=3) + args = parser.parse_args() + common.build_ppvm() + tools = common.tools(args.reference) + (common.OUT / "gates").mkdir(parents=True, exist_ok=True) + for gate in ("CX", "H"): + for n in args.size or SIZES: + body, count = layer(gate, n) + paths = [] + for reps in REPEATS: + path = common.OUT / "gates" / f"{gate}_{n}_{reps}.stim" + path.write_text(f"REPEAT {reps} {{\n{body}\n}}\n") + paths.append(path) + cells = [] + for name, cmd in tools.items(): + shots = common.calibrated_shots(cmd, paths[1], 0.2) + deltas = [] + for _ in range(args.rounds): + lo, hi = (common.time_per_shot(cmd, p, shots) for p in paths) + deltas.append((hi - lo) * 1e3 / ((REPEATS[1] - REPEATS[0]) * count)) + cells.append(f"{name} {statistics.median(deltas):6.2f}") + print(f"{gate:2} n={n:<5} ns/gate: " + " ".join(cells), flush=True) + + +if __name__ == "__main__": + main() diff --git a/crates/ppvm-tableau-2/benches/stim-compare/sweep.py b/crates/ppvm-tableau-2/benches/stim-compare/sweep.py new file mode 100644 index 000000000..024e1e017 --- /dev/null +++ b/crates/ppvm-tableau-2/benches/stim-compare/sweep.py @@ -0,0 +1,86 @@ +"""Size sweep: Stim-generated Clifford memory circuits (see `circuits.py`) on +ppvm-tableau-2's `run_stim` and on reference binaries, alternating tools over a +few rounds; median per tool. Writes the circuits and `sweep.csv` to +`target/stim-compare/`. + + uv run --no-project --with stim python sweep.py --reference stim=PATH + [--case surface:7]... [--family surface] [--max-qubits N] [--rounds 3] + +Python Stim only generates the circuits; timing is against the references +(e.g. a native Stim build). Times are per shot, noise-free, +gates/measurements/resets only; see the design doc's Benchmarks section for how +instruction batching differs between the tools. +""" + +import argparse +import csv +import statistics + +import circuits +import common + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--rounds", type=int, default=3) + parser.add_argument("--max-qubits", type=int, default=10**9) + parser.add_argument("--family", action="append") + parser.add_argument( + "--case", action="append", help="family:distance, e.g. surface:7" + ) + parser.add_argument("--reference", action="append", default=[]) + parser.add_argument( + "--seconds", type=float, default=0.3, help="target runtime per measurement" + ) + args = parser.parse_args() + + common.build_ppvm() + tools = common.tools(args.reference) + reference = list(tools)[1] + cases = {(f, int(d)) for f, d in (c.split(":") for c in args.case or [])} + (common.OUT / "circuits").mkdir(parents=True, exist_ok=True) + rows = [] + for family, task, distances in circuits.FAMILIES: + if args.family and family not in args.family: + continue + for d in distances: + if cases and (family, d) not in cases: + continue + text = circuits.generate(task, d) + n = circuits.num_qubits(text) + if n > args.max_qubits: + continue + path = common.OUT / "circuits" / f"{family}_d{d}.stim" + path.write_text(text) + shots = { + name: common.calibrated_shots(cmd, path, args.seconds) + for name, cmd in tools.items() + } + times = {name: [] for name in tools} + for _ in range(args.rounds): + for name, cmd in tools.items(): + times[name].append(common.time_per_shot(cmd, path, shots[name])) + row = {"family": family, "distance": d, "qubits": n} + row |= { + f"{name}_us": round(statistics.median(ts), 3) + for name, ts in times.items() + } + row[f"ppvm_over_{reference}"] = round( + row["ppvm_us"] / row[f"{reference}_us"], 3 + ) + rows.append(row) + cells = " ".join(f"{name} {row[f'{name}_us']:10.1f} µs" for name in tools) + ratio = row[f"ppvm_over_{reference}"] + print( + f"{family:10} d={d:<4} {n:5} q {cells} ppvm/{reference} {ratio:.2f}", + flush=True, + ) + with open(common.OUT / "sweep.csv", "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + print(f"wrote {common.OUT / 'sweep.csv'}") + + +if __name__ == "__main__": + main() diff --git a/crates/ppvm-tableau-2/examples/run_clifft.rs b/crates/ppvm-tableau-2/examples/run_clifft.rs new file mode 100644 index 000000000..12e7cd97d --- /dev/null +++ b/crates/ppvm-tableau-2/examples/run_clifft.rs @@ -0,0 +1,545 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Benchmark harness for the clifft-bench workloads: runs a Stim circuit, +//! noise included, on `GeneralizedTableau` one shot at a time with a fresh +//! simulator per shot. +//! +//! ```text +//! cargo run --release -p ppvm-tableau-2 --example run_clifft -- [shots] [--records ] [--loss

] +//! ``` +//! +//! `--loss p` applies a loss channel with probability `p` to each target after +//! every gate. A lost qubit's measurement is recorded as `0`; a reset, also the +//! one in `MR`, brings it back. +//! +//! Clifft's plain `R_X(α)`, `R_Y(α)`, `R_Z(α)` and `U3(θ, φ, λ)` / `U(…)` +//! lines (angles in half-turns) are rewritten into `stim-parser`'s `I[…]` tags before parsing. +//! `stim-parser` drops `rec[-k]` targets, so detectors are not evaluated here; +//! `--records` writes each shot's measurement record as a line of `0`/`1` to +//! check detector statistics outside the timed loop. Workloads are fetched by +//! `scripts/fetch_clifft_bench.sh`. + +use std::fmt::Write as _; +use std::time::Instant; + +use rand::rngs::SmallRng; +use rand::{RngExt, SeedableRng}; + +use ppvm_tableau_2::{ActiveDormant, DenseState, GeneralizedTableau}; +use ppvm_traits_2::{ + Clifford, Depolarizing2, LossChannel, Measure, PauliError, Reset, RotationOne, TGate, U3Gate, +}; +use stim_parser::ast::{Axis, ExtendedInstruction, PauliAxis, PauliFactor, Target}; +use stim_parser::instructions::{AnnotationKind, GateName, MeasureName, NoiseName}; + +type Sim = GeneralizedTableau>; + +#[derive(Clone, Copy)] +enum Basis { + X, + Y, + Z, +} + +/// One operation on one qubit or pair; `REPEAT` blocks are unrolled. +#[derive(Clone, Copy)] +enum Op { + One(GateName, usize), + Two(GateName, usize, usize), + T(usize), + TDag(usize), + Rotation(Axis, f64, usize), + U3([f64; 3], usize), + /// `X`, `Y`, `Z` with these probabilities on `noise[at..at + len]`, as one + /// `pauli_error_many`. + Pauli { + p: [f64; 3], + at: usize, + len: usize, + }, + /// `DEPOLARIZE2(p)` on `pairs[at..at + len]`, as one `depolarize2_many`. + Depolarize2 { + p: f64, + at: usize, + len: usize, + }, + /// `M`/`MR` on `measured[at..at + len]`, as one `measure_many`; flips and + /// resets as for `Measure`. + MeasureZ { + at: usize, + len: usize, + flip: f64, + reset: bool, + }, + /// Recorded outcome flipped with probability `flip`; `reset` returns the + /// qubit to the basis' `+1` state afterwards. + Measure { + basis: Basis, + q: usize, + flip: f64, + reset: bool, + }, + Reset(Basis, usize), + /// Classically controlled Pauli: apply it to `q` if `rec[-back]` is 1. + Feedback { + pauli: Basis, + back: usize, + q: usize, + }, + /// Pauli product `factors[at..at + len]`. + Mpp { + at: usize, + len: usize, + flip: f64, + }, +} + +/// Rewrite Clifft's plain rotation and `U3` lines into `I[…]` tags. Both write +/// angles in half-turns (`R_Z(α)` rotates by `α·π`), so the numbers carry over. +fn rewrite_dialect(src: &str) -> String { + let mut out = String::new(); + for line in src.lines() { + let body = line.trim_start(); + let indent = &line[..line.len() - body.len()]; + let rewritten = ["R_X", "R_Y", "R_Z", "U3", "U"] + .into_iter() + .find_map(|name| { + let rest = body.strip_prefix(name)?.strip_prefix('(')?; + let (args, targets) = rest.split_once(')')?; + let turns: Vec = args + .split(',') + .map(|a| a.trim().parse::().expect("angle")) + .collect(); + let params = match (name, turns.as_slice()) { + ("U3" | "U", [t, p, l]) => { + format!("U3(theta={t}*pi, phi={p}*pi, lambda={l}*pi)") + } + (_, [t]) => format!("{name}(theta={t}*pi)"), + _ => panic!("bad arguments in {line:?}"), + }; + Some(format!("{indent}I[{params}]{targets}")) + }); + writeln!(out, "{}", rewritten.as_deref().unwrap_or(line)).unwrap(); + } + out +} + +fn flip_arg(args: &[f64]) -> f64 { + args.first().copied().unwrap_or(0.0) +} + +/// Target lists that ops index into with `at..at + len`. +#[derive(Default)] +struct Pools { + /// MPP factors. + factors: Vec, + /// Z-basis measurement targets. + measured: Vec, + /// One-qubit noise targets. + noise: Vec, + /// Two-qubit noise pairs. + pairs: Vec<(usize, usize)>, +} + +/// Flatten the program into ops, unrolling `REPEAT` blocks. +fn lower(instructions: &[ExtendedInstruction], ops: &mut Vec, pools: &mut Pools) { + for instruction in instructions { + match instruction { + ExtendedInstruction::Gate(g) if g.targets.iter().any(|t| t.as_qubit().is_none()) => ops + .extend( + g.targets + .chunks(2) + .map(|pair| feedback(g.name, pair[0], pair[1])), + ), + ExtendedInstruction::Gate(g) => { + let qs: Vec = g + .targets + .iter() + .map(|t| t.as_qubit().expect("only qubit targets are supported")) + .collect(); + match g.name { + GateName::Reset | GateName::ResetZ => { + ops.extend(qs.iter().map(|&q| Op::Reset(Basis::Z, q))) + } + GateName::ResetX => ops.extend(qs.iter().map(|&q| Op::Reset(Basis::X, q))), + GateName::ResetY => ops.extend(qs.iter().map(|&q| Op::Reset(Basis::Y, q))), + GateName::CX + | GateName::ZCX + | GateName::CNot + | GateName::CY + | GateName::ZCY + | GateName::CZ + | GateName::ZCZ => { + ops.extend(qs.chunks(2).map(|p| Op::Two(g.name, p[0], p[1]))) + } + GateName::Identity => {} + name => ops.extend(qs.iter().map(|&q| Op::One(name, q))), + } + } + ExtendedInstruction::T { targets, .. } => ops.extend(targets.iter().map(|&q| Op::T(q))), + ExtendedInstruction::TDag { targets, .. } => { + ops.extend(targets.iter().map(|&q| Op::TDag(q))) + } + ExtendedInstruction::Rotation { + axis, + theta, + targets, + .. + } => ops.extend(targets.iter().map(|&q| Op::Rotation(*axis, *theta, q))), + ExtendedInstruction::U3 { + theta, + phi, + lambda, + targets, + .. + } => ops.extend(targets.iter().map(|&q| Op::U3([*theta, *phi, *lambda], q))), + ExtendedInstruction::Noise(n) => { + let p = flip_arg(&n.args); + let one = match n.name { + NoiseName::XError => [p, 0.0, 0.0], + NoiseName::YError => [0.0, p, 0.0], + NoiseName::ZError => [0.0, 0.0, p], + NoiseName::Depolarize1 => [p / 3.0; 3], + NoiseName::PauliChannel1 => [n.args[0], n.args[1], n.args[2]], + NoiseName::Depolarize2 => { + let (at, len) = (pools.pairs.len(), n.targets.len() / 2); + ops.push(Op::Depolarize2 { p, at, len }); + let pairs = n.targets.chunks(2).map(|pair| (pair[0], pair[1])); + pools.pairs.extend(pairs); + continue; + } + other => panic!("unsupported noise {other:?}"), + }; + let (at, len) = (pools.noise.len(), n.targets.len()); + ops.push(Op::Pauli { p: one, at, len }); + pools.noise.extend_from_slice(&n.targets); + } + ExtendedInstruction::Measure(m) => { + let (basis, reset) = match m.name { + MeasureName::M | MeasureName::MZ => (Basis::Z, false), + MeasureName::MX => (Basis::X, false), + MeasureName::MY => (Basis::Y, false), + MeasureName::MR => (Basis::Z, true), + MeasureName::MRX => (Basis::X, true), + MeasureName::MRY => (Basis::Y, true), + other => panic!("unsupported measurement {other:?}"), + }; + let flip = flip_arg(&m.args); + if let Basis::Z = basis { + ops.push(Op::MeasureZ { + at: pools.measured.len(), + len: m.targets.len(), + flip, + reset, + }); + pools.measured.extend_from_slice(&m.targets); + continue; + } + ops.extend(m.targets.iter().map(|&q| Op::Measure { + basis, + q, + flip, + reset, + })); + } + ExtendedInstruction::Mpp(mpp) => { + let flip = flip_arg(&mpp.args); + for product in &mpp.products { + ops.push(Op::Mpp { + at: pools.factors.len(), + len: product.len(), + flip, + }); + pools.factors.extend_from_slice(product); + } + } + ExtendedInstruction::Repeat { count, body, .. } => { + let mut block = Vec::new(); + lower(body, &mut block, pools); + for _ in 0..*count { + ops.extend_from_slice(&block); + } + } + ExtendedInstruction::Annotation(a) => match a.kind { + AnnotationKind::Detector + | AnnotationKind::ObservableInclude + | AnnotationKind::QubitCoords + | AnnotationKind::ShiftCoords + | AnnotationKind::Tick => {} + }, + other => panic!("unsupported instruction {other:?}"), + } + } +} + +/// `CX`/`CY`/`CZ` with a `rec[-k]` control (either side for `CZ`). +fn feedback(name: GateName, a: Target, b: Target) -> Op { + let pauli = match name { + GateName::CX | GateName::ZCX | GateName::CNot => Basis::X, + GateName::CY | GateName::ZCY => Basis::Y, + GateName::CZ | GateName::ZCZ => Basis::Z, + other => panic!("unsupported classically controlled gate {other:?}"), + }; + match (a, b, pauli) { + (Target::Rec(back), Target::Qubit(q), _) + | (Target::Qubit(q), Target::Rec(back), Basis::Z) => Op::Feedback { pauli, back, q }, + _ => panic!("unsupported targets {a:?} {b:?} for {name:?}"), + } +} + +fn apply_one(s: &mut Sim, name: GateName, q: usize) { + match name { + GateName::X => s.x(q), + GateName::Y => s.y(q), + GateName::Z => s.z(q), + GateName::H | GateName::HXZ => s.h(q), + GateName::S | GateName::SqrtZ => s.s(q), + GateName::SDag | GateName::SqrtZDag => s.s_dag(q), + GateName::SqrtX => s.sqrt_x(q), + GateName::SqrtXDag => s.sqrt_x_dag(q), + GateName::SqrtY => s.sqrt_y(q), + GateName::SqrtYDag => s.sqrt_y_dag(q), + GateName::T => s.t(q), + GateName::TDag => s.t_dag(q), + other => panic!("unsupported gate {other:?}"), + } +} + +fn apply_two(s: &mut Sim, name: GateName, a: usize, b: usize) { + match name { + GateName::CX | GateName::ZCX | GateName::CNot => s.cnot(a, b), + GateName::CY | GateName::ZCY => s.cy(a, b), + GateName::CZ | GateName::ZCZ => s.cz(a, b), + other => panic!("unsupported gate {other:?}"), + } +} + +/// Map `basis` on `q` to `Z` (`to_z`) or back. +fn change_basis(s: &mut Sim, basis: Basis, q: usize, to_z: bool) { + match (basis, to_z) { + (Basis::Z, _) => {} + (Basis::X, _) => s.h(q), + (Basis::Y, true) => { + s.s_dag(q); + s.h(q); + } + (Basis::Y, false) => { + s.h(q); + s.s(q); + } + } +} + +fn pauli_basis(axis: PauliAxis) -> Basis { + match axis { + PauliAxis::X => Basis::X, + PauliAxis::Y => Basis::Y, + PauliAxis::Z => Basis::Z, + } +} + +/// Run `op`, appending measurement outcomes to `record`; `rng` flips recorded +/// outcomes. +fn run(s: &mut Sim, op: Op, pools: &Pools, rng: &mut SmallRng, record: &mut Vec) { + let mut noisy = |m: bool, flip: f64| m ^ (flip > 0.0 && rng.random::() < flip); + match op { + Op::One(name, q) => apply_one(s, name, q), + Op::Two(name, a, b) => apply_two(s, name, a, b), + Op::T(q) => s.t(q), + Op::TDag(q) => s.t_dag(q), + Op::Rotation(axis, theta, q) => match axis { + Axis::X => s.rx(q, theta), + Axis::Y => s.ry(q, theta), + Axis::Z => s.rz(q, theta), + }, + Op::U3([theta, phi, lambda], q) => s.u3(q, theta, phi, lambda), + Op::Pauli { p, at, len } => s.pauli_error_many(&pools.noise[at..at + len], p), + Op::Depolarize2 { p, at, len } => s.depolarize2_many(&pools.pairs[at..at + len], p), + Op::Measure { + basis, + q, + flip, + reset, + } => { + change_basis(s, basis, q, true); + let m = s.measure(q); + if reset { + reset_measured(s, q, m); + } + change_basis(s, basis, q, false); + record.push(noisy(m.unwrap_or(false), flip)); + } + Op::MeasureZ { + at, + len, + flip, + reset, + } => { + let targets = &pools.measured[at..at + len]; + for (m, &q) in s.measure_many(targets).into_iter().zip(targets) { + if reset { + reset_measured(s, q, m); + } + record.push(noisy(m.unwrap_or(false), flip)); + } + } + Op::Feedback { pauli, back, q } => { + if record[record.len() - back] { + match pauli { + Basis::X => s.x(q), + Basis::Y => s.y(q), + Basis::Z => s.z(q), + } + } + } + Op::Reset(basis, q) => match basis { + Basis::Z => s.reset(q), + Basis::X => s.reset_x(q), + Basis::Y => s.reset_y(q), + }, + // Basis changes to Z, a CX ladder onto the first qubit, measure, undo. + Op::Mpp { at, len, flip } => { + let product = &pools.factors[at..at + len]; + let first = product[0].qubit; + for f in product { + change_basis(s, pauli_basis(f.axis), f.qubit, true); + } + for f in &product[1..] { + s.cnot(f.qubit, first); + } + let m = s.measure(first).unwrap_or(false); + for f in product[1..].iter().rev() { + s.cnot(f.qubit, first); + } + for f in product { + change_basis(s, pauli_basis(f.axis), f.qubit, false); + } + record.push(noisy(m, flip)); + } + } +} + +/// Reset `q` to `|0⟩` after measuring `m`: flip a `1`, and revive a lost qubit +/// (`None`) with a full reset. +fn reset_measured(s: &mut Sim, q: usize, m: Option) { + match m { + Some(true) => s.x(q), + Some(false) => {} + None => s.reset(q), + } +} + +/// Loss channel with probability `p` on each target of `op`, if it is a gate. +fn lose_after(s: &mut Sim, op: Op, p: f64) { + match op { + Op::One(_, q) | Op::T(q) | Op::TDag(q) | Op::Rotation(_, _, q) | Op::U3(_, q) => { + s.loss_channel(q, p) + } + Op::Two(_, a, b) => { + s.loss_channel(a, p); + s.loss_channel(b, p); + } + _ => {} + } +} + +fn qubits(op: &Op, pools: &Pools) -> Vec { + match *op { + Op::Two(_, a, b) => vec![a, b], + Op::One(_, q) + | Op::T(q) + | Op::TDag(q) + | Op::Rotation(_, _, q) + | Op::U3(_, q) + | Op::Measure { q, .. } + | Op::Reset(_, q) + | Op::Feedback { q, .. } => vec![q], + Op::Mpp { at, len, .. } => pools.factors[at..at + len] + .iter() + .map(|f| f.qubit) + .collect(), + Op::MeasureZ { at, len, .. } => pools.measured[at..at + len].to_vec(), + Op::Pauli { at, len, .. } => pools.noise[at..at + len].to_vec(), + Op::Depolarize2 { at, len, .. } => pools.pairs[at..at + len] + .iter() + .flat_map(|&(a, b)| [a, b]) + .collect(), + } +} + +fn main() { + let mut args = std::env::args().skip(1); + let path = args + .next() + .expect("usage: run_clifft [shots] [--records ] [--loss

]"); + let (mut shots, mut records_path, mut loss) = (1000usize, None, 0.0); + while let Some(arg) = args.next() { + if arg == "--records" { + records_path = Some(args.next().expect("--records needs a path")); + } else if arg == "--loss" { + loss = args + .next() + .expect("--loss needs p") + .parse() + .expect("loss p"); + } else { + shots = arg.parse().expect("shots"); + } + } + let src = rewrite_dialect(&std::fs::read_to_string(&path).expect("read circuit")); + let program = + stim_parser::parse_extended(&src).unwrap_or_else(|e| panic!("parse error: {e:?}")); + let (mut ops, mut pools) = (Vec::new(), Pools::default()); + lower(&program.instructions, &mut ops, &mut pools); + let n = 1 + ops + .iter() + .flat_map(|op| qubits(op, &pools)) + .max() + .expect("empty circuit"); + + let mut rng = SmallRng::seed_from_u64(0x9e37_79b9_7f4a_7c15); + let (mut record, mut records) = (Vec::new(), String::new()); + let (mut parity, mut max_k, mut k_at_measurements, mut measurements) = + (false, 0, 0usize, 0usize); + let start = Instant::now(); + for _ in 0..shots { + let mut s = Sim::new_with_seed(n, rng.random()); + record.clear(); + for &op in &ops { + run(&mut s, op, &pools, &mut rng, &mut record); + if loss > 0.0 { + lose_after(&mut s, op, loss); + } + let k = s.state().active().len(); + max_k = max_k.max(k); + let count = match op { + Op::Measure { .. } | Op::Mpp { .. } => 1, + Op::MeasureZ { len, .. } => len, + _ => 0, + }; + k_at_measurements += k * count; + measurements += count; + } + parity ^= record.iter().fold(false, |p, &m| p ^ m); + if records_path.is_some() { + records.extend(record.iter().map(|&m| if m { '1' } else { '0' })); + records.push('\n'); + } + } + let elapsed = start.elapsed().as_secs_f64(); + if let Some(p) = records_path { + std::fs::write(p, records).expect("write records"); + } + println!( + "{path}: {n} qubits, {} ops ({} measurements) per shot, {shots} shots", + ops.len(), + record.len() + ); + println!( + "{:.1} µs/shot, {:.0} shots/s, max k {max_k}, mean k at measurements {:.2} (parity {parity})", + elapsed / shots as f64 * 1e6, + shots as f64 / elapsed, + k_at_measurements as f64 / measurements.max(1) as f64, + ); +} diff --git a/crates/ppvm-tableau-2/examples/run_stim.rs b/crates/ppvm-tableau-2/examples/run_stim.rs new file mode 100644 index 000000000..c65253b4f --- /dev/null +++ b/crates/ppvm-tableau-2/examples/run_stim.rs @@ -0,0 +1,184 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Benchmark and profiling harness: runs a Stim circuit's Clifford gates, +//! measurements and resets on `InverseTableau`, one shot at a time with a fresh +//! tableau per shot. Noise and annotations are skipped (noise sampling is the +//! circuit runner's job, not the tableau's). +//! +//! ```text +//! cargo run --release -p ppvm-tableau-2 --example run_stim -- [shots] +//! ``` +//! +//! The clifft-bench surface code (d = 7, 7 rounds) is fetched by +//! `scripts/fetch_clifft_bench.sh` into `target/clifft-bench/`. + +use std::time::Instant; + +use ppvm_tableau_2::InverseTableau; +use ppvm_traits_2::Clifford; +use stim_parser::instructions::{GateName, MeasureName}; +use stim_parser::prelude::{Instruction, Target}; + +/// One gate, or one measurement instruction over `targets[at..at + len]` +/// (kept together so they run as one `measure_many`). +#[derive(Clone, Copy)] +enum Op { + One(GateName, usize), + Two(GateName, usize, usize), + Measure { at: usize, len: usize }, + Reset(usize), + MeasureReset { at: usize, len: usize }, +} + +fn qubits(targets: &[Target]) -> Vec { + targets + .iter() + .map(|t| t.as_qubit().expect("only qubit targets are supported")) + .collect() +} + +/// Flatten the program into ops, unrolling `REPEAT` blocks. Measurement +/// targets go to `targets`. +fn lower(instructions: &[Instruction], ops: &mut Vec, targets: &mut Vec) { + for instruction in instructions { + match instruction { + Instruction::Gate(g) => { + let qs = qubits(&g.targets); + match g.name { + GateName::Reset | GateName::ResetZ => { + ops.extend(qs.iter().map(|&q| Op::Reset(q))) + } + GateName::CX | GateName::CZ | GateName::CY => { + ops.extend(qs.chunks(2).map(|p| Op::Two(g.name, p[0], p[1]))) + } + name => ops.extend(qs.iter().map(|&q| Op::One(name, q))), + } + } + Instruction::Measure(m) => { + let (at, len) = (targets.len(), m.targets.len()); + targets.extend_from_slice(&m.targets); + ops.push(match m.name { + MeasureName::M | MeasureName::MZ => Op::Measure { at, len }, + MeasureName::MR => Op::MeasureReset { at, len }, + other => panic!("unsupported measurement {other:?}"), + }); + } + Instruction::Repeat { count, body, .. } => { + let mut block = Vec::new(); + lower(body, &mut block, targets); + for _ in 0..*count { + ops.extend_from_slice(&block); + } + } + Instruction::Noise(_) | Instruction::Annotation(_) => {} + other => panic!("unsupported instruction {other:?}"), + } + } +} + +fn apply_one(t: &mut InverseTableau, name: GateName, q: usize) { + match name { + GateName::X => t.x(q), + GateName::Y => t.y(q), + GateName::Z => t.z(q), + GateName::H | GateName::HXZ => t.h(q), + GateName::S | GateName::SqrtZ => t.s(q), + GateName::SDag | GateName::SqrtZDag => t.s_dag(q), + GateName::SqrtX => t.sqrt_x(q), + GateName::SqrtXDag => t.sqrt_x_dag(q), + GateName::SqrtY => t.sqrt_y(q), + GateName::SqrtYDag => t.sqrt_y_dag(q), + other => panic!("unsupported gate {other:?}"), + } +} + +fn apply_two(t: &mut InverseTableau, name: GateName, a: usize, b: usize) { + match name { + GateName::CX => t.cnot(a, b), + GateName::CZ => t.cz(a, b), + _ => t.cy(a, b), + } +} + +fn main() { + let mut args = std::env::args().skip(1); + let path = args.next().expect("usage: run_stim [shots]"); + let shots: usize = args.next().map_or(1000, |s| s.parse().expect("shots")); + let program = stim_parser::parse(&std::fs::read_to_string(&path).expect("read circuit")) + .unwrap_or_else(|e| panic!("parse error: {e:?}")); + let (mut ops, mut targets) = (Vec::new(), Vec::new()); + lower(&program.instructions, &mut ops, &mut targets); + let n = 1 + ops + .iter() + .flat_map(|op| match *op { + Op::Two(_, a, b) => vec![a, b], + Op::One(_, q) | Op::Reset(q) => vec![q], + Op::Measure { at, len } | Op::MeasureReset { at, len } => { + targets[at..at + len].to_vec() + } + }) + .max() + .expect("empty circuit"); + let mut outcomes = vec![false; targets.len()]; + + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut coin = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed & 1 == 1 + }; + let (mut parity, mut random) = (false, 0usize); + let start = Instant::now(); + for _ in 0..shots { + let mut t = InverseTableau::new(n); + for &op in &ops { + let mut flip = || { + random += 1; + coin() + }; + match op { + Op::One(name, q) => apply_one(&mut t, name, q), + Op::Two(name, a, b) => apply_two(&mut t, name, a, b), + Op::Measure { at, len } => { + let out = &mut outcomes[..len]; + t.measure_many(&targets[at..at + len], &mut flip, out); + parity ^= out.iter().fold(false, |p, &m| p ^ m); + } + Op::Reset(q) => t.reset(q, &mut flip), + Op::MeasureReset { at, len } => { + let out = &mut outcomes[..len]; + t.measure_many(&targets[at..at + len], &mut flip, out); + for (&q, &m) in targets[at..at + len].iter().zip(out.iter()) { + parity ^= m; + if m { + t.x(q); + } + } + } + } + } + } + let elapsed = start.elapsed().as_secs_f64(); + let count = |reset: bool| -> usize { + ops.iter() + .map(|op| match *op { + Op::Measure { len, .. } | Op::MeasureReset { len, .. } => len, + Op::Reset(_) => usize::from(reset), + _ => 0, + }) + .sum() + }; + let measurements = count(false); + println!( + "{path}: {n} qubits, {} ops ({measurements} measurements) per shot, {shots} shots", + ops.len() + ); + println!( + "{:.1} µs/shot, {:.0} shots/s, {:.1}% of measurements and resets random (parity {parity})", + elapsed / shots as f64 * 1e6, + shots as f64 / elapsed, + 100.0 * random as f64 / (shots * count(true)) as f64, + ); +} diff --git a/crates/ppvm-tableau-2/src/display.rs b/crates/ppvm-tableau-2/src/display.rs new file mode 100644 index 000000000..e14cf9e1e --- /dev/null +++ b/crates/ppvm-tableau-2/src/display.rs @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! `Display` for the simulator and its parts, built from their public +//! accessors. + +use std::fmt::{Display, Formatter, Result}; + +use crate::{ + ActiveDormant, ActiveState, DenseState, GeneralizedTableau, InverseTableau, RowRef, + VirtualState, +}; + +/// A row as a signed Pauli string over `n` qubits, qubit 0 first: `-XZI`. +fn write_row(f: &mut Formatter<'_>, row: RowRef<'_>, n: usize) -> Result { + write!(f, "{}", if row.negative { '-' } else { '+' })?; + for q in 0..n { + let c = match (row.x_bit(q), row.z_bit(q)) { + (false, false) => 'I', + (true, false) => 'X', + (true, true) => 'Y', + (false, true) => 'Z', + }; + write!(f, "{c}")?; + } + Ok(()) +} + +/// One line per qubit: the rows `C⁻¹ X_q C` and `C⁻¹ Z_q C`. +impl Display for InverseTableau { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let n = self.num_qubits(); + writeln!( + f, + "InverseTableau ({n} qubits, rows C⁻¹ X_q C and C⁻¹ Z_q C):" + )?; + for q in 0..n { + write!(f, " {q}: ")?; + write_row(f, self.ix(q), n)?; + write!(f, " ")?; + write_row(f, self.iz(q), n)?; + writeln!(f)?; + } + Ok(()) + } +} + +/// The nonzero amplitudes, axis 0 as the rightmost bit. +impl Display for DenseState { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let k = self.num_axes(); + for (alpha, c) in self.amplitudes().iter().enumerate() { + if c.norm_sqr() > 0.0 { + writeln!(f, " |{alpha:0k$b}⟩: {c}")?; + } + } + Ok(()) + } +} + +/// The virtual qubit of each axis, then `φ` over the axes. +impl Display for ActiveDormant { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + writeln!( + f, + "Active virtual qubits (axis 0 first): {:?}", + self.active() + )?; + write!(f, "{}", self.phi()) + } +} + +impl Display for GeneralizedTableau { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + let n = self.num_qubits(); + writeln!(f, "GeneralizedTableau ({n} qubits):")?; + write!(f, "{}", self.tableau())?; + write!(f, "{}", self.state())?; + let lost: Vec = (0..n).filter(|&q| self.is_lost(q)).collect(); + let leaked: Vec = (0..n).filter(|&q| self.is_leaked(q)).collect(); + writeln!(f, "Lost: {lost:?}, leaked: {leaked:?}") + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/data.rs b/crates/ppvm-tableau-2/src/generalized_tableau/data.rs new file mode 100644 index 000000000..3c45a8363 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/data.rs @@ -0,0 +1,135 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use rand::SeedableRng; +use rand::rngs::SmallRng; + +use num_complex::Complex64; +use ppvm_traits_2::{Clifford, Pauli}; + +use super::status::QubitStatus; +use crate::{InverseTableau, VirtualState}; + +/// The state `|ψ⟩ = C |χ⟩`: the Clifford `C` as an [`InverseTableau`], and the +/// virtual state `|χ⟩` in the representation `V`. +/// +/// Physical gates `C ← G·C` touch only the tableau. Measurements ask `V` for +/// the outcome weights, sample here, and let `V` collapse. Lost and leaked +/// qubits are tracked here; the tableau and `V` never see them. +#[derive(Clone, Debug)] +pub struct GeneralizedTableau { + pub(super) tableau: InverseTableau, + pub(super) state: V, + pub(super) status: Vec, + pub(super) rng: SmallRng, +} + +impl GeneralizedTableau { + /// `|0…0⟩` on `n` qubits, with the RNG seeded from OS entropy. + pub fn new(n: usize) -> Self { + Self::with_rng(n, rand::make_rng()) + } + + /// Same as [`new`](Self::new), but seed the RNG deterministically. + pub fn new_with_seed(n: usize, seed: u64) -> Self { + Self::with_rng(n, SmallRng::seed_from_u64(seed)) + } + + /// Clone the state but reseed the RNG, giving an independent simulation + /// branch. `Some(seed)` seeds it deterministically; `None` from OS entropy. + pub fn fork(&self, seed: Option) -> Self { + let mut forked = self.clone(); + forked.rng = match seed { + Some(s) => SmallRng::seed_from_u64(s), + None => rand::make_rng(), + }; + forked + } + + fn with_rng(n: usize, rng: SmallRng) -> Self { + Self { + tableau: InverseTableau::new(n), + state: V::new(n), + status: vec![QubitStatus::Live; n], + rng, + } + } + + pub fn num_qubits(&self) -> usize { + self.tableau.num_qubits() + } + + pub fn tableau(&self) -> &InverseTableau { + &self.tableau + } + + pub fn state(&self) -> &V { + &self.state + } + + /// Whether `q` is lost: gates skip it and measuring it gives `None`. + pub fn is_lost(&self, q: usize) -> bool { + self.status[q] == QubitStatus::Lost + } + + /// Whether `q` is leaked: gates skip it and measuring it gives the pinned bit. + pub fn is_leaked(&self, q: usize) -> bool { + self.status[q] == QubitStatus::Leaked + } + + /// Whether `q` is lost or leaked, so gates skip it. + pub(super) fn is_inactive(&self, q: usize) -> bool { + self.status[q].is_inactive() + } + + /// `|ψ⟩ ← (a·I + b·∏ Z_q) |ψ⟩` over `qubits`, which must be distinct. + /// Inactive qubits are dropped, as gates skip them. + pub(super) fn rotate_z(&mut self, qubits: &[usize], a: Complex64, b: Complex64) { + let live: Vec; + let qubits = if qubits.iter().any(|&q| self.is_inactive(q)) { + live = qubits + .iter() + .copied() + .filter(|&q| !self.is_inactive(q)) + .collect(); + if live.is_empty() { + return; + } + &live[..] + } else { + qubits + }; + let mut view = self.tableau.virtual_view(); + self.state.rotate(&mut view, qubits, a, b); + } + + /// `exp(−i θ/2 ∏ Z_q) = cos(θ/2)·I − i sin(θ/2)·∏ Z_q`. + pub(super) fn rz_product(&mut self, qubits: &[usize], theta: f64) { + let (s, c) = (theta / 2.0).sin_cos(); + self.rotate_z(qubits, Complex64::new(c, 0.0), Complex64::new(0.0, -s)); + } + + /// Map `axis` on `q` to `Z`: apply `W` with `W·axis·W† = Z`. + pub(super) fn axis_to_z(&mut self, axis: Pauli, q: usize) { + match axis { + Pauli::X => self.h(q), + Pauli::Y => { + self.s_dag(q); + self.h(q); + } + Pauli::Z | Pauli::I => {} + } + } + + /// Undo [`axis_to_z`](Self::axis_to_z): apply `W†`. + pub(super) fn z_to_axis(&mut self, axis: Pauli, q: usize) { + match axis { + Pauli::X => self.h(q), + Pauli::Y => { + self.h(q); + self.s(q); + } + Pauli::Z | Pauli::I => {} + } + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/gates/clifford.rs b/crates/ppvm-tableau-2/src/generalized_tableau/gates/clifford.rs new file mode 100644 index 000000000..31c719731 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/gates/clifford.rs @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use ppvm_traits_2::{ApplyGateRule, CliffordBatch}; + +use super::super::GeneralizedTableau; +use crate::VirtualState; + +/// Physical gates `C ← G·C` go to the tableau; `|χ⟩` is untouched. A gate on a +/// lost or leaked qubit is skipped, a two-qubit gate as a whole. +impl ApplyGateRule for GeneralizedTableau { + type B = bool; + + fn apply1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + if !self.is_inactive(q) { + self.tableau.apply1(q, rule); + } + } + + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([bool; 4]) -> ([bool; 4], bool)) { + if !self.is_inactive(a) && !self.is_inactive(b) { + self.tableau.apply2(a, b, rule); + } + } + + fn apply_sign1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + if !self.is_inactive(q) { + self.tableau.apply_sign1(q, rule); + } + } +} + +impl CliffordBatch for GeneralizedTableau {} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/gates/mod.rs b/crates/ppvm-tableau-2/src/generalized_tableau/gates/mod.rs new file mode 100644 index 000000000..901ad87e7 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/gates/mod.rs @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +mod clifford; +mod reset; +mod rot1; +mod rot2; +mod tgate; +mod u3; diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/gates/reset.rs b/crates/ppvm-tableau-2/src/generalized_tableau/gates/reset.rs new file mode 100644 index 000000000..5f821755d --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/gates/reset.rs @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use ppvm_traits_2::{Clifford, Reset, ResetState}; + +use super::super::GeneralizedTableau; +use super::super::status::QubitStatus; +use crate::VirtualState; + +/// Measure, then flip the qubit if it was `|1⟩`. Lost and leaked qubits are +/// left alone. +impl ResetState for GeneralizedTableau { + fn reset_state(&mut self, q: usize) { + if !self.is_inactive(q) && self.sample_z(q) { + self.x(q); + } + } +} + +/// A full reset: a lost or leaked qubit becomes live, then its state is reset. +impl Reset for GeneralizedTableau { + fn reset(&mut self, q: usize) { + self.status[q] = QubitStatus::Live; + self.reset_state(q); + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/gates/rot1.rs b/crates/ppvm-tableau-2/src/generalized_tableau/gates/rot1.rs new file mode 100644 index 000000000..c4b84623e --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/gates/rot1.rs @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use ppvm_traits_2::{Pauli, RotXY, RotationOne, RotationOneBatch}; + +use super::super::GeneralizedTableau; +use crate::VirtualState; + +/// `exp(−i θ/2 P)`: `P` is mapped to `Z` by a physical Clifford. +impl RotationOne for GeneralizedTableau { + fn rotate_1(&mut self, axis: Pauli, q: usize, theta: f64) { + if axis == Pauli::I { + return; + } + self.axis_to_z(axis, q); + self.rz_product(&[q], theta); + self.z_to_axis(axis, q); + } +} + +impl RotationOneBatch for GeneralizedTableau {} + +/// `R(φ, θ) = RZ(φ)·RX(θ)·RZ(−φ)`, exact: `RZ(φ)` turns `X` into +/// `cos φ·X + sin φ·Y`. Gates apply in circuit order, `RZ(−φ)` first. +impl RotXY for GeneralizedTableau { + fn r(&mut self, q: usize, axis_angle: f64, theta: f64) { + self.rz(q, -axis_angle); + self.rx(q, theta); + self.rz(q, axis_angle); + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/gates/rot2.rs b/crates/ppvm-tableau-2/src/generalized_tableau/gates/rot2.rs new file mode 100644 index 000000000..3b2989ea1 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/gates/rot2.rs @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use ppvm_traits_2::{Pauli, RotationTwo, RotationTwoBatch}; + +use super::super::GeneralizedTableau; +use crate::VirtualState; + +/// `exp(−i θ/2 P_a ⊗ P_b)`: each factor is mapped to `Z` by a physical Clifford. +impl RotationTwo for GeneralizedTableau { + fn rotate_2(&mut self, axis_a: Pauli, axis_b: Pauli, a: usize, b: usize, theta: f64) { + assert_ne!(a, b, "two-qubit rotation on one qubit"); + let qubits: Vec = [(axis_a, a), (axis_b, b)] + .into_iter() + .filter(|&(axis, _)| axis != Pauli::I) + .map(|(_, q)| q) + .collect(); + self.axis_to_z(axis_a, a); + self.axis_to_z(axis_b, b); + self.rz_product(&qubits, theta); + self.z_to_axis(axis_a, a); + self.z_to_axis(axis_b, b); + } +} + +impl RotationTwoBatch for GeneralizedTableau {} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/gates/tgate.rs b/crates/ppvm-tableau-2/src/generalized_tableau/gates/tgate.rs new file mode 100644 index 000000000..9f4d9e2c4 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/gates/tgate.rs @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use num_complex::Complex64; +use ppvm_traits_2::TGate; + +use super::super::GeneralizedTableau; +use crate::VirtualState; + +/// `T = diag(1, ω) = ½(1 + ω)·I + ½(1 − ω)·Z` with `ω = e^{iπ/4}`, exact +/// including the global phase. +impl TGate for GeneralizedTableau { + fn t(&mut self, q: usize) { + let w = Complex64::from_polar(1.0, std::f64::consts::FRAC_PI_4); + self.rotate_z(&[q], (1.0 + w) / 2.0, (1.0 - w) / 2.0); + } + + fn t_dag(&mut self, q: usize) { + let w = Complex64::from_polar(1.0, -std::f64::consts::FRAC_PI_4); + self.rotate_z(&[q], (1.0 + w) / 2.0, (1.0 - w) / 2.0); + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/gates/u3.rs b/crates/ppvm-tableau-2/src/generalized_tableau/gates/u3.rs new file mode 100644 index 000000000..159d86951 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/gates/u3.rs @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use ppvm_traits_2::{RotationOne, U3Gate}; + +use super::super::GeneralizedTableau; +use crate::VirtualState; + +/// `U3(θ, φ, λ) = RZ(φ)·RY(θ)·RZ(λ)` up to the global phase `e^{i(φ+λ)/2}`. +/// Gates apply in circuit order, `RZ(λ)` first. +impl U3Gate for GeneralizedTableau { + fn u3(&mut self, q: usize, theta: f64, phi: f64, lambda: f64) { + self.rz(q, lambda); + self.ry(q, theta); + self.rz(q, phi); + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/loss.rs b/crates/ppvm-tableau-2/src/generalized_tableau/loss.rs new file mode 100644 index 000000000..821d6f042 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/loss.rs @@ -0,0 +1,371 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Loss and leakage. A lost qubit is collapsed, reset to `|0⟩` and skipped by +//! gates; measuring it gives `None`. A leaked qubit is collapsed and pinned to +//! `|0⟩` or `|1⟩`; gates skip it, and measuring it gives the pinned bit. Loss +//! overwrites leakage. Neither event is a measurement outcome. + +use num_complex::Complex64; +use rand::RngExt; + +use ppvm_traits_2::{ + AsymmetricLossChannel, Clifford, CorrelatedLossChannel, LeakageChannel, LossChannel, + ResetLeakageChannel, ResetLossChannel, ResetState, +}; + +use super::GeneralizedTableau; +use super::status::QubitStatus; +use crate::VirtualState; + +impl GeneralizedTableau { + /// Reset `q`, collapsed onto outcome `m`, to `|0⟩` and mark it lost. The `X` + /// goes straight to the tableau, as `q` may be leaked. + fn mark_lost(&mut self, q: usize, m: bool) { + if m { + self.tableau.x(q); + } + self.status[q] = QubitStatus::Lost; + } + + /// Collapse `q` by sampling `Z_q`, then reset it and mark it lost. + fn lose(&mut self, q: usize) { + let m = self.sample_z(q); + self.mark_lost(q, m); + } +} + +/// With probability `p`, lose `q`. A lost qubit stays lost. +impl LossChannel for GeneralizedTableau { + fn loss_channel(&mut self, q: usize, p: f64) { + if !self.is_lost(q) && self.rng.random::() < p { + self.lose(q); + } + } +} + +/// Bring a lost qubit back as live; it is already in `|0⟩`. +impl ResetLossChannel for GeneralizedTableau { + fn reset_loss_channel(&mut self, q: usize) { + if self.is_lost(q) { + self.status[q] = QubitStatus::Live; + } + } +} + +/// With probability `p0` pin `q` to `|0⟩` and mark it leaked, with `p1` to +/// `|1⟩`. Lost and leaked qubits are left alone. +impl LeakageChannel for GeneralizedTableau { + fn leakage_channel(&mut self, q: usize, p0: f64, p1: f64) { + debug_assert!(p0 >= 0.0 && p1 >= 0.0 && p0 + p1 <= 1.0 + 1e-9); + if self.is_inactive(q) { + return; + } + let r = self.rng.random::(); + if r >= p0 + p1 { + return; + } + let pin = r >= p0; + if self.sample_z(q) != pin { + self.tableau.x(q); + } + self.status[q] = QubitStatus::Leaked; + } +} + +/// Bring a leaked qubit back as live `|0⟩`. Live and lost qubits are untouched. +impl ResetLeakageChannel for GeneralizedTableau { + fn reset_leakage_channel(&mut self, q: usize) { + if self.is_leaked(q) { + self.status[q] = QubitStatus::Live; + self.reset_state(q); + } + } +} + +/// `p = [p_LL, p_LQ, p_LN]` as the trait documents: if one of the pair is +/// already lost, the other is lost with `p[2]`; otherwise both with `p[0]` and +/// each named one alone with `p[1]`. A leaked partner counts as present. +impl CorrelatedLossChannel for GeneralizedTableau { + fn correlated_loss_channel(&mut self, a: usize, b: usize, p: [f64; 3]) { + debug_assert!( + p[0] >= 0.0 && p[1] >= 0.0 && p[0] + 2.0 * p[1] <= 1.0 + 1e-9, + "correlated loss needs p0, p1 >= 0 and p0 + 2·p1 <= 1; got {p:?}" + ); + debug_assert!((0.0..=1.0).contains(&p[2]), "p2 in [0, 1]; got {p:?}"); + if self.is_lost(a) { + self.loss_channel(b, p[2]); + } else if self.is_lost(b) { + self.loss_channel(a, p[2]); + } else { + match self.draw(&[p[0], p[1], p[1]]) { + Some(0) => { + self.lose(a); + self.lose(b); + } + Some(1) => self.lose(a), + Some(_) => self.lose(b), + None => {} + } + } + } +} + +/// State-dependent loss, with its back-action (issue #249). With Born weights +/// `P(m)` of `Z_q`, `q` is lost from `|m⟩` with probability `p_m·P(m)`; +/// otherwise the survival Kraus operator +/// `K₀ = √(1−p0)|0⟩⟨0| + √(1−p1)|1⟩⟨1| = a·I + b·Z_q` is applied and the state +/// renormalized. On a qubit in superposition `K₀` is non-Clifford and +/// activates an axis. +impl AsymmetricLossChannel for GeneralizedTableau { + fn asymmetric_loss_channel(&mut self, q: usize, p0: f64, p1: f64) { + debug_assert!((0.0..=1.0).contains(&p0) && (0.0..=1.0).contains(&p1)); + if self.is_lost(q) { + return; + } + let [w0, w1] = self.z_weights(q); + let pop = [w0 / (w0 + w1), w1 / (w0 + w1)]; + if let Some(k) = self.draw(&[p0 * pop[0], p1 * pop[1]]) { + // Lost from |m⟩: the outcome comes from the branch, not from `P(m)`. + let m = k == 1; + self.collapse(q, m); + self.mark_lost(q, m); + return; + } + // K₀ ∝ I: the renormalized state is unchanged, and rotating would + // activate an axis for nothing. + if p0 == p1 { + return; + } + // Scaled so the norm is unchanged: ‖K₀ψ‖² = Σ (1 − p_m)·P(m). + let scale = ((1.0 - p0) * pop[0] + (1.0 - p1) * pop[1]).sqrt().recip(); + let (s0, s1) = ((1.0 - p0).sqrt(), (1.0 - p1).sqrt()); + let a = Complex64::from((s0 + s1) / 2.0 * scale); + let b = Complex64::from((s0 - s1) / 2.0 * scale); + self.rotate_z(&[q], a, b); + } +} + +#[cfg(test)] +mod tests { + use std::f64::consts::PI; + + use ppvm_traits_2::{Measure, Pauli, Reset, RotationOne, RotationTwo, TGate}; + + use super::*; + use crate::{ActiveDormant, DenseState}; + + type Sim = GeneralizedTableau>; + + /// Whether `count` of `shots` is within 5σ of `rate`. + fn within(count: usize, shots: usize, rate: f64) -> bool { + let sigma = (rate * (1.0 - rate) / shots as f64).sqrt(); + ((count as f64 / shots as f64) - rate).abs() <= 5.0 * sigma + } + + /// A lost qubit reads `None` and no gate reaches it, including a CX from a + /// live `|1⟩` control. Clearing the flag finds it still in `|0⟩`. + #[test] + fn lost_qubit_is_skipped_and_reads_none() { + let mut s = Sim::new_with_seed(2, 0); + s.loss_channel(0, 1.0); + assert!(s.is_lost(0)); + s.x(1); + s.cnot(1, 0); + s.x(0); + s.h(0); + s.rx(0, 1.0); + s.t(0); + assert_eq!(s.measure(0), None); + assert_eq!(s.measure(1), Some(true)); + s.reset_loss_channel(0); + assert!(!s.is_lost(0)); + assert_eq!(s.measure(0), Some(false)); + } + + /// `exp(−iπ/2 X⊗X)` with the second qubit lost acts as `exp(−iπ/2 X)` on + /// the first and flips it; skipping it whole would leave `|0⟩`. + #[test] + fn rotation_with_a_lost_partner_acts_on_the_survivor() { + let mut s = Sim::new_with_seed(2, 0); + s.loss_channel(1, 1.0); + s.rotate_2(Pauli::X, Pauli::X, 0, 1, PI); + assert_eq!(s.measure(0), Some(true)); + assert_eq!(s.measure(1), None); + } + + /// Loss is an unrecorded measurement: losing half of a Bell pair leaves the + /// partner in a Z eigenstate, `|1⟩` half of the time. + #[test] + fn loss_collapses_the_partner() { + let shots = 2000; + let mut ones = 0; + for seed in 0..shots { + let mut s = Sim::new_with_seed(2, seed as u64); + s.h(0); + s.cnot(0, 1); + s.loss_channel(0, 1.0); + let [w0, w1] = s.z_weights(1); + assert!(w0 == 0.0 || w1 == 0.0, "partner is deterministic"); + ones += usize::from(s.measure(1).unwrap()); + } + assert!(within(ones, shots, 0.5), "{ones} of {shots}"); + } + + /// `loss_channel(p)` loses a qubit with probability `p`, whatever its state. + #[test] + fn loss_rate() { + let (p, shots) = (0.3, 20_000); + let mut lost = 0; + for seed in 0..shots { + let mut s = Sim::new_with_seed(1, seed as u64); + s.h(0); + s.loss_channel(0, p); + lost += usize::from(s.is_lost(0)); + } + assert!(within(lost, shots, p), "{lost} of {shots}"); + } + + /// A full reset brings a lost qubit back as live `|0⟩`, so gates reach it. + #[test] + fn reset_revives_a_lost_qubit() { + let mut s = Sim::new_with_seed(1, 0); + s.loss_channel(0, 1.0); + s.reset(0); + assert!(!s.is_lost(0)); + assert_eq!(s.measure(0), Some(false)); + s.x(0); + assert_eq!(s.measure(0), Some(true)); + } + + /// `leakage_channel(p0, p1)` pins to `|0⟩` with `p0` and `|1⟩` with `p1`, + /// whatever the state. Gates skip a leaked qubit, so it keeps reading the + /// pinned bit. + #[test] + fn leakage_pins_with_the_branch_probabilities() { + let (p0, p1, shots) = (0.2, 0.3, 20_000); + let (mut zeros, mut ones) = (0, 0); + for seed in 0..shots { + let mut s = Sim::new_with_seed(1, seed as u64); + s.h(0); + s.leakage_channel(0, p0, p1); + if s.is_leaked(0) { + let m = s.measure(0).unwrap(); + s.x(0); + s.h(0); + s.rx(0, 1.0); + assert_eq!(s.measure(0), Some(m), "gates skip a leaked qubit"); + if m { + ones += 1; + } else { + zeros += 1; + } + } + } + assert!(within(zeros, shots, p0), "{zeros} of {shots}"); + assert!(within(ones, shots, p1), "{ones} of {shots}"); + } + + /// Leakage reduction returns a leaked qubit as live `|0⟩`; it leaves a + /// lost qubit lost. + #[test] + fn reset_leakage_revives_only_leaked_qubits() { + let mut s = Sim::new_with_seed(2, 0); + s.leakage_channel(0, 0.0, 1.0); + assert_eq!(s.measure(0), Some(true)); + s.reset_leakage_channel(0); + assert!(!s.is_leaked(0)); + assert_eq!(s.measure(0), Some(false)); + s.x(0); + assert_eq!(s.measure(0), Some(true)); + s.loss_channel(1, 1.0); + s.reset_leakage_channel(1); + assert!(s.is_lost(1)); + } + + /// Loss overwrites leakage: the pinned `|1⟩` is reset to `|0⟩`. + #[test] + fn loss_overwrites_leakage() { + let mut s = Sim::new_with_seed(1, 0); + s.leakage_channel(0, 0.0, 1.0); + s.loss_channel(0, 1.0); + assert!(s.is_lost(0) && !s.is_leaked(0)); + assert_eq!(s.measure(0), None); + s.reset_loss_channel(0); + assert_eq!(s.measure(0), Some(false)); + } + + /// A full reset brings a leaked qubit back as live `|0⟩`. + #[test] + fn reset_revives_a_leaked_qubit() { + let mut s = Sim::new_with_seed(1, 0); + s.leakage_channel(0, 0.0, 1.0); + s.reset(0); + assert!(!s.is_leaked(0)); + assert_eq!(s.measure(0), Some(false)); + } + + /// `p = [p_LL, p_LQ, p_LN]`: from two present qubits both are lost with + /// `p_LL`, each named one alone with `p_LQ`; with one already lost, the + /// other is lost with `p_LN`. + #[test] + fn correlated_loss_event_rates() { + let (p, shots) = ([0.1, 0.2, 0.5], 20_000); + let mut counts = [0; 4]; + let mut second = 0; + for seed in 0..shots { + let mut s = Sim::new_with_seed(2, seed as u64); + s.h(0); + s.cnot(0, 1); + s.correlated_loss_channel(0, 1, p); + counts[usize::from(s.is_lost(0)) | usize::from(s.is_lost(1)) << 1] += 1; + let mut t = Sim::new_with_seed(2, seed as u64); + t.loss_channel(0, 1.0); + t.correlated_loss_channel(0, 1, p); + second += usize::from(t.is_lost(1)); + } + let rates = [1.0 - p[0] - 2.0 * p[1], p[1], p[1], p[0]]; + for (k, (&count, rate)) in counts.iter().zip(rates).enumerate() { + assert!( + within(count, shots, rate), + "event {k:#b}: {count} of {shots}" + ); + } + assert!(within(second, shots, p[2]), "{second} of {shots}"); + } + + /// The Bell-pair example of #249 with `p0 = 0, p1 = 1`: the qubit is lost + /// exactly from `|1⟩`, so a loss leaves the partner in `|1⟩`; survival + /// projects onto `|0⟩`, leaving `|00⟩`. Each happens half of the time. + #[test] + fn asymmetric_loss_on_a_bell_pair() { + let shots = 4000; + let mut lost = 0; + for seed in 0..shots { + let mut s = Sim::new_with_seed(2, seed as u64); + s.h(0); + s.cnot(0, 1); + s.asymmetric_loss_channel(0, 0.0, 1.0); + if s.is_lost(0) { + lost += 1; + assert_eq!(s.measure(1), Some(true), "lost from |1⟩"); + } else { + assert_eq!((s.measure(0), s.measure(1)), (Some(false), Some(false))); + } + } + assert!(within(lost, shots, 0.5), "{lost} of {shots}"); + } + + /// With `p0 = p1` the survival operator is proportional to `I`, so a + /// surviving qubit in superposition activates no axis. + #[test] + fn symmetric_asymmetric_loss_activates_no_axis() { + for seed in 0..50 { + let mut s = Sim::new_with_seed(2, seed); + s.h(0); + s.cnot(0, 1); + s.asymmetric_loss_channel(0, 0.3, 0.3); + assert!(s.state().active().is_empty(), "seed {seed}"); + } + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/measure.rs b/crates/ppvm-tableau-2/src/generalized_tableau/measure.rs new file mode 100644 index 000000000..d51334823 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/measure.rs @@ -0,0 +1,203 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use rand::RngExt; + +use ppvm_traits_2::Measure; + +use super::GeneralizedTableau; +use crate::VirtualState; + +impl GeneralizedTableau { + /// Unnormalized weights of the outcomes `0` and `1` of `Z_q`. + pub(super) fn z_weights(&mut self, q: usize) -> [f64; 2] { + let mut view = self.tableau.virtual_view(); + self.state.z_weights(&mut view, q) + } + + /// Project onto outcome `m` of `Z_q`, which must have nonzero weight. + pub(super) fn collapse(&mut self, q: usize, m: bool) { + let mut view = self.tableau.virtual_view(); + self.state.collapse(&mut view, q, m); + } + + /// Sample `Z_q` and collapse, whatever the status of `q`. + pub(super) fn sample_z(&mut self, q: usize) -> bool { + // Hot path: a stabilizer state measures on the tableau alone. + if self.state.is_zero() { + let rng = &mut self.rng; + return self.tableau.measure(q, || rng.random()); + } + let [w0, w1] = self.z_weights(q); + let m = self.rng.random::() * (w0 + w1) < w1; + self.collapse(q, m); + m + } +} + +/// Measure `Z_q` and collapse; `Some(true)` for `|1⟩`. A lost qubit gives +/// `None`, a leaked one its pinned bit. +impl Measure for GeneralizedTableau { + fn measure(&mut self, q: usize) -> Option { + if self.is_lost(q) { + return None; + } + Some(self.sample_z(q)) + } + + /// With no active qubits, the live targets run as one batch on the + /// tableau's `measure_many` and lost ones give `None`; otherwise one target + /// at a time. + fn measure_many(&mut self, targets: &[usize]) -> Vec> { + if !self.state.is_zero() { + return targets.iter().map(|&q| self.measure(q)).collect(); + } + let live: Vec = targets + .iter() + .copied() + .filter(|&q| !self.is_lost(q)) + .collect(); + let mut outcomes = vec![false; live.len()]; + let rng = &mut self.rng; + self.tableau + .measure_many(&live, || rng.random(), &mut outcomes); + let mut outcomes = outcomes.into_iter(); + targets + .iter() + .map(|&q| (!self.is_lost(q)).then(|| outcomes.next().unwrap())) + .collect() + } +} + +#[cfg(test)] +mod tests { + use ppvm_traits_2::{Clifford, LossChannel, Reset, TGate}; + + use super::*; + use crate::{ActiveDormant, DenseState}; + + type Sim = GeneralizedTableau>; + + /// Bell pair: the two outcomes always agree, and both occur. + #[test] + fn bell_pair_outcomes_agree() { + let mut ones = 0; + for seed in 0..200 { + let mut s = Sim::new_with_seed(2, seed); + s.h(0); + s.cnot(0, 1); + let (a, b) = (s.measure(0).unwrap(), s.measure(1).unwrap()); + assert_eq!(a, b); + ones += usize::from(a); + } + assert!((60..140).contains(&ones), "{ones} of 200"); + } + + /// `n` Bell pairs `(2i, 2i + 1)`, with `T` on each control when `t`. + fn bell_pairs(n: usize, t: bool, seed: u64) -> Sim { + let mut s = Sim::new_with_seed(2 * n, seed); + for i in 0..n { + s.h(2 * i); + if t { + s.t(2 * i); + } + s.cnot(2 * i, 2 * i + 1); + } + s + } + + /// Batched Bell pairs, enough for the tableau's column-major path: each + /// pair agrees, about half are `1`, and measuring again repeats. + #[test] + fn measure_many_on_bell_pairs() { + let n = 100; + let targets: Vec = (0..2 * n).collect(); + for seed in 0..5 { + let mut s = bell_pairs(n, false, seed); + let m: Vec = s.measure_many(&targets).into_iter().flatten().collect(); + assert_eq!(m.len(), 2 * n); + assert!(m.chunks(2).all(|p| p[0] == p[1])); + let ones = m.iter().step_by(2).filter(|&&b| b).count(); + assert!((25..75).contains(&ones), "{ones} of {n}"); + let again: Vec = s.measure_many(&targets).into_iter().flatten().collect(); + assert_eq!(again, m); + } + } + + /// The per-target fallback: active qubits (from `T`) and a lost qubit, + /// which gives `None` while its partner is still measured. + #[test] + fn measure_many_with_active_or_lost_qubits() { + let targets: Vec = (0..8).collect(); + for seed in 0..20 { + let mut s = bell_pairs(4, true, seed); + assert!(!s.state().is_zero()); + let m = s.measure_many(&targets); + assert!(m.chunks(2).all(|p| p[0].is_some() && p[0] == p[1])); + + let mut s = bell_pairs(4, false, seed); + s.loss_channel(0, 1.0); + let m = s.measure_many(&targets); + assert_eq!(m[0], None); + assert!(m[1].is_some()); + assert!(m[2..].chunks(2).all(|p| p[0].is_some() && p[0] == p[1])); + } + } + + /// A measured qubit stays in its outcome, and reset leaves `|0⟩`. + #[test] + fn measurement_repeats_and_reset_clears() { + for seed in 0..50 { + let mut s = Sim::new_with_seed(3, seed); + s.h(0); + s.cnot(0, 1); + s.sqrt_x(2); + s.cz(1, 2); + for q in 0..3 { + let m = s.measure(q); + assert_eq!(s.measure(q), m); + } + for q in 0..3 { + s.reset(q); + assert_eq!(s.measure(q), Some(false)); + } + } + } + + /// A fork carries the collapsed state: after measuring one half of a Bell + /// pair, the fork's other half agrees with it. + #[test] + fn fork_keeps_the_collapsed_state() { + for seed in 0..50 { + let mut s = Sim::new_with_seed(2, seed); + s.h(0); + s.cnot(0, 1); + let a = s.measure(0); + let mut f = s.fork(Some(seed + 1000)); + assert_eq!(f.measure(1), a); + } + } + + /// Forks of a superposition sample independently: one seed repeats its + /// outcome, different seeds give both outcomes. + #[test] + fn forks_sample_independently() { + let mut s = Sim::new_with_seed(1, 0); + s.h(0); + let mut ones = 0; + for seed in 0..200 { + let m = s.fork(Some(seed)).measure(0); + assert_eq!(s.fork(Some(seed)).measure(0), m); + ones += usize::from(m.unwrap()); + } + assert!((60..140).contains(&ones), "{ones} of 200"); + } + + /// `X` then measure is deterministic: `Z|1⟩ = −|1⟩`. + #[test] + fn x_flips_the_outcome() { + let mut s = Sim::new_with_seed(1, 0); + s.x(0); + assert_eq!(s.measure(0), Some(true)); + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/mod.rs b/crates/ppvm-tableau-2/src/generalized_tableau/mod.rs new file mode 100644 index 000000000..4387626d0 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/mod.rs @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! [`GeneralizedTableau`]: the simulator, `|ψ⟩ = C |χ⟩`. +//! +//! - `data`: the struct, constructors and shared helpers. +//! - `gates`: Clifford, T, rotation and `U3` gates, and reset. +//! - `measure`: Z measurement. +//! - `loss`: loss and leakage channels. +//! - `noise`: Pauli and depolarizing channels. + +mod data; +mod gates; +mod loss; +mod measure; +mod noise; +mod status; + +pub use data::GeneralizedTableau; diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/noise.rs b/crates/ppvm-tableau-2/src/generalized_tableau/noise.rs new file mode 100644 index 000000000..3c1634990 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/noise.rs @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Pauli channels as trajectories: draw one Pauli and apply it as a physical +//! gate, so `|χ⟩` is untouched. + +use rand::RngExt; + +use ppvm_traits_2::{Clifford, Depolarizing, Depolarizing2, PauliError, TwoQubitPauliError}; + +use super::GeneralizedTableau; +use crate::VirtualState; + +impl GeneralizedTableau { + /// Draw event `k` with probability `probabilities[k]`, or `None` with the + /// remaining probability. Uses one random number. + pub(super) fn draw(&mut self, probabilities: &[f64]) -> Option { + debug_assert!(probabilities.iter().all(|&p| p >= 0.0)); + debug_assert!(probabilities.iter().sum::() <= 1.0 + 1e-9); + let r = self.rng.random::(); + let mut cumulative = 0.0; + probabilities.iter().position(|&p| { + cumulative += p; + r < cumulative + }) + } + + /// Draw event `k` with probability `probabilities[k] / total`, given that + /// one happens. Rounding falls back to the last possible event. + fn draw_given_event(&mut self, probabilities: &[f64], total: f64) -> usize { + let r = self.rng.random::() * total; + let mut cumulative = 0.0; + probabilities + .iter() + .position(|&p| { + cumulative += p; + r < cumulative + }) + .unwrap_or_else(|| probabilities.iter().rposition(|&p| p > 0.0).unwrap()) + } + + /// First index `≥ i` that gets an error when each target does independently + /// with probability `p`: a geometric skip from one random number. + fn next_error(&mut self, i: usize, p: f64) -> usize { + if p <= 0.0 { + return usize::MAX; + } + let u: f64 = self.rng.random(); + // ln(1 − u) / ln(1 − p) ≥ 0; the cast saturates, so huge skips end the loop. + let skip = ((-u).ln_1p() / (-p).ln_1p()).floor() as usize; + i.saturating_add(skip) + } + + /// Apply Pauli `k` (0 = I, 1 = X, 2 = Y, 3 = Z) to `q`. + fn pauli(&mut self, q: usize, k: usize) { + match k { + 0 => {} + 1 => self.x(q), + 2 => self.y(q), + _ => self.z(q), + } + } +} + +/// `X`, `Y`, `Z` with probabilities `p[0]`, `p[1]`, `p[2]`. The batched +/// methods skip straight to the next error instead of drawing per target. +impl PauliError for GeneralizedTableau { + fn pauli_error(&mut self, q: usize, p: [f64; 3]) { + if let Some(k) = self.draw(&p) { + self.pauli(q, k + 1); + } + } + + fn pauli_error_many(&mut self, targets: &[usize], p: [f64; 3]) { + let total: f64 = p.iter().sum(); + let mut i = self.next_error(0, total); + while i < targets.len() { + let k = self.draw_given_event(&p, total); + self.pauli(targets[i], k + 1); + i = self.next_error(i + 1, total); + } + } + + fn x_error_many(&mut self, targets: &[usize], p: f64) { + self.pauli_error_many(targets, [p, 0.0, 0.0]); + } + + fn y_error_many(&mut self, targets: &[usize], p: f64) { + self.pauli_error_many(targets, [0.0, p, 0.0]); + } + + fn z_error_many(&mut self, targets: &[usize], p: f64) { + self.pauli_error_many(targets, [0.0, 0.0, p]); + } +} + +/// `p[k]` is the probability of `P_a ⊗ P_b` with `4a + b = k + 1`, in the +/// trait's order `IX, IY, IZ, XI, …, ZZ`. +impl TwoQubitPauliError for GeneralizedTableau { + fn two_qubit_pauli_error(&mut self, a: usize, b: usize, p: [f64; 15]) { + if let Some(k) = self.draw(&p) { + self.pauli(a, (k + 1) / 4); + self.pauli(b, (k + 1) % 4); + } + } + + /// Skip sampling over pairs, as for `pauli_error_many`. + fn two_qubit_pauli_error_many(&mut self, pairs: &[(usize, usize)], p: [f64; 15]) { + let total: f64 = p.iter().sum(); + let mut i = self.next_error(0, total); + while i < pairs.len() { + let k = self.draw_given_event(&p, total); + let (a, b) = pairs[i]; + self.pauli(a, (k + 1) / 4); + self.pauli(b, (k + 1) % 4); + i = self.next_error(i + 1, total); + } + } +} + +/// Stim's `DEPOLARIZE1(p)`: each of `X`, `Y`, `Z` with probability `p/3`. +impl Depolarizing for GeneralizedTableau { + fn depolarize1(&mut self, q: usize, p: f64) { + self.pauli_error(q, [p / 3.0; 3]); + } + + fn depolarize1_many(&mut self, targets: &[usize], p: f64) { + self.pauli_error_many(targets, [p / 3.0; 3]); + } +} + +/// Stim's `DEPOLARIZE2(p)`: each of the 15 non-identity Paulis with +/// probability `p/15`. +impl Depolarizing2 for GeneralizedTableau { + fn depolarize2(&mut self, a: usize, b: usize, p: f64) { + self.two_qubit_pauli_error(a, b, [p / 15.0; 15]); + } + + fn depolarize2_many(&mut self, pairs: &[(usize, usize)], p: f64) { + self.two_qubit_pauli_error_many(pairs, [p / 15.0; 15]); + } +} + +#[cfg(test)] +mod tests { + use ppvm_traits_2::Measure; + + use super::*; + use crate::{ActiveDormant, DenseState}; + + type Sim = GeneralizedTableau>; + + /// The `(x, z)` bits of the Pauli applied to each qubit of a fresh `n`-qubit + /// state by `channel`: X bits flip `|0⟩`, Z bits flip `|+⟩`. + fn applied(n: usize, seed: u64, channel: impl Fn(&mut Sim)) -> Vec<(bool, bool)> { + let (mut zero, mut plus) = (Sim::new_with_seed(n, seed), Sim::new_with_seed(n, seed)); + (0..n).for_each(|q| plus.h(q)); + channel(&mut zero); + channel(&mut plus); + (0..n) + .map(|q| { + plus.h(q); + (zero.measure(q).unwrap(), plus.measure(q).unwrap()) + }) + .collect() + } + + fn bits(name: char) -> (bool, bool) { + match name { + 'I' => (false, false), + 'X' => (true, false), + 'Y' => (true, true), + _ => (false, true), + } + } + + /// With all probability on one entry, exactly that Pauli is applied, in + /// the order the traits document. + #[test] + fn one_hot_channels_apply_the_documented_pauli() { + for (k, name) in "XYZ".chars().enumerate() { + let mut p = [0.0; 3]; + p[k] = 1.0; + assert_eq!(applied(1, 0, |s| s.pauli_error(0, p)), [bits(name)]); + } + let order = "IX IY IZ XI XX XY XZ YI YX YY YZ ZI ZX ZY ZZ"; + for (k, pair) in order.split(' ').enumerate() { + let mut p = [0.0; 15]; + p[k] = 1.0; + let names: Vec = pair.chars().collect(); + assert_eq!( + applied(2, 0, |s| s.two_qubit_pauli_error(0, 1, p)), + [bits(names[0]), bits(names[1])], + "{pair}" + ); + } + } + + /// Flip frequencies on `|0…0⟩` match the channels: `DEPOLARIZE1(p)` flips + /// with `2p/3` (X, Y), `DEPOLARIZE2(p)` flips a given qubit with `8p/15` + /// and both with `4p/15`. + #[test] + fn depolarizing_flip_rates() { + let (p, shots) = (0.3, 20_000); + let within = |count: usize, rate: f64| { + let sigma = (rate * (1.0 - rate) / shots as f64).sqrt(); + ((count as f64 / shots as f64) - rate).abs() < 5.0 * sigma + }; + let mut flips = 0; + for seed in 0..shots { + let mut s = Sim::new_with_seed(1, seed as u64); + s.depolarize1(0, p); + flips += usize::from(s.measure(0).unwrap()); + } + assert!(within(flips, 2.0 * p / 3.0), "{flips} of {shots}"); + let (mut first, mut both) = (0, 0); + for seed in 0..shots { + let mut s = Sim::new_with_seed(2, seed as u64); + s.depolarize2(0, 1, p); + let (a, b) = (s.measure(0).unwrap(), s.measure(1).unwrap()); + first += usize::from(a); + both += usize::from(a && b); + } + assert!(within(first, 8.0 * p / 15.0), "{first} of {shots}"); + assert!(within(both, 4.0 * p / 15.0), "{both} of {shots}"); + } + + /// Batched channels act on each target independently with the channel's + /// rates: per Pauli, at either end of the batch, and on neighbouring pairs. + #[test] + fn batched_channels_match_independent_rates() { + let (n, shots, p) = (400, 100, 0.06); + let targets: Vec = (0..n).collect(); + let samples = |count: usize| (count * shots) as f64; + let within = |hits: usize, trials: f64, rate: f64| { + let sigma = (rate * (1.0 - rate) / trials).sqrt(); + ((hits as f64 / trials) - rate).abs() <= 5.0 * sigma + }; + let channels: [(&str, [f64; 3], fn(&mut Sim, &[usize], f64)); 4] = [ + ("X", [p, 0.0, 0.0], |s, t, p| s.x_error_many(t, p)), + ("Y", [0.0, p, 0.0], |s, t, p| s.y_error_many(t, p)), + ("Z", [0.0, 0.0, p], |s, t, p| s.z_error_many(t, p)), + ("DEPOLARIZE1", [p / 3.0; 3], |s, t, p| { + s.depolarize1_many(t, p) + }), + ]; + for (name, rates, channel) in channels { + let (mut per_pauli, mut ends, mut pairs) = ([0; 3], [0; 2], 0); + for seed in 0..shots { + let got = applied(n, seed as u64, |s| channel(s, &targets, p)); + let hit: Vec = got.iter().map(|&b| b != bits('I')).collect(); + for b in &got { + if let Some(k) = "XYZ".chars().position(|c| bits(c) == *b) { + per_pauli[k] += 1; + } + } + ends[0] += hit[..n / 10].iter().filter(|&&h| h).count(); + ends[1] += hit[n - n / 10..].iter().filter(|&&h| h).count(); + pairs += hit.windows(2).filter(|w| w[0] && w[1]).count(); + } + for k in 0..3 { + assert!( + within(per_pauli[k], samples(n), rates[k]), + "{name}: {per_pauli:?}" + ); + } + for end in ends { + assert!(within(end, samples(n / 10), p), "{name}: ends {ends:?}"); + } + assert!( + within(pairs, samples(n - 1), p * p), + "{name}: pairs {pairs}" + ); + } + } + + /// `p = 0` never applies the Pauli, `p = 1` applies it to every target. + #[test] + fn batched_channels_at_zero_and_one() { + let targets: Vec = (0..50).collect(); + let none = applied(50, 0, |s| s.x_error_many(&targets, 0.0)); + assert!(none.iter().all(|&b| b == bits('I'))); + let all = applied(50, 0, |s| s.x_error_many(&targets, 1.0)); + assert!(all.iter().all(|&b| b == bits('X'))); + } + + /// Batched two-qubit channels act on each pair independently: each of the + /// 15 Paulis at its rate (all distinct, so a mixed-up order shows), at + /// either end of the batch, and on neighbouring pairs. + #[test] + fn batched_two_qubit_channels_match_independent_rates() { + let (n, shots) = (400, 100); + let pairs: Vec<(usize, usize)> = (0..n / 2).map(|i| (2 * i, 2 * i + 1)).collect(); + let rates: [f64; 15] = std::array::from_fn(|k| 0.0005 * (k + 1) as f64); + let total: f64 = rates.iter().sum(); + let order: Vec<(bool, bool, bool, bool)> = "IX IY IZ XI XX XY XZ YI YX YY YZ ZI ZX ZY ZZ" + .split(' ') + .map(|pair| { + let c: Vec = pair.chars().collect(); + let ((xa, za), (xb, zb)) = (bits(c[0]), bits(c[1])); + (xa, za, xb, zb) + }) + .collect(); + let samples = |count: usize| (count * shots) as f64; + let within = |hits: usize, trials: f64, rate: f64| { + let sigma = (rate * (1.0 - rate) / trials).sqrt(); + ((hits as f64 / trials) - rate).abs() <= 5.0 * sigma + }; + let channels: [(&str, [f64; 15], f64, fn(&mut Sim, &[(usize, usize)])); 2] = [ + ("PAULI_CHANNEL_2", rates, total, |s, t| { + s.two_qubit_pauli_error_many(t, std::array::from_fn(|k| 0.0005 * (k + 1) as f64)) + }), + ("DEPOLARIZE2", [0.06 / 15.0; 15], 0.06, |s, t| { + s.depolarize2_many(t, 0.06) + }), + ]; + for (name, rates, total, channel) in channels { + let (mut per_pauli, mut ends, mut both) = ([0; 15], [0; 2], 0); + let tenth = pairs.len() / 10; + for seed in 0..shots { + let got = applied(n, seed as u64, |s| channel(s, &pairs)); + let kinds: Vec> = got + .chunks(2) + .map(|q| { + order + .iter() + .position(|&o| o == (q[0].0, q[0].1, q[1].0, q[1].1)) + }) + .collect(); + for k in kinds.iter().flatten() { + per_pauli[*k] += 1; + } + let hit: Vec = kinds.iter().map(Option::is_some).collect(); + ends[0] += hit[..tenth].iter().filter(|&&h| h).count(); + ends[1] += hit[hit.len() - tenth..].iter().filter(|&&h| h).count(); + both += hit.windows(2).filter(|w| w[0] && w[1]).count(); + } + for k in 0..15 { + assert!( + within(per_pauli[k], samples(pairs.len()), rates[k]), + "{name}: {per_pauli:?}" + ); + } + for end in ends { + assert!(within(end, samples(tenth), total), "{name}: ends {ends:?}"); + } + assert!( + within(both, samples(pairs.len() - 1), total * total), + "{name}: both {both}" + ); + } + } +} diff --git a/crates/ppvm-tableau-2/src/generalized_tableau/status.rs b/crates/ppvm-tableau-2/src/generalized_tableau/status.rs new file mode 100644 index 000000000..8f8d43142 --- /dev/null +++ b/crates/ppvm-tableau-2/src/generalized_tableau/status.rs @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +/// A qubit relative to the computational subspace. Lost and leaked qubits are +/// inactive: gates skip them. Measuring a lost qubit gives `None`, a leaked +/// one its pinned bit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum QubitStatus { + #[default] + Live, + Lost, + Leaked, +} + +impl QubitStatus { + pub(super) fn is_inactive(self) -> bool { + self != QubitStatus::Live + } +} diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/bitword.rs b/crates/ppvm-tableau-2/src/inverse_tableau/bitword.rs new file mode 100644 index 000000000..4deb980e5 --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/bitword.rs @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The storage word and the only code that knows its width. Everything else +//! touches words through these items and `Bits`, so a wider word can be tried +//! by changing the alias. + +/// Storage word. Swap to benchmark other widths. +pub(super) type BitWord = u64; +pub(super) const BITWORD_BITS: usize = BitWord::BITS as usize; +pub(super) const ZERO: BitWord = 0; +/// The highest bit of a word. +pub(super) const TOP_BIT: BitWord = 1 << (BITWORD_BITS - 1); + +/// Bit `i` of a packed bit string. +#[inline(always)] +pub(super) fn get_bit(words: &[BitWord], i: usize) -> bool { + (words[i / BITWORD_BITS] >> (i % BITWORD_BITS)) & 1 == 1 +} + +#[inline(always)] +pub(super) fn flip_bit(words: &mut [BitWord], i: usize) { + words[i / BITWORD_BITS] ^= 1 << (i % BITWORD_BITS); +} + +/// Word index and mask of bit `i`. +#[inline(always)] +pub(super) fn bit_position(i: usize) -> (usize, BitWord) { + (i / BITWORD_BITS, 1 << (i % BITWORD_BITS)) +} + +/// All ones if `b`, else zero (for branch-free masked updates). +#[inline(always)] +pub(super) fn mask_if(b: bool) -> BitWord { + ZERO.wrapping_sub(BitWord::from(b)) +} + +/// Indices of the set bits of a packed bit string, ascending. +pub(super) fn set_bits(words: &[BitWord]) -> impl Iterator + '_ { + set_bits_of(words.iter().copied()) +} + +/// [`set_bits`] over words computed on the fly (e.g. masked). +pub(super) fn set_bits_of(words: impl Iterator) -> impl Iterator { + words.enumerate().flat_map(|(w, word)| { + let mut rest = word; + std::iter::from_fn(move || { + (rest != ZERO).then(|| { + let b = rest.trailing_zeros() as usize; + rest &= rest - 1; + w * BITWORD_BITS + b + }) + }) + }) +} + +/// Column blocks transposed together by [`transpose_64x64`]. +pub(super) const LANES: usize = 4; + +/// Transpose [`LANES`] independent 64 × 64 bit matrices in place: lane `l` of +/// word `i` is word `i` of matrix `l`, and bit `j` of word `i` swaps with bit +/// `i` of word `j` in each. Running every step on all lanes lets the compiler +/// vectorize across matrices. Width-specific (64-bit words). +#[inline(always)] +pub(super) fn transpose_64x64(a: &mut [[BitWord; LANES]; 64]) { + const PASSES: [(BitWord, usize); 6] = [ + (0x5555_5555_5555_5555, 1), + (0x3333_3333_3333_3333, 2), + (0x0F0F_0F0F_0F0F_0F0F, 4), + (0x00FF_00FF_00FF_00FF, 8), + (0x0000_FFFF_0000_FFFF, 16), + (0x0000_0000_FFFF_FFFF, 32), + ]; + for (mask, shift) in PASSES { + for base in (0..64).step_by(2 * shift) { + for k in base..base + shift { + let (x, y) = (a[k], a[k + shift]); + for l in 0..LANES { + a[k][l] = (x[l] & mask) | ((y[l] & mask) << shift); + a[k + shift][l] = ((x[l] & !mask) >> shift) | (y[l] & !mask); + } + } + } + } +} diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/data.rs b/crates/ppvm-tableau-2/src/inverse_tableau/data.rs new file mode 100644 index 000000000..5a463506d --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/data.rs @@ -0,0 +1,249 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The tableau's storage: rows, signs, and where rows sit in the arena. + +use super::bitword::{ + BITWORD_BITS, BitWord, TOP_BIT, ZERO, bit_position, flip_bit, get_bit, mask_if, set_bits, + set_bits_of, +}; +use super::view::QubitMask; + +/// The inverse tableau of an `n`-qubit Clifford. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InverseTableau { + pub(super) n: usize, + /// Words per row and plane: `n.div_ceil(BITWORD_BITS)`. + pub(super) stride: usize, + /// X and Z words of all `2n` rows, arranged by `offsets`. + pub(super) words: Vec, + /// Bit `r` is the sign of row `r` (set = −). + pub(super) signs: Vec, +} + +// NOTE: we could impl Word for RowRef to make it a true PauliWord if we ever need it +/// A borrowed row: its X words, Z words and sign. +#[derive(Clone, Copy, Debug)] +pub struct RowRef<'a> { + pub x: &'a [BitWord], + pub z: &'a [BitWord], + pub negative: bool, +} + +impl<'a> RowRef<'a> { + /// X bit of the row at qubit `q`. + pub fn x_bit(&self, q: usize) -> bool { + get_bit(self.x, q) + } + + /// Z bit of the row at qubit `q`. + pub fn z_bit(&self, q: usize) -> bool { + get_bit(self.z, q) + } + + /// Qubits where the row has an X or Y, ascending. + pub fn x_support(&self) -> impl Iterator + 'a { + set_bits(self.x) + } + + /// Qubits outside `mask` where the row has an X or Y, ascending. + pub fn x_outside(&self, mask: &'a QubitMask) -> impl Iterator + 'a { + set_bits_of(self.x.iter().zip(&mask.words).map(|(&x, &m)| x & !m)) + } + + /// Qubits in `mask` where the row has a Z or Y, ascending. + pub fn z_inside(&self, mask: &'a QubitMask) -> impl Iterator + 'a { + set_bits_of(self.z.iter().zip(&mask.words).map(|(&z, &m)| z & m)) + } +} + +impl InverseTableau { + /// The identity Clifford, i.e. the state `|0…0⟩`: `ix_q = X_q`, `iz_q = Z_q`. + pub fn new(n: usize) -> Self { + let stride = n.div_ceil(BITWORD_BITS); + let mut t = Self { + n, + stride, + words: vec![ZERO; 4 * n * stride], + signs: vec![ZERO; (2 * n).div_ceil(BITWORD_BITS)], + }; + for q in 0..n { + let (ix, iz) = (t.x_at(q), t.z_at(n + q)); + flip_bit(&mut t.words[ix..], q); + flip_bit(&mut t.words[iz..], q); + } + t + } + + pub fn num_qubits(&self) -> usize { + self.n + } + + /// Row `ix_q = C⁻¹ X_q C`. + pub fn ix(&self, q: usize) -> RowRef<'_> { + assert!(q < self.n, "qubit {q} out of range"); + self.row(q) + } + + /// Row `iz_q = C⁻¹ Z_q C`. + pub fn iz(&self, q: usize) -> RowRef<'_> { + assert!(q < self.n, "qubit {q} out of range"); + self.row(self.n + q) + } + + pub(super) fn row(&self, r: usize) -> RowRef<'_> { + let (x, z) = (self.x_at(r), self.z_at(r)); + RowRef { + x: &self.words[x..x + self.stride], + z: &self.words[z..z + self.stride], + negative: self.negative(r), + } + } + + /// Whether row `r` has sign `−`. + #[inline(always)] + pub(super) fn negative(&self, r: usize) -> bool { + get_bit(&self.signs, r) + } + + pub(super) fn flip_sign(&mut self, r: usize) { + flip_bit(&mut self.signs, r); + } + + // Arrangement: blocks by row kind, ix-X, ix-Z, iz-X, iz-Z (#204's order). + // Row r is row i = r % n of kind r / n (0 for ix, 1 for iz). + #[inline(always)] + pub(super) fn offsets(n: usize, stride: usize, kind: usize, i: usize) -> (usize, usize) { + ( + ((2 * kind) * n + i) * stride, + ((2 * kind + 1) * n + i) * stride, + ) + } + + /// The rows of `qubits` in generator order: `ix_q`, `iz_q` per qubit. `M` + /// is twice the number of qubits. + #[inline(always)] + pub(super) fn qubit_rows(&self, qubits: &[usize]) -> [usize; M] { + let mut rows = [0; M]; + for (k, &q) in qubits.iter().enumerate() { + rows[2 * k] = q; + rows[2 * k + 1] = self.n + q; + } + rows + } + + /// The X words and the Z words of the rows of distinct qubits, in the + /// order of [`qubit_rows`](Self::qubit_rows), mutably. + /// + /// Panics unless every qubit is in range and no qubit repeats: distinct + /// qubits own distinct rows, which makes the ranges disjoint, so this is + /// the one place that checks it. + #[inline(always)] + pub(super) fn qubit_rows_mut( + &mut self, + qubits: &[usize], + ) -> ([&mut [BitWord]; M], [&mut [BitWord]; M]) { + assert_eq!(M, 2 * qubits.len()); + for (i, &q) in qubits.iter().enumerate() { + assert!(q < self.n, "qubit {q} out of range"); + assert!(!qubits[..i].contains(&q), "qubit {q} repeated"); + } + let rows: [usize; M] = self.qubit_rows(qubits); + let (xs, zs) = (rows.map(|r| self.x_at(r)), rows.map(|r| self.z_at(r))); + let (stride, words) = (self.stride, self.words.as_mut_ptr()); + // SAFETY: distinct qubits in range own distinct rows, whose + // `stride`-word ranges of `words` are disjoint; the slices borrow + // `self` mutably for their lifetime. + unsafe { + ( + xs.map(|x| std::slice::from_raw_parts_mut(words.add(x), stride)), + zs.map(|z| std::slice::from_raw_parts_mut(words.add(z), stride)), + ) + } + } + + /// Kind and index of row `r < 2n`, without dividing. + #[inline(always)] + fn kind_and_index(&self, r: usize) -> (usize, usize) { + let kind = usize::from(r >= self.n); + (kind, r - kind * self.n) + } + + #[inline(always)] + pub(super) fn x_at(&self, r: usize) -> usize { + let (kind, i) = self.kind_and_index(r); + Self::offsets(self.n, self.stride, kind, i).0 + } + + #[inline(always)] + pub(super) fn z_at(&self, r: usize) -> usize { + let (kind, i) = self.kind_and_index(r); + Self::offsets(self.n, self.stride, kind, i).1 + } + + /// Visit every row in order with its X words and Z words; `f` returns + /// whether the row's sign flips. Signs are updated a word (64 rows) at a + /// time. Walks the blocks of `offsets` directly: rows of one kind are + /// `stride` words apart. + #[inline(always)] + pub(super) fn for_each_row( + &mut self, + mut f: impl FnMut(&mut [BitWord], &mut [BitWord]) -> bool, + ) { + let (n, stride) = (self.n, self.stride); + if n == 0 { + return; + } + debug_assert_eq!( + Self::offsets(n, stride, 1, 0), + (2 * n * stride, 3 * n * stride) + ); + let (ix, iz) = self.words.split_at_mut(2 * n * stride); + let (ix_x, ix_z) = ix.split_at_mut(n * stride); + let (iz_x, iz_z) = iz.split_at_mut(n * stride); + let (mut flips, mut r) = (ZERO, 0); + for (xs, zs) in [(ix_x, ix_z), (iz_x, iz_z)] { + for (x, z) in xs.chunks_exact_mut(stride).zip(zs.chunks_exact_mut(stride)) { + let (sw, sm) = bit_position(r); + flips |= sm & mask_if(f(x, z)); + if sm == TOP_BIT { + self.signs[sw] ^= flips; + flips = ZERO; + } + r += 1; + } + } + if !r.is_multiple_of(BITWORD_BITS) { + self.signs[r / BITWORD_BITS] ^= flips; + } + } +} + +#[cfg(test)] +mod tests { + use super::super::test_support::*; + use super::*; + + #[test] + fn identity_rows_are_single_paulis() { + for n in SIZES { + let t = InverseTableau::new(n); + for q in 0..n { + for j in 0..n { + assert_eq!(t.ix(q).x_bit(j), j == q); + assert!(!t.ix(q).z_bit(j)); + assert!(!t.iz(q).x_bit(j)); + assert_eq!(t.iz(q).z_bit(j), j == q); + } + assert!(!t.ix(q).negative && !t.iz(q).negative); + } + } + } + + #[test] + fn identity_has_canonical_commutation() { + for n in SIZES { + assert_canonical_commutation(&InverseTableau::new(n)); + } + } +} diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/measure.rs b/crates/ppvm-tableau-2/src/inverse_tableau/measure.rs new file mode 100644 index 000000000..0fba7d91a --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/measure.rs @@ -0,0 +1,311 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Z measurement and reset of the stabilizer state `C |0…0⟩` (no active +//! qubits). + +use ppvm_pauli_kernels::{Bits, heisenberg}; +use ppvm_traits_2::Clifford; + +use super::bitword::{BitWord, ZERO, set_bits}; +use super::transposed::TransposedTableau; +use super::{InverseTableau, QubitMask}; + +/// Random targets a batch needs before `measure_many` transposes. Measured at +/// 118 qubits: a batch of ~48 small collapses (the d=7 surface code) is faster +/// strided, a batch of 118 is 2.8× faster transposed. The break-even should +/// grow with `n` (transposing costs ~n²/64 words, a strided collapse ~n rows); +/// retune with other sizes. +const TRANSPOSE_THRESHOLD: usize = 64; + +/// What measuring needs from a tableau layout: row `iz_q` and the collapse. +trait Collapse { + /// Columns where row `iz_q` has an X bit, ascending, into `out`. + fn iz_x_support(&self, q: usize, out: &mut Vec); + fn iz_z_bit(&self, q: usize, c: usize) -> bool; + fn iz_negative(&self, q: usize) -> bool; + /// `C ← C·V` with `V = CX(p, targets…) · last(p)`, where `last` is + /// [`collapse_last`] with these flags. + fn collapse(&mut self, pivot: usize, targets: &[usize], has_y: bool, fix_sign: bool); +} + +/// The collapse's final gate on the pivot: `S` if it holds a Y, then `H`, then +/// `X` if the sign calls for it. Generic so both layouts run the same rules. +#[inline(always)] +fn collapse_last(has_y: bool, fix_sign: bool, x: B, z: B) -> ([B; 2], B) { + // `x & !x` is the zero flip (`Bits` has no zero constant). + let ([x, z], f1) = if has_y { + heisenberg::s(x, z) + } else { + ([x, z], x & !x) + }; + let ([x, z], f2) = heisenberg::h(x, z); + let ([x, z], f3) = if fix_sign { + heisenberg::x(x, z) + } else { + ([x, z], x & !x) + }; + ([x, z], f1 ^ f2 ^ f3) +} + +/// Measure `Z_q` on `t` and collapse; `targets` is scratch. +/// +/// Measuring `Z_q` is measuring `O = C⁻¹ Z_q C` (row `iz_q`) on `|0…0⟩`: +/// +/// - **No X in `O`:** `O` is a signed Z string, so the outcome is its sign. +/// - **X on some virtual qubits:** 50/50. Pick the lowest, `p`, as pivot +/// and change basis so that `O` becomes `±Z_p`: `CX(p, v)` clears every +/// other X (trivial on the state, since `p` is in `|0⟩`), leaving +/// `O = s · X_p · Z…` or `s · Y_p · Z…`. The projected state on `p` is +/// `|0⟩ ± |1⟩` (or `|0⟩ ± i|1⟩`), which `C ← C·H` (or `C·S·H`) and an +/// `X` when the sign calls for it map back to `|0⟩`. +fn measure_on( + t: &mut T, + q: usize, + coin: impl FnOnce() -> bool, + targets: &mut Vec, +) -> bool { + targets.clear(); + t.iz_x_support(q, targets); + if targets.is_empty() { + return t.iz_negative(q); + } + let pivot = targets.remove(0); + // The CXs reduce O to s · X_p or s · Y_p (times Z's); find which, and s, + // from row iz_q alone before changing the tableau. + let (mut pivot_bits, mut negative) = ([true, t.iz_z_bit(q, pivot)], t.iz_negative(q)); + for &v in targets.iter() { + let ([px, pz, _, _], flip) = + heisenberg::cnot([pivot_bits[0], pivot_bits[1], true, t.iz_z_bit(q, v)]); + pivot_bits = [px, pz]; + negative ^= flip; + } + let (has_y, outcome) = (pivot_bits[1], coin()); + t.collapse(pivot, targets, has_y, outcome != negative); + outcome +} + +impl Collapse for InverseTableau { + fn iz_x_support(&self, q: usize, out: &mut Vec) { + out.extend(set_bits(self.iz(q).x)); + } + + fn iz_z_bit(&self, q: usize, c: usize) -> bool { + self.iz(q).z_bit(c) + } + + fn iz_negative(&self, q: usize) -> bool { + self.iz(q).negative + } + + fn collapse(&mut self, pivot: usize, targets: &[usize], has_y: bool, fix_sign: bool) { + self.fan_out(pivot, targets, &[], |x, z| { + collapse_last(has_y, fix_sign, x, z) + }); + } +} + +impl Collapse for TransposedTableau { + fn iz_x_support(&self, q: usize, out: &mut Vec) { + self.x_support(1, q, out); + } + + fn iz_z_bit(&self, q: usize, c: usize) -> bool { + self.bits(1, q, c)[1] + } + + fn iz_negative(&self, q: usize) -> bool { + self.negative(1, q) + } + + fn collapse(&mut self, pivot: usize, targets: &[usize], has_y: bool, fix_sign: bool) { + self.fan_out(pivot, targets, |x: BitWord, z: BitWord| { + collapse_last(has_y, fix_sign, x, z) + }); + } +} + +impl InverseTableau { + /// Measure `Z_q` on `C |0…0⟩` and collapse; returns the outcome (`true` + /// for `|1⟩`). `coin` is called only if the outcome is random. See + /// [`measure_on`] for the method. + pub fn measure(&mut self, q: usize, coin: impl FnOnce() -> bool) -> bool { + measure_on(self, q, coin, &mut Vec::new()) + } + + /// Measure `Z_q` for each of `qubits` in order, collapsing after each, and + /// write the outcomes to `outcomes`. `coin` is called once per random + /// outcome. Same result as calling [`measure`](Self::measure) in order. + /// + /// With at least `TRANSPOSE_THRESHOLD` random targets, the batch runs on a + /// column-major copy: two transposes, then each collapse a few words per + /// 64 rows instead of one bit per row. + pub fn measure_many( + &mut self, + qubits: &[usize], + coin: impl FnMut() -> bool, + outcomes: &mut [bool], + ) { + // Count random targets only as far as the decision needs. + let transpose = qubits.len() >= TRANSPOSE_THRESHOLD + && qubits + .iter() + .filter(|&&q| self.iz(q).x.iter().any(|&w| w != ZERO)) + .nth(TRANSPOSE_THRESHOLD - 1) + .is_some(); + self.measure_many_with(qubits, coin, outcomes, transpose); + } + + fn measure_many_with( + &mut self, + qubits: &[usize], + mut coin: impl FnMut() -> bool, + outcomes: &mut [bool], + transpose: bool, + ) { + assert_eq!(qubits.len(), outcomes.len()); + let mut targets = Vec::new(); + if transpose { + let mut columns = TransposedTableau::from_rows(self); + for (&q, outcome) in qubits.iter().zip(outcomes) { + *outcome = measure_on(&mut columns, q, &mut coin, &mut targets); + } + columns.write_rows(self); + } else { + for (&q, outcome) in qubits.iter().zip(outcomes) { + *outcome = measure_on(self, q, &mut coin, &mut targets); + } + } + } + + /// Collapse `O = C⁻¹ Z_q C` onto outcome `m` on `|χ⟩ = |φ⟩ ⊗ |0…0⟩`, where + /// `φ` lives on the `active` qubits and `O` has an X or Y on a dormant one. + /// + /// Stim's collapse with the pivot `p` restricted to dormant qubits: `p` is + /// the lowest of them, `CX(p, v)` clears every other X (active ones too), + /// and `CZ(p, c)` clears the Z on every active `c`. Both are trivial on + /// `χ`, since `p` is in `|0⟩`, so `φ` is unchanged. What is left is + /// `±X_p` or `±Y_p` times Z's on dormant qubits, which act as `+1`, so the + /// final gates are those of [`measure`](Self::measure). + pub fn collapse_dormant(&mut self, q: usize, active: &QubitMask, m: bool) { + let o = self.iz(q); + let pivot = o.x_outside(active).next().expect("no dormant X in O"); + let cx_targets: Vec = o.x_support().filter(|&v| v != pivot).collect(); + let cz_targets: Vec = o.z_inside(active).collect(); + // Pivot bits and sign of O after the CXs and CZs, from row iz_q alone. + // The CXs leave the other qubits' Z bits and clear their X bits. + let (mut pivot_bits, mut negative) = ([true, o.z_bit(pivot)], o.negative); + for &v in &cx_targets { + let ([px, pz, _, _], flip) = + heisenberg::cnot([pivot_bits[0], pivot_bits[1], true, o.z_bit(v)]); + pivot_bits = [px, pz]; + negative ^= flip; + } + for _ in &cz_targets { + let ([px, pz, _, _], flip) = + heisenberg::cz([pivot_bits[0], pivot_bits[1], false, true]); + pivot_bits = [px, pz]; + negative ^= flip; + } + let has_y = pivot_bits[1]; + self.fan_out(pivot, &cx_targets, &cz_targets, |x, z| { + collapse_last(has_y, m != negative, x, z) + }); + } + + /// Reset qubit `q` to `|0⟩`: measure it, then flip it if it was `|1⟩`. + pub fn reset(&mut self, q: usize, coin: impl FnOnce() -> bool) { + if self.measure(q, coin) { + self.x(q); + } + } +} + +#[cfg(test)] +mod tests { + use super::super::test_support::*; + use super::*; + + /// After a measurement, measuring again is deterministic and repeats it. + #[test] + fn measuring_again_repeats_the_outcome() { + for (i, n) in SIZES.into_iter().enumerate() { + let mut t = InverseTableau::new(n); + random_circuit(n, 200, 0x3e5 + i as u64) + .into_iter() + .for_each(|g| apply(&mut t, g)); + for q in 0..n { + let first = t.measure(q, || q % 2 == 0); + let again = t.measure(q, || panic!("second measurement is random")); + assert_eq!(first, again, "n = {n}, q = {q}"); + } + } + } + + #[test] + fn measurement_preserves_commutation() { + for (i, n) in [1, 2, 7, 65].into_iter().enumerate() { + let mut t = InverseTableau::new(n); + for (k, gate) in random_circuit(n, 100, 0x5ca1 + i as u64) + .into_iter() + .enumerate() + { + apply(&mut t, gate); + t.measure(k % n, || k % 3 == 0); + assert_canonical_commutation(&t); + } + } + } + + /// `measure_many` equals measuring one qubit at a time with the same coins, + /// on both the row-major and the column-major path. + #[test] + fn measure_many_matches_measure() { + for (i, n) in SIZES.into_iter().enumerate() { + let mut start = InverseTableau::new(n); + random_circuit(n, 150, 0xba7c + i as u64) + .into_iter() + .for_each(|g| apply(&mut start, g)); + // Every qubit, then a repeat, so later targets see earlier collapses. + let qubits: Vec = (0..n).rev().chain([0]).collect(); + let coins = |seed: u64| { + let mut s = seed | 1; + move || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + s & 1 == 1 + } + }; + let mut single = start.clone(); + let mut coin = coins(7); + let mut expected = Vec::new(); + // `&mut coin` is needed: `coin` is reused across iterations. + #[allow(clippy::needless_borrows_for_generic_args)] + for &q in &qubits { + expected.push(single.measure(q, &mut coin)); + } + for transpose in [false, true] { + let mut batched = start.clone(); + let mut outcomes = vec![false; qubits.len()]; + batched.measure_many_with(&qubits, coins(7), &mut outcomes, transpose); + assert_eq!(outcomes, expected, "n = {n}, transpose = {transpose}"); + assert_eq!(batched, single, "n = {n}, transpose = {transpose}"); + } + } + } + + #[test] + fn reset_leaves_zero() { + for (i, n) in [1, 2, 7, 65].into_iter().enumerate() { + let mut t = InverseTableau::new(n); + random_circuit(n, 100, 0x7e5e + i as u64) + .into_iter() + .for_each(|g| apply(&mut t, g)); + for q in 0..n { + t.reset(q, || true); + assert!(!t.measure(q, || panic!("reset qubit is random"))); + } + } + } +} diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/mod.rs b/crates/ppvm-tableau-2/src/inverse_tableau/mod.rs new file mode 100644 index 000000000..a9f8d024b --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/mod.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The inverse stabilizer tableau `C⁻¹` of a Clifford `C`. +//! +//! Row `ix_q` is `C⁻¹ X_q C` and row `iz_q` is `C⁻¹ Z_q C`, each stored as +//! packed X and Z bits plus one sign bit (rows are Hermitian, so their phase +//! is ±1). Rows are indexed `ix_q = q`, `iz_q = n + q`. +//! +//! - `data`: the storage, row reads, and where rows sit in the arena. +//! - `bitword`: the storage word; the only code that knows its width. +//! - `physical_gates`: physical gates `C ← G·C`, which mix rows. +//! - `virtual_gates`: changes of basis `C ← C·V`, which rewrite columns. +//! - `measure`: Z measurement and reset of the stabilizer state. +//! - `transposed`: a column-major copy for batches of changes of basis. +//! - `view`: [`VirtualView`], the virtual side handed to a virtual state. +//! +//! Where rows sit in the arena is decided only in `data`: by `offsets` (used +//! by `x_at`, `z_at`) and by `for_each_row`, which walks the same blocks. + +mod bitword; +mod data; +mod measure; +mod physical_gates; +#[cfg(test)] +mod test_support; +mod transposed; +mod view; +mod virtual_gates; + +pub use data::{InverseTableau, RowRef}; +pub use view::{OwnedRow, QubitMask, VirtualView}; diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/physical_gates.rs b/crates/ppvm-tableau-2/src/inverse_tableau/physical_gates.rs new file mode 100644 index 000000000..8a7987292 --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/physical_gates.rs @@ -0,0 +1,333 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Physical gates, `C ← G·C`: they mix whole rows. + +use ppvm_pauli_kernels::{row_product, word_product}; +use ppvm_traits_2::{ApplyGateRule, CliffordBatch}; + +use super::InverseTableau; +use super::bitword::{BitWord, ZERO}; + +/// Where a gate sends one of its generators: `G† P G = (−1)^flip · P(factors)`. +/// +/// The generators are X then Z for each gate qubit; bit `j` of `factors` says +/// whether the Hermitian Pauli `P(factors)` contains generator `j`. Plain +/// integer masks, so that for a given gate everything below folds to constants. +#[derive(Clone, Copy)] +struct Image { + factors: u8, + flip: bool, +} + +impl Image { + fn new((bits, flip): ([bool; M], bool)) -> Self { + let mut factors = 0; + for (j, &b) in bits.iter().enumerate() { + factors |= u8::from(b) << j; + } + Self { factors, flip } + } + + fn has(&self, j: usize) -> bool { + self.factors >> j & 1 == 1 + } + + /// Whether generator `g` maps to itself up to sign, so its row keeps its bits. + fn keeps_bits(&self, g: usize) -> bool { + self.factors == 1 << g + } + + /// Whether row `g` becomes itself times rows that keep their bits (`changed` + /// marks the rows that do not), so it can be multiplied in place (CX, CZ, S, + /// √X and their inverses). + fn multiplies_in_place(&self, g: usize, changed: u8) -> bool { + self.has(g) && self.factors & !(1 << g) & changed == 0 + } + + /// Number of Y factors: an X and a Z on the same qubit. + fn y_count(&self) -> u32 { + (self.factors & self.factors >> 1 & 0b0101_0101).count_ones() + } + + /// One word of the product of the old rows in `factors`, and its phase. + #[inline(always)] + fn multiply(&self, old_words: &[[BitWord; 2]; M]) -> ([BitWord; 2], u32) { + let mut word = [ZERO; 2]; + let mut phase = 0u32; + for (j, old) in old_words.iter().enumerate() { + if self.has(j) { + let (product, k) = word_product(word[0], word[1], old[0], old[1]); + word = product; + phase = phase.wrapping_add(k); + } + } + (word, phase) + } +} + +/// Bit `g` set for each row the gate changes. +fn changed_rows(images: &[Image; M]) -> u8 { + let mut changed = 0; + for (g, image) in images.iter().enumerate() { + changed |= u8::from(!image.keeps_bits(g)) << g; + } + changed +} + +/// Rewrite row `g` (X words `x[g]`, Z words `z[g]`) as `C⁻¹ (G† P_g G) C`. +/// +/// Write the image as `(−1)^flip · i^#Y` times its generators in order (a Y is +/// `i·X·Z`). Conjugating by `C` turns each generator into its old row, so the +/// new row is the product of those old rows times `(−1)^flip · i^#Y`. For +/// example `S` sends `X ↦ −Y = −i·X·Z`, so `ix ← −i · ix · iz`, and keeps `Z`, +/// so `iz` stays. +/// +/// The product is taken site by site, so the new words at index `w` depend +/// only on the old words at `w`: each index is loaded, multiplied in registers +/// and stored once. `phases[g]` (a power of `i`) comes in with the image's own +/// factors and signs and collects each word's product phase. +#[inline(always)] +fn recombine( + x: [&mut [BitWord]; M], + z: [&mut [BitWord]; M], + images: &[Image; M], + phases: &mut [u32; M], +) { + let len = x[0].len(); + assert!(x.iter().chain(&z).all(|s| s.len() == len)); + for w in 0..len { + let old_words: [[BitWord; 2]; M] = std::array::from_fn(|j| [x[j][w], z[j][w]]); + for (g, image) in images.iter().enumerate() { + if image.keeps_bits(g) { + continue; + } + let ([new_x, new_z], phase) = image.multiply(&old_words); + x[g][w] = new_x; + z[g][w] = new_z; + phases[g] = phases[g].wrapping_add(phase); + } + } +} + +/// `(&mut v[g], &v[j])` for `g ≠ j`. +fn pair(v: &mut [T], g: usize, j: usize) -> (&mut T, &T) { + if g < j { + let (lo, hi) = v.split_at_mut(j); + (&mut lo[g], &hi[0]) + } else { + let (lo, hi) = v.split_at_mut(g); + (&mut hi[0], &lo[j]) + } +} + +/// The in-place path: each changed row `g` is multiplied by its other factors +/// with `row_product`, like Stim's `zs[t] *= zs[c]`. +/// +/// That computes `R_g · R_j …` with `R_g` first, while the image is a product +/// in generator order; moving `R_g` past an earlier factor costs `−1` when the +/// two anticommute, i.e. when they are the X and Z rows of one qubit. +#[inline(always)] +fn multiply_in_place( + mut x: [&mut [BitWord]; M], + mut z: [&mut [BitWord]; M], + images: &[Image; M], + phases: &mut [u32; M], +) { + for (g, image) in images.iter().enumerate() { + if image.keeps_bits(g) { + continue; + } + for j in 0..M { + if j == g || !image.has(j) { + continue; + } + let (dst_x, src_x) = pair(&mut x, g, j); + let (dst_z, src_z) = pair(&mut z, g, j); + let k = row_product(dst_x, dst_z, src_x, src_z); + let reorder = if j < g && j / 2 == g / 2 { 2 } else { 0 }; + phases[g] = phases[g].wrapping_add(u32::from(k) + reorder); + } + } +} + +impl InverseTableau { + /// Starting phase of each new row, as a power of `i`: one `i` per Y in the + /// image, `−1` for its flip and `−1` per negative old row it multiplies. + /// A row whose image contains the row itself leaves its own sign out: its + /// phase is then the *change* of its sign (see `set_signs`). + #[inline(always)] + fn initial_phases(&self, rows: [usize; M], images: &[Image; M]) -> [u32; M] { + let mut phases = [0; M]; + for (g, image) in images.iter().enumerate() { + phases[g] = image.y_count() + 2 * u32::from(image.flip); + for (j, &r) in rows.iter().enumerate() { + if j != g && image.has(j) && self.negative(r) { + phases[g] += 2; + } + } + } + phases + } + + /// Set each row's sign from its final phase (`i⁰ = +`, `i² = −`): relative + /// to its old sign when its image contains the row itself, else absolute. + #[inline(always)] + fn set_signs( + &mut self, + rows: [usize; M], + images: &[Image; M], + phases: [u32; M], + ) { + for (g, &r) in rows.iter().enumerate() { + debug_assert!(phases[g].is_multiple_of(2), "row is not Hermitian"); + let negative = phases[g] % 4 == 2; + if images[g].has(g) { + if negative { + self.flip_sign(r); + } + } else if self.negative(r) != negative { + self.flip_sign(r); + } + } + } + + /// Replace each row of `qubits` by its image's product of old rows: in place + /// when the pattern allows it, else with the fused pass. The choice depends + /// only on the images, which are constants for a given gate. + #[inline(always)] + fn rewrite_rows(&mut self, qubits: &[usize], images: &[Image; M]) { + let rows = self.qubit_rows(qubits); + let mut phases = self.initial_phases(rows, images); + let in_place = { + let changed = changed_rows(images); + let mut all = true; + for (g, image) in images.iter().enumerate() { + all &= changed >> g & 1 == 0 || image.multiplies_in_place(g, changed); + } + all + }; + let (x, z) = self.qubit_rows_mut(qubits); + if in_place { + multiply_in_place(x, z, images, &mut phases); + } else { + recombine(x, z, images, &mut phases); + } + self.set_signs(rows, images, phases); + } +} + +/// Physical gates, `C ← G·C`: the new row for generator `P` is `C⁻¹ (G† P G) C`, +/// so the rule evaluated on `P` names the old rows to multiply. +impl ApplyGateRule for InverseTableau { + type B = bool; + + fn apply1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + let images = [rule(true, false), rule(false, true)].map(Image::new); + self.rewrite_rows(&[q], &images); + } + + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([bool; 4]) -> ([bool; 4], bool)) { + let images = [ + rule([true, false, false, false]), + rule([false, true, false, false]), + rule([false, false, true, false]), + rule([false, false, false, true]), + ] + .map(Image::new); + self.rewrite_rows(&[a, b], &images); + } + + fn apply_sign1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + assert!(q < self.n, "qubit {q} out of range"); + let ((x_bits, x_flip), (z_bits, z_flip)) = (rule(true, false), rule(false, true)); + debug_assert!(x_bits == [true, false] && z_bits == [false, true]); + if x_flip { + self.flip_sign(q); + } + if z_flip { + self.flip_sign(self.n + q); + } + } +} + +/// The default loops are right here: gates on different qubits touch disjoint +/// rows, so a batch has no shared work to fuse. +impl CliffordBatch for InverseTableau {} + +#[cfg(test)] +mod tests { + use ppvm_pauli_word_2::PauliWord; + use ppvm_phased_pauli_word_2::Phased; + use ppvm_traits_2::{PauliBits, Phase}; + + use super::super::RowRef; + use super::super::test_support::*; + use super::*; + + type Reference = Phased>; + + /// `C⁻¹ P C` for `C = G_m ⋯ G_1`: propagate `P` through the gates in reverse. + fn heisenberg(n: usize, q: usize, z: bool, circuit: &[Gate]) -> Reference { + let mut word = PauliWord::new(n); + if z { + word.set_z_bit(q, true); + } else { + word.set_x_bit(q, true); + } + let mut p = Phased::new(word); + for &gate in circuit.iter().rev() { + apply(&mut p, gate); + } + p + } + + fn assert_row_eq(row: RowRef, expected: &Reference, n: usize) { + for j in 0..n { + assert_eq!(row.x_bit(j), expected.word().x_bit(j), "x bit {j}"); + assert_eq!(row.z_bit(j), expected.word().z_bit(j), "z bit {j}"); + } + let negative = match expected.phase() { + Phase::Pos1 => false, + Phase::Neg1 => true, + phase => panic!("non-Hermitian reference phase {phase:?}"), + }; + assert_eq!(row.negative, negative, "sign"); + } + + /// Rows must equal `C⁻¹ X_q C` / `C⁻¹ Z_q C` computed by Heisenberg + /// propagation of single Pauli words. + #[test] + fn physical_gates_match_heisenberg_propagation() { + for (i, n) in SIZES.into_iter().enumerate() { + let circuit = random_circuit(n, 200, 0x9e37_79b9 + i as u64); + let mut t = InverseTableau::new(n); + for &gate in &circuit { + apply(&mut t, gate); + } + for q in 0..n { + assert_row_eq(t.ix(q), &heisenberg(n, q, false, &circuit), n); + assert_row_eq(t.iz(q), &heisenberg(n, q, true, &circuit), n); + } + } + } + + #[test] + fn physical_gates_preserve_commutation() { + for (i, n) in [1, 2, 7, 65].into_iter().enumerate() { + let mut t = InverseTableau::new(n); + for gate in random_circuit(n, 100, 0x5eed + i as u64) { + apply(&mut t, gate); + assert_canonical_commutation(&t); + } + } + } + + /// A sign-only gate past the last qubit would flip another row's sign. + #[test] + #[should_panic(expected = "out of range")] + fn sign_gate_out_of_range_panics() { + use ppvm_traits_2::Clifford; + InverseTableau::new(4).z(5); + } +} diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/test_support.rs b/crates/ppvm-tableau-2/src/inverse_tableau/test_support.rs new file mode 100644 index 000000000..af5be0163 --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/test_support.rs @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Helpers shared by the tableau's unit tests. + +use ppvm_pauli_kernels::Bits; +use ppvm_traits_2::Clifford; + +use super::{InverseTableau, RowRef}; + +pub(super) const SIZES: [usize; 7] = [1, 2, 7, 63, 64, 65, 130]; + +/// Whether two rows anticommute: odd symplectic product. +fn anticommute(a: RowRef, b: RowRef) -> bool { + let mut parity = 0; + for i in 0..a.x.len() { + parity ^= ((a.x[i] & b.z[i]) ^ (a.z[i] & b.x[i])).popcount() & 1; + } + parity == 1 +} + +/// Conjugation preserves commutation: `ix_a`, `iz_b` anticommute iff `a == b`. +pub(super) fn assert_canonical_commutation(t: &InverseTableau) { + let n = t.num_qubits(); + for a in 0..n { + for b in 0..n { + assert_eq!(anticommute(t.ix(a), t.iz(b)), a == b); + assert!(!anticommute(t.ix(a), t.ix(b))); + assert!(!anticommute(t.iz(a), t.iz(b))); + } + } +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum Gate { + One(usize, usize), + Two(usize, usize, usize), +} + +/// `gate` as a physical gate (or on any `Clifford`). +pub(super) fn apply(t: &mut T, gate: Gate) { + match gate { + Gate::One(g, q) => match g { + 0 => t.x(q), + 1 => t.y(q), + 2 => t.z(q), + 3 => t.h(q), + 4 => t.s(q), + 5 => t.s_dag(q), + 6 => t.sqrt_x(q), + 7 => t.sqrt_x_dag(q), + 8 => t.sqrt_y(q), + _ => t.sqrt_y_dag(q), + }, + Gate::Two(g, a, b) => match g { + 0 => t.cnot(a, b), + 1 => t.cz(a, b), + _ => t.cy(a, b), + }, + } +} + +type Rule1 = fn(bool, bool) -> ([bool; 2], bool); +type Rule2 = fn([bool; 4]) -> ([bool; 4], bool); + +/// `gate` as a change of basis on virtual qubits, `C ← C·V`. +pub(super) fn change_basis(t: &mut InverseTableau, gate: Gate) { + use ppvm_pauli_kernels::heisenberg as rules; + let one: [Rule1; 10] = [ + rules::x, + rules::y, + rules::z, + rules::h, + rules::s, + rules::s_dag, + rules::sqrt_x, + rules::sqrt_x_dag, + rules::sqrt_y, + rules::sqrt_y_dag, + ]; + let two: [Rule2; 3] = [rules::cnot, rules::cz, rules::cy]; + match gate { + Gate::One(g, v) => t.change_basis1(v, one[g]), + Gate::Two(g, a, b) => t.change_basis2(a, b, two[g]), + } +} + +/// A random circuit from a xorshift seed. +pub(super) fn random_circuit(n: usize, len: usize, mut seed: u64) -> Vec { + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as usize + }; + (0..len) + .map(|_| { + if n < 2 || next() % 3 == 0 { + Gate::One(next() % 10, next() % n) + } else { + let a = next() % n; + let b = (a + 1 + next() % (n - 1)) % n; + Gate::Two(next() % 3, a, b) + } + }) + .collect() +} diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/transposed.rs b/crates/ppvm-tableau-2/src/inverse_tableau/transposed.rs new file mode 100644 index 000000000..f08cd88fc --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/transposed.rs @@ -0,0 +1,209 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! A column-major copy of the tableau, for batches of changes of basis. +//! +//! Column `c` (virtual qubit `c`) of a row block is `stride` contiguous words, +//! one bit per row, so a change of basis runs the gate rules on 64 rows per +//! word (`B = u64`) instead of one bit per row. Building the copy and writing +//! it back each cost a transpose, so it only pays for a batch. + +use ppvm_pauli_kernels::heisenberg; + +use super::InverseTableau; +use super::bitword::{BitWord, LANES, ZERO, bit_position, flip_bit, get_bit, transpose_64x64}; + +pub(super) struct TransposedTableau { + n: usize, + stride: usize, + /// `x[k][c * stride + w]`: X bits of column `c` for rows `64w..` of + /// block `k` (0: the `ix` rows, 1: the `iz` rows). + x: [Vec; 2], + z: [Vec; 2], + /// `signs[k]`: bit `i` is the sign of row `i` of block `k`. + signs: [Vec; 2], +} + +impl TransposedTableau { + /// The column-major copy of `t`. + pub(super) fn from_rows(t: &InverseTableau) -> Self { + let (n, stride) = (t.n, t.stride); + let empty = || [vec![ZERO; n * stride], vec![ZERO; n * stride]]; + let mut c = Self { + n, + stride, + x: empty(), + z: empty(), + signs: [vec![ZERO; stride], vec![ZERO; stride]], + }; + for k in 0..2 { + for plane in 0..2 { + let dst = if plane == 0 { &mut c.x[k] } else { &mut c.z[k] }; + for_each_block(stride, |rows, cols, lanes| { + let mut block = [[ZERO; LANES]; 64]; + for (r, words) in block.iter_mut().enumerate() { + let i = rows + r; + if i < n { + let (x, z) = InverseTableau::offsets(n, stride, k, i); + let at = if plane == 0 { x } else { z } + cols / 64; + // A loop: `copy_from_slice` (or a zip) of < 4 words calls `memmove`. + #[allow(clippy::manual_memcpy)] + for l in 0..lanes { + words[l] = t.words[at + l]; + } + } + } + transpose_64x64(&mut block); + for (j, words) in block.iter().enumerate() { + for (l, &word) in words[..lanes].iter().enumerate() { + let c = cols + 64 * l + j; + if c < n { + dst[c * stride + rows / 64] = word; + } + } + } + }); + } + for i in 0..n { + if t.negative(k * n + i) { + flip_bit(&mut c.signs[k], i); + } + } + } + c + } + + /// Write this copy back into the rows of `t`. + pub(super) fn write_rows(&self, t: &mut InverseTableau) { + let (n, stride) = (self.n, self.stride); + for k in 0..2 { + for plane in 0..2 { + let src = if plane == 0 { &self.x[k] } else { &self.z[k] }; + for_each_block(stride, |rows, cols, lanes| { + let mut block = [[ZERO; LANES]; 64]; + for (j, words) in block.iter_mut().enumerate() { + for (l, word) in words[..lanes].iter_mut().enumerate() { + let c = cols + 64 * l + j; + if c < n { + *word = src[c * stride + rows / 64]; + } + } + } + transpose_64x64(&mut block); + for (r, words) in block.iter().enumerate() { + let i = rows + r; + if i < n { + let (x, z) = InverseTableau::offsets(n, stride, k, i); + let at = if plane == 0 { x } else { z } + cols / 64; + #[allow(clippy::manual_memcpy)] + for l in 0..lanes { + t.words[at + l] = words[l]; + } + } + } + }); + } + for i in 0..n { + if t.negative(k * n + i) != get_bit(&self.signs[k], i) { + t.flip_sign(k * n + i); + } + } + } + } + + /// X and Z bits of row `i` of block `k` at column `c`. + pub(super) fn bits(&self, k: usize, i: usize, c: usize) -> [bool; 2] { + let w = c * self.stride; + [ + get_bit(&self.x[k][w..w + self.stride], i), + get_bit(&self.z[k][w..w + self.stride], i), + ] + } + + /// Columns where row `i` of block `k` has an X bit, ascending, into `out`: + /// word `i / 64` of each column, without touching the Z bits. + pub(super) fn x_support(&self, k: usize, i: usize, out: &mut Vec) { + let (w, mask) = bit_position(i); + let words = self.x[k][w..].iter().step_by(self.stride); + out.extend( + words + .enumerate() + .filter(|&(_, &word)| word & mask != ZERO) + .map(|(c, _)| c), + ); + } + + pub(super) fn negative(&self, k: usize, i: usize) -> bool { + get_bit(&self.signs[k], i) + } + + /// [`InverseTableau::fan_out`] without CZ targets, on columns: the rules + /// run on 64 rows per word. + pub(super) fn fan_out( + &mut self, + pivot: usize, + cx_targets: &[usize], + last: impl Fn(BitWord, BitWord) -> ([BitWord; 2], BitWord), + ) { + let s = self.stride; + for k in 0..2 { + let (x, z) = (&mut self.x[k], &mut self.z[k]); + for w in 0..s { + let p = pivot * s + w; + let (mut px, mut pz, mut flips) = (x[p], z[p], ZERO); + for &t in cx_targets { + let i = t * s + w; + let ([nx, nz, tx, tz], f) = heisenberg::cnot([px, pz, x[i], z[i]]); + (x[i], z[i], px, pz) = (tx, tz, nx, nz); + flips ^= f; + } + let ([nx, nz], f) = last(px, pz); + (x[p], z[p]) = (nx, nz); + self.signs[k][w] ^= flips ^ f; + } + } + } +} + +/// Visit the 64 × 64 blocks of a `stride`-word square bit matrix in groups of up to +/// [`LANES`] side by side: first row, first column, and blocks in the group. +fn for_each_block(stride: usize, mut f: impl FnMut(usize, usize, usize)) { + for rows in (0..stride).map(|w| 64 * w) { + for w in (0..stride).step_by(LANES) { + f(rows, 64 * w, LANES.min(stride - w)); + } + } +} + +#[cfg(test)] +mod tests { + use super::super::test_support::*; + use super::*; + + /// Building the copy and writing it back restores the tableau exactly, + /// and the copy's bits and signs are the rows' bits and signs. + #[test] + fn round_trip_and_bits_match() { + // 300 qubits: one full group of `LANES` column blocks and a partial one. + for (i, n) in SIZES.into_iter().chain([300]).enumerate() { + let mut t = InverseTableau::new(n); + random_circuit(n, 150, 0x7a + i as u64) + .into_iter() + .for_each(|g| apply(&mut t, g)); + let c = TransposedTableau::from_rows(&t); + for q in 0..n { + for col in 0..n { + assert_eq!(c.bits(0, q, col), [t.ix(q).x_bit(col), t.ix(q).z_bit(col)]); + assert_eq!(c.bits(1, q, col), [t.iz(q).x_bit(col), t.iz(q).z_bit(col)]); + } + assert_eq!(c.negative(1, q), t.iz(q).negative); + } + let mut back = InverseTableau::new(n); + random_circuit(n, 20, 0x99) + .into_iter() + .for_each(|g| apply(&mut back, g)); + c.write_rows(&mut back); + assert_eq!(back, t, "n = {n}"); + } + } +} diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/view.rs b/crates/ppvm-tableau-2/src/inverse_tableau/view.rs new file mode 100644 index 000000000..1ad37baa5 --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/view.rs @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! [`VirtualView`]: the part of the tableau a virtual state may use. + +use ppvm_pauli_kernels::row_product; + +use super::bitword::{BITWORD_BITS, BitWord, ZERO, bit_position, get_bit, mask_if}; +use super::{InverseTableau, RowRef}; + +/// A set of qubits as packed bits, e.g. the active virtual qubits, so rows +/// can be classified against it word by word. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct QubitMask { + pub(super) words: Vec, +} + +impl QubitMask { + /// The empty set over `n` qubits. + pub fn new(n: usize) -> Self { + Self { + words: vec![ZERO; n.div_ceil(BITWORD_BITS)], + } + } + + pub fn contains(&self, q: usize) -> bool { + get_bit(&self.words, q) + } + + pub fn set(&mut self, q: usize, member: bool) { + let (w, m) = bit_position(q); + self.words[w] = self.words[w] & !m | m & mask_if(member); + } +} + +/// An owned row, e.g. a product of rows: its X words, Z words and sign. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OwnedRow { + x: Vec, + z: Vec, + negative: bool, +} + +impl OwnedRow { + pub fn row(&self) -> RowRef<'_> { + RowRef { + x: &self.x, + z: &self.z, + negative: self.negative, + } + } +} + +/// The virtual side of an [`InverseTableau`]: row reads and changes of basis +/// `C ← C·V`, but no physical gates. A virtual state gets this view, so it can +/// change basis together with its own state while `|ψ⟩` stays the same. +pub struct VirtualView<'a> { + t: &'a mut InverseTableau, +} + +impl InverseTableau { + pub fn virtual_view(&mut self) -> VirtualView<'_> { + VirtualView { t: self } + } +} + +impl VirtualView<'_> { + pub fn num_qubits(&self) -> usize { + self.t.num_qubits() + } + + /// Row `ix_q = C⁻¹ X_q C`. + pub fn ix(&self, q: usize) -> RowRef<'_> { + self.t.ix(q) + } + + /// Row `iz_q = C⁻¹ Z_q C`. + pub fn iz(&self, q: usize) -> RowRef<'_> { + self.t.iz(q) + } + + /// `O = C⁻¹ (∏ Z_q) C = ∏ iz_q` over `qubits`, which must be distinct. The + /// `Z_q` commute, so `O` is a Hermitian Pauli string with sign ±1. + pub fn iz_product(&self, qubits: &[usize]) -> OwnedRow { + let stride = self.t.stride; + let (mut x, mut z) = (vec![ZERO; stride], vec![ZERO; stride]); + // Power of `i` in front of the product of the bare rows. + let mut phase = 0u8; + for &q in qubits { + let r = self.t.iz(q); + let k = row_product(&mut x, &mut z, r.x, r.z) + 2 * u8::from(r.negative); + phase = phase.wrapping_add(k); + } + debug_assert_eq!(phase % 2, 0, "product of commuting rows is Hermitian"); + OwnedRow { + x, + z, + negative: phase % 4 == 2, + } + } + + /// See [`InverseTableau::change_basis1`]. + pub fn change_basis1(&mut self, v: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + self.t.change_basis1(v, rule); + } + + /// See [`InverseTableau::change_basis2`]. + pub fn change_basis2( + &mut self, + a: usize, + b: usize, + rule: impl Fn([bool; 4]) -> ([bool; 4], bool), + ) { + self.t.change_basis2(a, b, rule); + } + + /// See [`InverseTableau::fan_out`]. + pub fn fan_out( + &mut self, + pivot: usize, + cx_targets: &[usize], + cz_targets: &[usize], + last: impl Fn(bool, bool) -> ([bool; 2], bool), + ) { + self.t.fan_out(pivot, cx_targets, cz_targets, last); + } + + /// Measure `Z_q` with every virtual qubit dormant, i.e. on `C |0…0⟩`. See + /// [`InverseTableau::measure`]; the collapse is a change of basis only. + pub fn measure(&mut self, q: usize, coin: impl FnOnce() -> bool) -> bool { + self.t.measure(q, coin) + } + + /// See [`InverseTableau::collapse_dormant`]. + pub fn collapse_dormant(&mut self, q: usize, active: &QubitMask, m: bool) { + self.t.collapse_dormant(q, active, m); + } +} diff --git a/crates/ppvm-tableau-2/src/inverse_tableau/virtual_gates.rs b/crates/ppvm-tableau-2/src/inverse_tableau/virtual_gates.rs new file mode 100644 index 000000000..a84b04a70 --- /dev/null +++ b/crates/ppvm-tableau-2/src/inverse_tableau/virtual_gates.rs @@ -0,0 +1,228 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Virtual gates, i.e. changes of basis `C ← C·V`: they rewrite columns. + +use ppvm_pauli_kernels::heisenberg; + +use super::InverseTableau; +use super::bitword::{BitWord, ZERO, bit_position, mask_if}; + +impl InverseTableau { + /// Change the basis of virtual qubit `v` by the one-qubit Clifford `V` + /// whose Heisenberg rule is `rule`: `C ← C·V`. + /// + /// Updates the tableau only. The state `C (|φ⟩ ⊗ |0…0⟩)` stays the same if + /// the caller also applies `V†` to `φ`, or if `V` acts trivially on it (e.g. + /// `v` dormant and `V` fixes `|0⟩`). + /// + /// Every row `R` becomes `V† R V`: the rule runs on each row's bits in + /// column `v`. Strided: one word per row. + /// + /// Used by: dormant-pivot collapse (`H` on the pivot, `X` to fix the + /// outcome), active collapse (the final rotation onto `Z_h`), reset. + pub fn change_basis1(&mut self, v: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + debug_assert!(v < self.n); + let (w, m) = bit_position(v); + self.for_each_row(|x, z| { + let old = [x[w] & m != ZERO, z[w] & m != ZERO]; + let (new, flip) = rule(old[0], old[1]); + x[w] ^= m & mask_if(new[0] != old[0]); + z[w] ^= m & mask_if(new[1] != old[1]); + flip + }); + } + + /// Change the basis of virtual qubits `a`, `b` by the two-qubit Clifford + /// `V` whose Heisenberg rule is `rule` (`a` is the control for controlled + /// gates): `C ← C·V`. Same contract as [`change_basis1`](Self::change_basis1). + /// + /// Used by: T-gate localization (`CX(p, v)` collects the X bits of `O` onto + /// the pivot `p`), dormant-pivot collapse (`CX(p, v)`, `CZ(p, c)`), active + /// collapse (the `CX` / `CZ` that reduce `P` to one qubit). + pub fn change_basis2( + &mut self, + a: usize, + b: usize, + rule: impl Fn([bool; 4]) -> ([bool; 4], bool), + ) { + debug_assert!(a < self.n && b < self.n && a != b); + let [(wa, ma), (wb, mb)] = [bit_position(a), bit_position(b)]; + self.for_each_row(|x, z| { + let old = [ + x[wa] & ma != ZERO, + z[wa] & ma != ZERO, + x[wb] & mb != ZERO, + z[wb] & mb != ZERO, + ]; + let (new, flip) = rule(old); + x[wa] ^= ma & mask_if(new[0] != old[0]); + z[wa] ^= ma & mask_if(new[1] != old[1]); + x[wb] ^= mb & mask_if(new[2] != old[2]); + z[wb] ^= mb & mask_if(new[3] != old[3]); + flip + }); + } + + /// Change basis by a pivot fan-out in one pass over the rows: + /// `C ← C·V` with `V = CX(p, t₁)⋯CX(p, t_k) · CZ(p, c₁)⋯CZ(p, c_m) · L(p)`, + /// where `L` is the one-qubit Clifford whose Heisenberg rule is `last`. + /// + /// Same result and contract as the corresponding [`change_basis2`] / + /// [`change_basis1`] calls in that order, but each row loads and stores the + /// pivot's bits and its sign once instead of once per gate. Targets must be + /// distinct and differ from the pivot. + /// + /// Used by: T-gate localization (CX only, `last` the identity), both + /// random measurement collapses (CX, CZ, then `H`/`S·H` and an `X`). + /// + /// [`change_basis1`]: Self::change_basis1 + /// [`change_basis2`]: Self::change_basis2 + pub fn fan_out( + &mut self, + pivot: usize, + cx_targets: &[usize], + cz_targets: &[usize], + last: impl Fn(bool, bool) -> ([bool; 2], bool), + ) { + debug_assert!( + cx_targets + .iter() + .chain(cz_targets) + .all(|&t| t < self.n && t != pivot) + ); + let (pw, pm) = bit_position(pivot); + self.for_each_row(|x, z| { + let old_pivot = [x[pw] & pm != ZERO, z[pw] & pm != ZERO]; + let (mut pivot_bits, mut flip) = (old_pivot, false); + if old_pivot[0] { + pivot_bits[0] = true; + for &t in cx_targets { + flip ^= target_step(x, z, t, &mut pivot_bits, heisenberg::cnot); + } + for &t in cz_targets { + flip ^= target_step(x, z, t, &mut pivot_bits, heisenberg::cz); + } + } else { + pivot_bits[0] = false; + for &t in cx_targets { + flip ^= target_step(x, z, t, &mut pivot_bits, heisenberg::cnot); + } + for &t in cz_targets { + flip ^= target_step(x, z, t, &mut pivot_bits, heisenberg::cz); + } + } + let (new_pivot, f) = last(pivot_bits[0], pivot_bits[1]); + x[pw] ^= pm & mask_if(new_pivot[0] != old_pivot[0]); + z[pw] ^= pm & mask_if(new_pivot[1] != old_pivot[1]); + flip ^ f + }); + } +} + +/// Run a two-qubit `rule` on the pivot's bits (held in `pivot_bits`) and +/// target `t`'s bits in one row (`x`, `z`); store the target's changed bits. +/// Returns the sign flip. +#[inline(always)] +fn target_step( + x: &mut [BitWord], + z: &mut [BitWord], + t: usize, + pivot_bits: &mut [bool; 2], + rule: impl Fn([bool; 4]) -> ([bool; 4], bool), +) -> bool { + let (w, m) = bit_position(t); + let old = [x[w] & m != ZERO, z[w] & m != ZERO]; + let ([px, pz, tx, tz], flip) = rule([pivot_bits[0], pivot_bits[1], old[0], old[1]]); + x[w] ^= m & mask_if(tx != old[0]); + z[w] ^= m & mask_if(tz != old[1]); + *pivot_bits = [px, pz]; + flip +} + +#[cfg(test)] +mod tests { + use super::super::test_support::*; + use super::*; + + #[test] + fn change_basis_preserves_commutation() { + for (i, n) in [1, 2, 7, 65].into_iter().enumerate() { + let mut t = InverseTableau::new(n); + for gate in random_circuit(n, 100, 0xba5e + i as u64) { + change_basis(&mut t, gate); + assert_canonical_commutation(&t); + } + } + } + + /// `(G·C)·V = G·(C·V)`: the order of physical gates relative to changes of + /// basis does not matter. + #[test] + fn physical_gates_commute_with_changes_of_basis() { + for (i, n) in SIZES.into_iter().filter(|&n| n > 1).enumerate() { + let physical = random_circuit(n, 100, 0xc0de + i as u64); + let basis = random_circuit(n, 100, 0xfeed + i as u64); + let (mut first, mut second) = (InverseTableau::new(n), InverseTableau::new(n)); + physical.iter().for_each(|&g| apply(&mut first, g)); + basis.iter().for_each(|&g| change_basis(&mut first, g)); + basis.iter().for_each(|&g| change_basis(&mut second, g)); + physical.iter().for_each(|&g| apply(&mut second, g)); + assert_eq!(first, second, "n = {n}"); + } + } + + type Rule1 = fn(bool, bool) -> ([bool; 2], bool); + + /// The fused fan-out equals the separate changes of basis it replaces. + #[test] + fn fan_out_matches_separate_changes_of_basis() { + use ppvm_pauli_kernels::heisenberg as rules; + let lasts: [Rule1; 6] = [ + |x, z| ([x, z], false), + rules::h, + rules::s, + rules::x, + rules::sqrt_x, + rules::sqrt_y_dag, + ]; + let mut seed = 0xfa40_u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as usize + }; + for n in SIZES.into_iter().filter(|&n| n > 1) { + for round in 0..20 { + let mut start = InverseTableau::new(n); + random_circuit(n, 60, next() as u64) + .into_iter() + .for_each(|g| apply(&mut start, g)); + random_circuit(n, 20, next() as u64) + .into_iter() + .for_each(|g| change_basis(&mut start, g)); + let pivot = next() % n; + // Each other qubit is a CX target, a CZ target, or neither. + let (mut cx, mut cz) = (Vec::new(), Vec::new()); + for t in (0..n).filter(|&t| t != pivot) { + match next() % 4 { + 0 => cx.push(t), + 1 => cz.push(t), + _ => {} + } + } + let last = lasts[round % lasts.len()]; + let mut fused = start.clone(); + fused.fan_out(pivot, &cx, &cz, last); + let mut separate = start; + cx.iter() + .for_each(|&t| separate.change_basis2(pivot, t, rules::cnot)); + cz.iter() + .for_each(|&t| separate.change_basis2(pivot, t, rules::cz)); + separate.change_basis1(pivot, last); + assert_eq!(fused, separate, "n = {n}, round {round}"); + } + } + } +} diff --git a/crates/ppvm-tableau-2/src/lib.rs b/crates/ppvm-tableau-2/src/lib.rs new file mode 100644 index 000000000..b8d81fb11 --- /dev/null +++ b/crates/ppvm-tableau-2/src/lib.rs @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Hybrid stabilizer simulation: `|ψ⟩ = C |χ⟩`, an inverse tableau for the +//! Clifford `C` plus the state `|χ⟩` of the virtual qubits in an exchangeable +//! representation. +//! +//! - `inverse_tableau`: [`InverseTableau`] and its [`VirtualView`]. +//! - `virtual_state`: the [`VirtualState`] trait and [`ActiveDormant`], which +//! keeps amplitudes only for the active virtual qubits. +//! - `generalized_tableau`: [`GeneralizedTableau`], the simulator. + +mod display; +mod generalized_tableau; +mod inverse_tableau; +mod virtual_state; + +pub use generalized_tableau::GeneralizedTableau; +pub use inverse_tableau::{InverseTableau, OwnedRow, QubitMask, RowRef, VirtualView}; +pub use virtual_state::{ + ActiveDormant, ActiveState, AxisPauli, DenseState, RotationCollapse, VirtualState, +}; diff --git a/crates/ppvm-tableau-2/src/virtual_state/active_dormant/axis.rs b/crates/ppvm-tableau-2/src/virtual_state/active_dormant/axis.rs new file mode 100644 index 000000000..bc53034d2 --- /dev/null +++ b/crates/ppvm-tableau-2/src/virtual_state/active_dormant/axis.rs @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Paulis on the active axes, and the rotation that collapses onto one axis. + +use ppvm_traits_2::{ApplyGateRule, Clifford}; + +/// A Pauli on the active axes, unsigned: bit `j` of `x` / `z` is the X / Z +/// factor on axis `j`, and both set is Y. +/// `P|α⟩ = i^{|x∧z|} (−1)^{|α∧z|} |α ⊕ x⟩`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AxisPauli { + pub x: u64, + pub z: u64, +} + +impl AxisPauli { + pub fn is_identity(&self) -> bool { + self.x == 0 && self.z == 0 + } + + fn get(&self, j: usize) -> [bool; 2] { + [self.x >> j & 1 == 1, self.z >> j & 1 == 1] + } + + fn set(&mut self, j: usize, [x, z]: [bool; 2]) { + self.x = self.x & !(1 << j) | u64::from(x) << j; + self.z = self.z & !(1 << j) | u64::from(z) << j; + } +} + +/// An [`AxisPauli`] with a sign, so the gate rules can run on it. +struct Signed { + p: AxisPauli, + negative: bool, +} + +impl ApplyGateRule for Signed { + type B = bool; + + fn apply1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + let [x, z] = self.p.get(q); + let (bits, flip) = rule(x, z); + self.p.set(q, bits); + self.negative ^= flip; + } + + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([bool; 4]) -> ([bool; 4], bool)) { + let ([xa, za], [xb, zb]) = (self.p.get(a), self.p.get(b)); + let ([xa, za, xb, zb], flip) = rule([xa, za, xb, zb]); + self.p.set(a, [xa, za]); + self.p.set(b, [xb, zb]); + self.negative ^= flip; + } +} + +/// The change of basis `V` of a collapse, shared by the tableau (`C ← C·V`) +/// and the active state (`φ ← V† φ`), as a gate sequence applied in this +/// order: CX from `pivot` to every axis in `fan_out`, CX from every axis in +/// `fan_in` to `pivot`, CZ between `pivot` and every axis in `cz`, then `S`, +/// `H`, `X` on `pivot` where set. +/// +/// Built by [`RotationCollapse::collapse`] so that `V† P V = ±Z_pivot` and the +/// measured branch leaves `pivot` in `|0⟩`; one place decides the gates. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RotationCollapse { + pub pivot: usize, + pub fan_out: u64, + pub fan_in: u64, + pub cz: u64, + pub s: bool, + pub h: bool, + pub x: bool, +} + +impl RotationCollapse { + /// The rotation for measuring `p` with outcome `m` (eigenvalue `(−1)^m`): + /// after `V`, the projection onto that outcome leaves `pivot` in `|0⟩`. + /// + /// With an X part, the pivot is its lowest X axis: CX from it clears the + /// other X bits, CZ clears the remaining Z bits, and `H` (`S`, `H` for a + /// Y) turns the pivot's X into Z. A Z-only `p` collects its Z bits onto its + /// lowest Z axis with CX into it. + pub fn collapse(p: AxisPauli, m: bool) -> Self { + assert!(!p.is_identity(), "measuring the identity"); + let mut v = if p.x != 0 { + let pivot = p.x.trailing_zeros() as usize; + let fan_out = p.x & !(1 << pivot); + let cx_only = Self { + pivot, + fan_out, + fan_in: 0, + cz: 0, + s: false, + h: false, + x: false, + }; + // After the CXs, the Z bits left on other axes are the CZ targets, + // and a Z left on the pivot makes it a Y. + let after_cx = cx_only.conjugate(p).0; + Self { + cz: after_cx.z & !(1 << pivot), + s: after_cx.z >> pivot & 1 == 1, + h: true, + ..cx_only + } + } else { + let pivot = p.z.trailing_zeros() as usize; + Self { + pivot, + fan_out: 0, + fan_in: p.z & !(1 << pivot), + cz: 0, + s: false, + h: false, + x: false, + } + }; + let (reduced, negative) = v.conjugate(p); + debug_assert_eq!( + reduced, + AxisPauli { + x: 0, + z: 1 << v.pivot + } + ); + // The projection leaves the pivot in |b⟩ with (−1)^b = ±(−1)^m; X maps it to |0⟩. + v.x = m != negative; + v + } + + /// Apply the gates of `V` to `c`, in order. + pub(crate) fn apply_gates(&self, c: &mut impl Clifford) { + let p = self.pivot; + for t in bits(self.fan_out) { + c.cnot(p, t); + } + for ctrl in bits(self.fan_in) { + c.cnot(ctrl, p); + } + for t in bits(self.cz) { + c.cz(p, t); + } + if self.s { + c.s(p); + } + if self.h { + c.h(p); + } + if self.x { + c.x(p); + } + } + + /// `V† p V` and whether it picks up a sign, by running the gate rules on + /// `p` in gate order. + pub fn conjugate(&self, p: AxisPauli) -> (AxisPauli, bool) { + let mut signed = Signed { p, negative: false }; + self.apply_gates(&mut signed); + (signed.p, signed.negative) + } +} + +/// The set bits of `mask`, ascending. +pub(super) fn bits(mut mask: u64) -> impl Iterator { + std::iter::from_fn(move || { + (mask != 0).then(|| { + let j = mask.trailing_zeros() as usize; + mask &= mask - 1; + j + }) + }) +} diff --git a/crates/ppvm-tableau-2/src/virtual_state/active_dormant/dense.rs b/crates/ppvm-tableau-2/src/virtual_state/active_dormant/dense.rs new file mode 100644 index 000000000..aeacf7cae --- /dev/null +++ b/crates/ppvm-tableau-2/src/virtual_state/active_dormant/dense.rs @@ -0,0 +1,499 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The exact dense backend: `2^k` amplitudes, bit `j` of an index is axis `j`. + +use num_complex::Complex64; + +use super::axis::{AxisPauli, RotationCollapse, bits}; +use super::state::ActiveState; + +#[derive(Clone, Debug, PartialEq)] +pub struct DenseState { + amplitudes: Vec, +} + +impl Default for DenseState { + /// No axes: the single amplitude 1. + fn default() -> Self { + Self { + amplitudes: vec![Complex64::new(1.0, 0.0)], + } + } +} + +/// `i^e`. +fn i_pow(e: u32) -> Complex64 { + [ + Complex64::new(1.0, 0.0), + Complex64::new(0.0, 1.0), + Complex64::new(-1.0, 0.0), + Complex64::new(0.0, -1.0), + ][(e % 4) as usize] +} + +/// `c` with `P|α⟩ = c · |α ⊕ x⟩`. +fn pauli_factor(p: AxisPauli, alpha: usize) -> Complex64 { + let negative = (alpha as u64 & p.z).count_ones() % 2 == 1; + let c = i_pow((p.x & p.z).count_ones()); + if negative { -c } else { c } +} + +impl DenseState { + pub fn amplitudes(&self) -> &[Complex64] { + &self.amplitudes + } + + /// `φ ← G† φ` for each gate of `v` in order. + fn apply_rotation_dagger(&mut self, v: &RotationCollapse) { + let p = 1usize << v.pivot; + for t in bits(v.fan_out) { + self.cx(p, 1 << t); + } + for c in bits(v.fan_in) { + self.cx(1 << c, p); + } + for t in bits(v.cz) { + let both = p | 1 << t; + self.for_each_index(|a, amp| { + if a & both == both { + *amp = -*amp; + } + }); + } + if v.s { + // S† = diag(1, −i). + self.for_each_index(|a, amp| { + if a & p != 0 { + *amp *= Complex64::new(0.0, -1.0); + } + }); + } + if v.h { + let r = std::f64::consts::FRAC_1_SQRT_2; + for a in (0..self.amplitudes.len()).filter(|a| a & p == 0) { + let (lo, hi) = (self.amplitudes[a], self.amplitudes[a | p]); + self.amplitudes[a] = (lo + hi) * r; + self.amplitudes[a | p] = (lo - hi) * r; + } + } + if v.x { + for a in (0..self.amplitudes.len()).filter(|a| a & p == 0) { + self.amplitudes.swap(a, a | p); + } + } + } + + /// CX with control mask `c` and target mask `t` (its own inverse). + fn cx(&mut self, c: usize, t: usize) { + for a in (0..self.amplitudes.len()).filter(|a| a & c != 0 && a & t == 0) { + self.amplitudes.swap(a, a | t); + } + } + + fn for_each_index(&mut self, mut f: impl FnMut(usize, &mut Complex64)) { + for (a, amp) in self.amplitudes.iter_mut().enumerate() { + f(a, amp); + } + } +} + +impl ActiveState for DenseState { + fn num_axes(&self) -> usize { + self.amplitudes.len().trailing_zeros() as usize + } + + fn activate(&mut self) { + let len = self.amplitudes.len(); + self.amplitudes.resize(2 * len, Complex64::new(0.0, 0.0)); + } + + fn rotate(&mut self, p: AxisPauli, a: Complex64, b: Complex64) { + let x = p.x as usize; + if x == 0 { + self.for_each_index(|alpha, amp| *amp *= a + b * pauli_factor(p, alpha)); + return; + } + // Pair α with β = α ⊕ x: each new amplitude mixes the two old ones. + for alpha in 0..self.amplitudes.len() { + let beta = alpha ^ x; + if alpha < beta { + let (ua, ub) = (self.amplitudes[alpha], self.amplitudes[beta]); + self.amplitudes[alpha] = a * ua + b * pauli_factor(p, beta) * ub; + self.amplitudes[beta] = a * ub + b * pauli_factor(p, alpha) * ua; + } + } + } + + fn branch_weights(&self, p: AxisPauli) -> [f64; 2] { + let x = p.x as usize; + // ‖½(1 ± P)φ‖² summed directly, with (Pφ)[α] = c(α ⊕ x) · φ[α ⊕ x]: never + // negative, and an impossible branch stays O(ε²) instead of ±ε. + let (mut plus, mut minus) = (0.0, 0.0); + for (alpha, &) in self.amplitudes.iter().enumerate() { + let p_amp = pauli_factor(p, alpha ^ x) * self.amplitudes[alpha ^ x]; + plus += (amp + p_amp).norm_sqr(); + minus += (amp - p_amp).norm_sqr(); + } + [0.25 * plus, 0.25 * minus] + } + + fn collapse(&mut self, p: AxisPauli, m: bool, v: &RotationCollapse) { + // Project onto eigenvalue (−1)^m: φ ← ½(φ ± P φ). + let sign = if m { -0.5 } else { 0.5 }; + self.rotate(p, Complex64::new(0.5, 0.0), Complex64::new(sign, 0.0)); + self.apply_rotation_dagger(v); + // The pivot is |0⟩ now: keep those amplitudes, removing its bit. + let h = v.pivot; + let low = (1usize << h) - 1; + let kept: Vec = (0..self.amplitudes.len() / 2) + .map(|a| self.amplitudes[(a & low) | (a & !low) << 1]) + .collect(); + let norm = kept.iter().map(|a| a.norm_sqr()).sum::().sqrt(); + assert!(norm > 0.0, "collapsed onto a branch of zero weight"); + self.amplitudes = kept.into_iter().map(|a| a / norm).collect(); + } +} + +#[cfg(test)] +mod tests { + //! Checked against plain matrices: Paulis as tensor products of 2 × 2 + //! matrices, `V` as a product of gate matrices. Bit `j` of an index is axis + //! `j`. No code is shared with the backend. + use super::*; + + type C = Complex64; + type Mat = Vec>; + + fn c(re: f64, im: f64) -> C { + C::new(re, im) + } + + fn identity(d: usize) -> Mat { + (0..d) + .map(|i| { + (0..d) + .map(|j| c(f64::from(u8::from(i == j)), 0.0)) + .collect() + }) + .collect() + } + + fn mul(a: &Mat, b: &Mat) -> Mat { + let d = a.len(); + (0..d) + .map(|i| { + (0..d) + .map(|j| (0..d).map(|k| a[i][k] * b[k][j]).sum()) + .collect() + }) + .collect() + } + + fn dagger(a: &Mat) -> Mat { + let d = a.len(); + (0..d) + .map(|i| (0..d).map(|j| a[j][i].conj()).collect()) + .collect() + } + + fn apply(a: &Mat, v: &[C]) -> Vec { + a.iter() + .map(|row| row.iter().zip(v).map(|(x, y)| x * y).sum()) + .collect() + } + + /// The one-qubit matrix `u` on axis `j` of `k`. + fn on_axis(u: [[C; 2]; 2], j: usize, k: usize) -> Mat { + let d = 1 << k; + (0..d) + .map(|r| { + (0..d) + .map(|s| { + if (r ^ s) & !(1 << j) == 0 { + u[r >> j & 1][s >> j & 1] + } else { + c(0.0, 0.0) + } + }) + .collect() + }) + .collect() + } + + fn pauli(p: AxisPauli, k: usize) -> Mat { + let (o, l, i) = (c(0.0, 0.0), c(1.0, 0.0), c(0.0, 1.0)); + (0..k).fold(identity(1 << k), |m, j| { + let u = match (p.x >> j & 1, p.z >> j & 1) { + (0, 0) => return m, + (1, 0) => [[o, l], [l, o]], + (0, _) => [[l, o], [o, -l]], + _ => [[o, -i], [i, o]], + }; + mul(&m, &on_axis(u, j, k)) + }) + } + + /// `V` = the product of `v`'s gate matrices in gate order. + fn rotation_matrix(v: &RotationCollapse, k: usize) -> Mat { + let d = 1 << k; + let (o, l, i) = (c(0.0, 0.0), c(1.0, 0.0), c(0.0, 1.0)); + let r = std::f64::consts::FRAC_1_SQRT_2; + let cx = |ctl: usize, tgt: usize| -> Mat { + (0..d) + .map(|row| { + (0..d) + .map(|col| { + let image = if col >> ctl & 1 == 1 { + col ^ 1 << tgt + } else { + col + }; + c(f64::from(u8::from(row == image)), 0.0) + }) + .collect() + }) + .collect() + }; + let cz = |a: usize, b: usize| -> Mat { + (0..d) + .map(|row| { + (0..d) + .map(|col| { + let s = if col >> a & 1 == 1 && col >> b & 1 == 1 { + -1.0 + } else { + 1.0 + }; + c(if row == col { s } else { 0.0 }, 0.0) + }) + .collect() + }) + .collect() + }; + let mut gates = Vec::new(); + bits(v.fan_out).for_each(|t| gates.push(cx(v.pivot, t))); + bits(v.fan_in).for_each(|s| gates.push(cx(s, v.pivot))); + bits(v.cz).for_each(|t| gates.push(cz(v.pivot, t))); + if v.s { + gates.push(on_axis([[l, o], [o, i]], v.pivot, k)); + } + if v.h { + gates.push(on_axis( + [[c(r, 0.0), c(r, 0.0)], [c(r, 0.0), c(-r, 0.0)]], + v.pivot, + k, + )); + } + if v.x { + gates.push(on_axis([[o, l], [l, o]], v.pivot, k)); + } + gates.iter().fold(identity(d), |m, g| mul(&m, g)) + } + + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 - 0.5 + } + + fn state(&mut self, k: usize) -> DenseState { + let amps: Vec = (0..1 << k).map(|_| c(self.unit(), self.unit())).collect(); + let norm = amps.iter().map(|a| a.norm_sqr()).sum::().sqrt(); + DenseState { + amplitudes: amps.into_iter().map(|a| a / norm).collect(), + } + } + + fn pauli(&mut self, k: usize) -> AxisPauli { + loop { + let mask = (1u64 << k) - 1; + let p = AxisPauli { + x: self.next() & mask, + z: self.next() & mask, + }; + if !p.is_identity() { + return p; + } + } + } + } + + fn assert_close(a: &[C], b: &[C]) { + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(b) { + assert!((x - y).norm() < 1e-12, "{a:?} != {b:?}"); + } + } + + #[test] + fn activate_appends_zero() { + let mut rng = Rng(3); + let phi = rng.state(3); + let mut grown = phi.clone(); + grown.activate(); + assert_eq!(grown.num_axes(), 4); + let zeros = vec![c(0.0, 0.0); 8]; + assert_close(&grown.amplitudes[..8], &phi.amplitudes); + assert_close(&grown.amplitudes[8..], &zeros); + } + + #[test] + fn rotate_matches_matrices() { + let mut rng = Rng(5); + for k in 1..=5 { + for _ in 0..20 { + let (phi, p) = (rng.state(k), rng.pauli(k)); + let (a, b) = (c(rng.unit(), rng.unit()), c(rng.unit(), rng.unit())); + let mut got = phi.clone(); + got.rotate(p, a, b); + let pm = pauli(p, k); + let op: Mat = (0..1 << k) + .map(|i| { + (0..1 << k) + .map(|j| a * identity(1 << k)[i][j] + b * pm[i][j]) + .collect() + }) + .collect(); + assert_close(&got.amplitudes, &apply(&op, &phi.amplitudes)); + } + } + } + + #[test] + fn branch_weights_match_matrices() { + let mut rng = Rng(7); + for k in 1..=5 { + for _ in 0..20 { + let (phi, p) = (rng.state(k), rng.pauli(k)); + let pv = apply(&pauli(p, k), &phi.amplitudes); + let e: C = phi + .amplitudes + .iter() + .zip(&pv) + .map(|(x, y)| x.conj() * y) + .sum(); + let [w0, w1] = phi.branch_weights(p); + assert!( + (w0 - 0.5 * (1.0 + e.re)).abs() < 1e-12 + && (w1 - 0.5 * (1.0 - e.re)).abs() < 1e-12 + ); + } + } + } + + /// On an eigenstate of `P`, up to rounding, the weights are probabilities: + /// never negative, summing to 1, with the impossible branch at rounding + /// level. + #[test] + fn branch_weights_on_eigenstates() { + let mut rng = Rng(13); + for k in 1..=5 { + for _ in 0..200 { + let (psi, p, q) = (rng.state(k), rng.pauli(k), rng.pauli(k)); + if p.x == 0 && p.z == 0 { + continue; + } + let sign = if rng.next() & 1 == 1 { -1.0 } else { 1.0 }; + let pv = apply(&pauli(p, k), &psi.amplitudes); + let amps: Vec = psi + .amplitudes + .iter() + .zip(&pv) + .map(|(a, b)| a + sign * b) + .collect(); + let norm = amps.iter().map(|a| a.norm_sqr()).sum::().sqrt(); + let mut phi = DenseState { + amplitudes: amps.into_iter().map(|a| a / norm).collect(), + }; + // e^{−iθQ} then e^{iθQ}: the same state, with rounding. + let theta = rng.unit(); + let (cos, sin) = (theta.cos(), theta.sin()); + phi.rotate(q, c(cos, 0.0), c(0.0, -sin)); + phi.rotate(q, c(cos, 0.0), c(0.0, sin)); + let [w0, w1] = phi.branch_weights(p); + assert!(w0 >= 0.0 && w1 >= 0.0, "{w0} {w1}"); + assert!((w0 + w1 - 1.0).abs() < 1e-12); + assert!(w0.min(w1) < 1e-12); + } + } + } + + /// `V† ½(1 + (−1)^m P) V` is the projector onto "pivot in |0⟩". + #[test] + fn rotation_maps_the_branch_to_pivot_zero() { + let mut rng = Rng(11); + for k in 1..=5 { + for _ in 0..30 { + let (p, m) = (rng.pauli(k), rng.next() & 1 == 1); + let v = RotationCollapse::collapse(p, m); + let vm = rotation_matrix(&v, k); + let (pm, id) = (pauli(p, k), identity(1 << k)); + let s = if m { -0.5 } else { 0.5 }; + let proj: Mat = (0..1 << k) + .map(|i| (0..1 << k).map(|j| 0.5 * id[i][j] + s * pm[i][j]).collect()) + .collect(); + let got = mul(&mul(&dagger(&vm), &proj), &vm); + let z = pauli( + AxisPauli { + x: 0, + z: 1 << v.pivot, + }, + k, + ); + for i in 0..1 << k { + for j in 0..1 << k { + let want = 0.5 * id[i][j] + 0.5 * z[i][j]; + assert!( + (got[i][j] - want).norm() < 1e-12, + "k = {k}, p = {p:?}, m = {m}" + ); + } + } + } + } + } + + #[test] + fn collapse_matches_matrices() { + let mut rng = Rng(13); + for k in 1..=5 { + for _ in 0..30 { + let (phi, p) = (rng.state(k), rng.pauli(k)); + let m = rng.next() & 1 == 1; + if phi.branch_weights(p)[usize::from(m)] < 1e-6 { + continue; + } + let v = RotationCollapse::collapse(p, m); + let mut got = phi.clone(); + got.collapse(p, m, &v); + // Project, apply V†, keep the pivot's |0⟩ half, renormalize. + let s = if m { -0.5 } else { 0.5 }; + let pv = apply(&pauli(p, k), &phi.amplitudes); + let projected: Vec = phi + .amplitudes + .iter() + .zip(&pv) + .map(|(x, y)| 0.5 * x + s * y) + .collect(); + let rotated = apply(&dagger(&rotation_matrix(&v, k)), &projected); + let kept: Vec = (0..1usize << k) + .filter(|a| a >> v.pivot & 1 == 0) + .map(|a| rotated[a]) + .collect(); + let norm = kept.iter().map(|a| a.norm_sqr()).sum::().sqrt(); + let want: Vec = kept.iter().map(|a| a / norm).collect(); + assert_eq!(got.num_axes(), k - 1); + assert_close(&got.amplitudes, &want); + } + } + } +} diff --git a/crates/ppvm-tableau-2/src/virtual_state/active_dormant/mod.rs b/crates/ppvm-tableau-2/src/virtual_state/active_dormant/mod.rs new file mode 100644 index 000000000..0fda26415 --- /dev/null +++ b/crates/ppvm-tableau-2/src/virtual_state/active_dormant/mod.rs @@ -0,0 +1,181 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! [`ActiveDormant`]: `|χ⟩ = |φ⟩ ⊗ |0…0⟩`, with `φ` a vector over the active +//! virtual qubits behind the [`ActiveState`] interface, and every other +//! (dormant) virtual qubit in `|0⟩`. +//! +//! - `axis`: Paulis on the axes ([`AxisPauli`]) and the collapse rotation +//! ([`RotationCollapse`]) shared with the tableau. +//! - `state`: the [`ActiveState`] trait. +//! - `dense`: [`DenseState`], an exact vector of `2^k` amplitudes. + +mod axis; +mod dense; +mod state; + +use num_complex::Complex64; + +use ppvm_traits_2::ApplyGateRule; + +use super::VirtualState; +use crate::{QubitMask, RowRef, VirtualView}; + +pub use axis::{AxisPauli, RotationCollapse}; +pub use dense::DenseState; +pub use state::ActiveState; + +/// `|χ⟩ = |φ⟩ ⊗ |0…0⟩`: amplitudes only for the active virtual qubits. +/// +/// Non-Clifford gates activate virtual qubits (localization), and measurements +/// retire them; with no active qubits it is the stabilizer state `C |0…0⟩`. +#[derive(Clone, Debug, PartialEq)] +pub struct ActiveDormant { + /// Virtual qubit of each axis of `φ`: axis `j` is qubit `active[j]`. + active: Vec, + /// The qubits of `active`, for word-wise classification. + mask: QubitMask, + phi: S, +} + +/// How `O = C⁻¹ Z_q C` acts on `|φ⟩ ⊗ |0…0⟩`. +enum Case { + /// No X/Y on dormant qubits and none on the active axes: `O = ±1` there. + Deterministic { outcome: bool }, + /// X/Y on a dormant qubit: 50/50, `φ` untouched. + DormantPivot, + /// `O = ±P` with `P` a nontrivial Pauli on the active axes. + Active { p: AxisPauli, negative: bool }, +} + +impl ActiveDormant { + /// The virtual qubit of each axis of `φ`. + pub fn active(&self) -> &[usize] { + &self.active + } + + pub fn phi(&self) -> &S { + &self.phi + } + + /// `o` on the active axes; its X bits must all be on active qubits. + fn axis_pauli(&self, o: RowRef<'_>) -> AxisPauli { + let mut p = AxisPauli { x: 0, z: 0 }; + for (j, &v) in self.active.iter().enumerate() { + p.x |= u64::from(o.x_bit(v)) << j; + p.z |= u64::from(o.z_bit(v)) << j; + } + debug_assert_eq!(o.x_support().count(), p.x.count_ones() as usize); + p + } + + fn classify(&self, o: RowRef<'_>) -> Case { + if o.x_outside(&self.mask).next().is_some() { + return Case::DormantPivot; + } + let p = self.axis_pauli(o); + if p.is_identity() { + Case::Deterministic { + outcome: o.negative, + } + } else { + Case::Active { + p, + negative: o.negative, + } + } + } +} + +/// The view with axis `j` as virtual qubit `active[j]`, so a [`RotationCollapse`]'s +/// gates change the tableau's basis. +struct OnAxes<'v, 'a> { + t: &'v mut VirtualView<'a>, + active: &'v [usize], +} + +impl ApplyGateRule for OnAxes<'_, '_> { + type B = bool; + + fn apply1(&mut self, j: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + self.t.change_basis1(self.active[j], rule); + } + + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([bool; 4]) -> ([bool; 4], bool)) { + self.t.change_basis2(self.active[a], self.active[b], rule); + } +} + +impl VirtualState for ActiveDormant { + fn new(num_qubits: usize) -> Self { + Self { + active: Vec::new(), + mask: QubitMask::new(num_qubits), + phi: S::default(), + } + } + + fn is_zero(&self) -> bool { + self.active.is_empty() + } + + /// Localization: if `O` has X/Y on dormant qubits, CX from the lowest of + /// them (in `|0⟩`, so `χ` is unchanged) clears the others, and it becomes + /// active. Then `O` acts as `±P` on the active axes and as `+1` elsewhere. + fn rotate(&mut self, t: &mut VirtualView<'_>, qubits: &[usize], a: Complex64, b: Complex64) { + debug_assert_eq!(self.active.len(), self.phi.num_axes()); + let mut o = t.iz_product(qubits); + let dormant_x: Vec = o.row().x_outside(&self.mask).collect(); + if let Some((&pivot, rest)) = dormant_x.split_first() { + t.fan_out(pivot, rest, &[], |x, z| ([x, z], false)); + assert!(self.active.len() < 64, "at most 64 active axes"); + self.active.push(pivot); + self.mask.set(pivot, true); + self.phi.activate(); + o = t.iz_product(qubits); + } + let o = o.row(); + let p = self.axis_pauli(o); + self.phi.rotate(p, a, if o.negative { -b } else { b }); + } + + /// Deterministic, 50/50 for a dormant pivot, or the branch weights of `±P`. + fn z_weights(&mut self, t: &mut VirtualView<'_>, q: usize) -> [f64; 2] { + debug_assert_eq!(self.active.len(), self.phi.num_axes()); + match self.classify(t.iz(q)) { + Case::Deterministic { outcome: false } => [1.0, 0.0], + Case::Deterministic { outcome: true } => [0.0, 1.0], + Case::DormantPivot => [0.5, 0.5], + Case::Active { p, negative } => { + let [plus, minus] = self.phi.branch_weights(p); + if negative { + [minus, plus] + } else { + [plus, minus] + } + } + } + } + + /// The active case measures `P` with outcome `m ⊕ negative`, changes basis + /// so that its pivot axis ends in `|0⟩`, and retires that axis. + fn collapse(&mut self, t: &mut VirtualView<'_>, q: usize, m: bool) { + match self.classify(t.iz(q)) { + Case::Deterministic { outcome } => { + debug_assert_eq!(outcome, m, "collapsing onto an impossible outcome"); + } + Case::DormantPivot => t.collapse_dormant(q, &self.mask, m), + Case::Active { p, negative } => { + let m = m != negative; + let v = RotationCollapse::collapse(p, m); + v.apply_gates(&mut OnAxes { + t, + active: &self.active, + }); + self.phi.collapse(p, m, &v); + let retired = self.active.remove(v.pivot); + self.mask.set(retired, false); + } + } + } +} diff --git a/crates/ppvm-tableau-2/src/virtual_state/active_dormant/state.rs b/crates/ppvm-tableau-2/src/virtual_state/active_dormant/state.rs new file mode 100644 index 000000000..6f35894ca --- /dev/null +++ b/crates/ppvm-tableau-2/src/virtual_state/active_dormant/state.rs @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The interface of the active part. + +use num_complex::Complex64; + +use super::axis::{AxisPauli, RotationCollapse}; + +/// Storage for `φ` over the active axes `0..k`. Only three things happen to +/// it: a Pauli rotation, an activation, and a collapse; every other change of +/// basis is trivial on the state. It sees axes only, never the tableau. +/// +/// `P` is unsigned: the caller folds signs into the coefficients and the +/// outcome. Weights are unnormalized, so `rotate` need not be unitary. +pub trait ActiveState: Clone { + fn num_axes(&self) -> usize; + + /// Append axis `k` in `|0⟩`. + fn activate(&mut self); + + /// `φ ← a·φ + b·P φ`. + fn rotate(&mut self, p: AxisPauli, a: Complex64, b: Complex64); + + /// Unnormalized weights `‖½(1 + P) φ‖²` and `‖½(1 − P) φ‖²` of the + /// outcomes `+1` and `−1`. + fn branch_weights(&self, p: AxisPauli) -> [f64; 2]; + + /// Project onto outcome `m` of `p` (eigenvalue `(−1)^m`), apply `V†` for + /// `v = RotationCollapse::collapse(p, m)`, drop axis `v.pivot` (now `|0⟩`), and + /// renormalize. Axes above the pivot shift down by one. The branch must + /// have nonzero weight. + fn collapse(&mut self, p: AxisPauli, m: bool, v: &RotationCollapse); +} diff --git a/crates/ppvm-tableau-2/src/virtual_state/mod.rs b/crates/ppvm-tableau-2/src/virtual_state/mod.rs new file mode 100644 index 000000000..ee1d05cd1 --- /dev/null +++ b/crates/ppvm-tableau-2/src/virtual_state/mod.rs @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The state `|χ⟩` of the virtual qubits, with `|ψ⟩ = C |χ⟩`, behind the +//! [`VirtualState`] interface. +//! +//! - `active_dormant`: [`ActiveDormant`], `|χ⟩ = |φ⟩ ⊗ |0…0⟩` with `φ` over +//! the active qubits, and the storage of `φ`. + +mod active_dormant; + +use num_complex::Complex64; + +use crate::VirtualView; + +pub use active_dormant::{ActiveDormant, ActiveState, AxisPauli, DenseState, RotationCollapse}; + +/// The `2ⁿ`-dimensional state `|χ⟩` of the `n` virtual qubits, in a +/// representation of the implementor's choice. +/// +/// It sees the tableau only through a [`VirtualView`]: it may change basis +/// (`C ← C·V` with `χ ← V† χ`, so `|ψ⟩` is unchanged), but never applies a +/// physical gate. Arguments are physical qubits; the implementor reads +/// `O = C⁻¹ Z_q C` from the view. The caller samples outcomes, so weights are +/// unnormalized and `rotate` need not be unitary. +pub trait VirtualState: Clone { + /// `|0…0⟩` on `num_qubits` virtual qubits. + fn new(num_qubits: usize) -> Self; + + /// Whether `χ = |0…0⟩`, so `|ψ⟩ = C |0…0⟩` is a stabilizer state and the + /// caller may measure on the tableau alone. `false` is always correct. + fn is_zero(&self) -> bool { + false + } + + /// `χ ← (a·I + b·O) χ` with `O = C⁻¹ (∏ Z_q) C` over `qubits`. + fn rotate(&mut self, t: &mut VirtualView<'_>, qubits: &[usize], a: Complex64, b: Complex64); + + /// Unnormalized weights of the outcomes `0` and `1` of `Z_q`. Takes `&mut` + /// so an implementor may change basis here and reuse it in `collapse`. + fn z_weights(&mut self, t: &mut VirtualView<'_>, q: usize) -> [f64; 2]; + + /// Project onto outcome `m` of `Z_q` and renormalize. The outcome must have + /// nonzero weight. + fn collapse(&mut self, t: &mut VirtualView<'_>, q: usize, m: bool); +} diff --git a/crates/ppvm-tableau-2/tests/dense_matrix.rs b/crates/ppvm-tableau-2/tests/dense_matrix.rs new file mode 100644 index 000000000..28b45f432 --- /dev/null +++ b/crates/ppvm-tableau-2/tests/dense_matrix.rs @@ -0,0 +1,728 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Gates against dense matrices: row `ix_q` must equal `C† X_q C` and +//! `iz_q` must equal `C† Z_q C`, with `C` the product of textbook gate matrices. +//! Measurements are checked against a state vector. No Pauli code is shared +//! with the tableau. + +use std::collections::{HashSet, VecDeque}; + +use num_complex::Complex64 as C; +use ppvm_tableau_2::{ActiveDormant, DenseState, GeneralizedTableau, InverseTableau, VirtualState}; +use ppvm_traits_2::{ + AsymmetricLossChannel, Clifford, Measure, Pauli, RotXY, RotationOne, RotationTwo, TGate, U3Gate, +}; + +/// A dense `2^n × 2^n` matrix; basis index bit `q` is qubit `q`. +#[derive(Clone)] +struct Mat { + d: usize, + a: Vec, +} + +impl Mat { + fn identity(n: usize) -> Self { + let d = 1 << n; + Self { + d, + a: (0..d * d) + .map(|k| C::from(f64::from(u8::from(k % (d + 1) == 0)))) + .collect(), + } + } + + fn mul(&self, o: &Mat) -> Mat { + let d = self.d; + let mut a = vec![C::default(); d * d]; + for i in 0..d { + for k in 0..d { + let s = self.a[i * d + k]; + for j in 0..d { + a[i * d + j] += s * o.a[k * d + j]; + } + } + } + Mat { d, a } + } + + fn adjoint(&self) -> Mat { + let d = self.d; + Mat { + d, + a: (0..d * d) + .map(|k| self.a[(k % d) * d + k / d].conj()) + .collect(), + } + } +} + +type U2 = [[C; 2]; 2]; + +fn c(re: f64, im: f64) -> C { + C::new(re, im) +} + +/// One-qubit gate `u` on qubit `q`. +fn single(u: U2, q: usize, n: usize) -> Mat { + let d = 1 << n; + let mut m = Mat { + d, + a: vec![C::default(); d * d], + }; + for i in 0..d { + for j in 0..d { + if (i ^ j) & !(1 << q) == 0 { + m.a[i * d + j] = u[(i >> q) & 1][(j >> q) & 1]; + } + } + } + m +} + +/// `u` on `target`, controlled on `control` being `|1⟩`. +fn controlled(u: U2, control: usize, target: usize, n: usize) -> Mat { + let d = 1 << n; + let mut m = Mat { + d, + a: vec![C::default(); d * d], + }; + for i in 0..d { + for j in 0..d { + if (i ^ j) & !(1 << target) == 0 { + m.a[i * d + j] = if (i >> control) & 1 == 1 { + u[(i >> target) & 1][(j >> target) & 1] + } else { + C::from(f64::from(u8::from(i == j))) + }; + } + } + } + m +} + +fn gate_matrices() -> [U2; 10] { + let (o, l, i) = (c(0.0, 0.0), c(1.0, 0.0), c(0.0, 1.0)); + let r = std::f64::consts::FRAC_1_SQRT_2; + let h = |a: C, b: C, cc: C, dd: C| [[a * 0.5, b * 0.5], [cc * 0.5, dd * 0.5]]; + [ + [[o, l], [l, o]], // X + [[o, -i], [i, o]], // Y + [[l, o], [o, -l]], // Z + [[c(r, 0.0), c(r, 0.0)], [c(r, 0.0), c(-r, 0.0)]], // H + [[l, o], [o, i]], // S + [[l, o], [o, -i]], // S† + h(c(1.0, 1.0), c(1.0, -1.0), c(1.0, -1.0), c(1.0, 1.0)), // √X + h(c(1.0, -1.0), c(1.0, 1.0), c(1.0, 1.0), c(1.0, -1.0)), // √X† + h(c(1.0, 1.0), c(-1.0, -1.0), c(1.0, 1.0), c(1.0, 1.0)), // √Y + h(c(1.0, -1.0), c(1.0, -1.0), c(-1.0, 1.0), c(1.0, -1.0)), // √Y† + ] +} + +#[derive(Clone, Copy, Debug)] +enum Gate { + One(usize, usize), + Two(usize, usize, usize), +} + +fn apply(t: &mut impl Clifford, gate: Gate) { + match gate { + Gate::One(g, q) => match g { + 0 => t.x(q), + 1 => t.y(q), + 2 => t.z(q), + 3 => t.h(q), + 4 => t.s(q), + 5 => t.s_dag(q), + 6 => t.sqrt_x(q), + 7 => t.sqrt_x_dag(q), + 8 => t.sqrt_y(q), + _ => t.sqrt_y_dag(q), + }, + Gate::Two(g, a, b) => match g { + 0 => t.cnot(a, b), + 1 => t.cz(a, b), + _ => t.cy(a, b), + }, + } +} + +type Rule1 = fn(bool, bool) -> ([bool; 2], bool); +type Rule2 = fn([bool; 4]) -> ([bool; 4], bool); + +/// `gate` as a change of basis on virtual qubits, `C ← C·V`. +fn change_basis(t: &mut InverseTableau, gate: Gate) { + use ppvm_pauli_kernels::heisenberg as rules; + let one: [Rule1; 10] = [ + rules::x, + rules::y, + rules::z, + rules::h, + rules::s, + rules::s_dag, + rules::sqrt_x, + rules::sqrt_x_dag, + rules::sqrt_y, + rules::sqrt_y_dag, + ]; + let two: [Rule2; 3] = [rules::cnot, rules::cz, rules::cy]; + match gate { + Gate::One(g, v) => t.change_basis1(v, one[g]), + Gate::Two(g, a, b) => t.change_basis2(a, b, two[g]), + } +} + +fn matrix(gate: Gate, n: usize) -> Mat { + let u = gate_matrices(); + match gate { + Gate::One(g, q) => single(u[g], q, n), + Gate::Two(g, a, b) => controlled([u[0], u[2], u[1]][g], a, b, n), + } +} + +fn all_gates(n: usize) -> Vec { + let mut gates: Vec = (0..10) + .flat_map(|g| (0..n).map(move |q| Gate::One(g, q))) + .collect(); + for g in 0..3 { + for a in 0..n { + for b in (0..n).filter(|&b| b != a) { + gates.push(Gate::Two(g, a, b)); + } + } + } + gates +} + +/// All Hermitian Pauli strings on `n` qubits, indexed by `x | z << n`. +struct Paulis { + n: usize, + table: Vec, +} + +impl Paulis { + fn new(n: usize) -> Self { + let u = gate_matrices(); + let table = (0..1usize << (2 * n)) + .map(|code| { + (0..n).fold(Mat::identity(n), |m, q| { + match ((code >> q) & 1, (code >> (n + q)) & 1) { + (0, 0) => m, + (1, 0) => m.mul(&single(u[0], q, n)), + (0, _) => m.mul(&single(u[2], q, n)), + _ => m.mul(&single(u[1], q, n)), + } + }) + }) + .collect(); + Self { n, table } + } + + fn x(&self, q: usize) -> &Mat { + &self.table[1 << q] + } + + fn z(&self, q: usize) -> &Mat { + &self.table[1 << (self.n + q)] + } + + /// The signed Pauli string equal to `a`, as `(x | z << n, negative)`. + fn decompose(&self, a: &Mat) -> (usize, bool) { + // A Pauli string maps |0⟩ to a multiple of |x⟩, so column 0 gives x. + let x = (0..a.d) + .find(|&r| a.a[r * a.d].norm() > 0.5) + .expect("zero column"); + for z in 0..1usize << self.n { + let code = x | z << self.n; + let p = &self.table[code]; + let overlap = (0..a.d * a.d).map(|k| p.a[k].conj() * a.a[k]).sum::() / a.d as f64; + if (overlap - 1.0).norm() < 1e-9 { + return (code, false); + } + if (overlap + 1.0).norm() < 1e-9 { + return (code, true); + } + } + panic!("not a signed Pauli string"); + } +} + +/// Row `ix_q` (or `iz_q`) as `(x | z << n, negative)`. +fn row_code(t: &InverseTableau, q: usize, z: bool) -> (usize, bool) { + let row = if z { t.iz(q) } else { t.ix(q) }; + let n = t.num_qubits(); + let code = (0..n) + .map(|j| usize::from(row.x_bit(j)) << j | usize::from(row.z_bit(j)) << (n + j)) + .sum(); + (code, row.negative) +} + +fn assert_rows_match(t: &InverseTableau, cliff: &Mat, paulis: &Paulis, context: &str) { + let dag = cliff.adjoint(); + for q in 0..t.num_qubits() { + let x = paulis.decompose(&dag.mul(paulis.x(q)).mul(cliff)); + let z = paulis.decompose(&dag.mul(paulis.z(q)).mul(cliff)); + assert_eq!(row_code(t, q, false), x, "ix_{q} after {context}"); + assert_eq!(row_code(t, q, true), z, "iz_{q} after {context}"); + } +} + +/// The whole tableau packed into one integer (small `n` only). +fn key(t: &InverseTableau) -> u64 { + let n = t.num_qubits(); + (0..n) + .flat_map(|q| [row_code(t, q, false), row_code(t, q, true)]) + .fold(0, |k, (code, negative)| { + (k << (2 * n + 1)) | (code as u64) << 1 | u64::from(negative) + }) +} + +/// Every gate, physical and as a change of basis, on every two-qubit +/// Clifford. Visiting the whole group also +/// checks that the tableaux reached are exactly its 11520 elements. +#[test] +fn every_gate_on_every_two_qubit_clifford() { + let n = 2; + let gates = all_gates(n); + let paulis = Paulis::new(n); + let start = InverseTableau::new(n); + let mut seen = HashSet::from([key(&start)]); + let mut queue = VecDeque::from([(start, Mat::identity(n))]); + while let Some((t, cliff)) = queue.pop_front() { + for &gate in &gates { + let mut next = t.clone(); + apply(&mut next, gate); + let next_cliff = matrix(gate, n).mul(&cliff); + assert_rows_match(&next, &next_cliff, &paulis, &format!("{gate:?}")); + let mut rebased = t.clone(); + change_basis(&mut rebased, gate); + let rebased_cliff = cliff.mul(&matrix(gate, n)); + assert_rows_match( + &rebased, + &rebased_cliff, + &paulis, + &format!("basis {gate:?}"), + ); + if seen.insert(key(&next)) { + queue.push_back((next, next_cliff)); + } + } + } + assert_eq!(seen.len(), 11520); +} + +/// Random three-qubit circuits mixing physical gates and changes of basis, +/// covering two-qubit gates on non-adjacent qubits. +#[test] +fn random_three_qubit_circuits() { + let n = 3; + let gates = all_gates(n); + let paulis = Paulis::new(n); + let mut seed = 0x2545_f491_4f6c_dd1du64; + for round in 0..50 { + let mut t = InverseTableau::new(n); + let mut cliff = Mat::identity(n); + for _ in 0..60 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let gate = gates[seed as usize % gates.len()]; + if seed >> 63 == 0 { + apply(&mut t, gate); + cliff = matrix(gate, n).mul(&cliff); + } else { + change_basis(&mut t, gate); + cliff = cliff.mul(&matrix(gate, n)); + } + } + assert_rows_match(&t, &cliff, &paulis, &format!("round {round}")); + } +} + +/// Row `ix_q` (or `iz_q`) as a signed Pauli matrix. +fn row_matrix(t: &InverseTableau, q: usize, z: bool, paulis: &Paulis) -> Mat { + let (code, negative) = row_code(t, q, z); + let mut m = paulis.table[code].clone(); + if negative { + m.a.iter_mut().for_each(|e| *e = -*e); + } + m +} + +/// `⟨0…0| C⁻¹ P C |0…0⟩` for the Pauli string `code`, from the rows alone. +fn tableau_expectation(t: &InverseTableau, code: usize, paulis: &Paulis) -> C { + conjugated(t, code, paulis).a[0] +} + +/// `C⁻¹ P C` for the Pauli string `code`, from the rows alone: +/// `P = i^#Y · ∏ X_q^x Z_q^z`, so `C⁻¹ P C = i^#Y · ∏ ix_q^x iz_q^z`. +fn conjugated(t: &InverseTableau, code: usize, paulis: &Paulis) -> Mat { + let n = t.num_qubits(); + let mut m = Mat::identity(n); + let mut phase = c(1.0, 0.0); + for q in 0..n { + let (x, z) = ((code >> q) & 1 == 1, (code >> (n + q)) & 1 == 1); + if x { + m = m.mul(&row_matrix(t, q, false, paulis)); + } + if z { + m = m.mul(&row_matrix(t, q, true, paulis)); + } + if x && z { + phase *= c(0.0, 1.0); + } + } + m.a.iter_mut().for_each(|e| *e *= phase); + m +} + +fn apply_to_state(m: &Mat, v: &[C]) -> Vec { + (0..m.d) + .map(|i| (0..m.d).map(|j| m.a[i * m.d + j] * v[j]).sum()) + .collect() +} + +fn state_expectation(v: &[C], p: &Mat) -> C { + let pv = apply_to_state(p, v); + v.iter().zip(&pv).map(|(a, b)| a.conj() * b).sum() +} + +/// Probability that qubit `q` is `|1⟩`. +fn probability_one(v: &[C], q: usize) -> f64 { + v.iter() + .enumerate() + .filter(|(i, _)| (i >> q) & 1 == 1) + .map(|(_, a)| a.norm_sqr()) + .sum() +} + +/// Project onto outcome `m` of qubit `q` and renormalize. +fn project(v: &mut [C], q: usize, m: bool) { + v.iter_mut() + .enumerate() + .filter(|(i, _)| ((i >> q) & 1 == 1) != m) + .for_each(|(_, a)| *a = C::default()); + let norm = v.iter().map(|a| a.norm_sqr()).sum::().sqrt(); + v.iter_mut().for_each(|a| *a /= norm); +} + +/// Measure `q` on both the tableau and the state vector, forcing `forced` when +/// the outcome is random. The tableau must call the coin exactly when the +/// state vector says the outcome is random. +fn measure_both(t: &mut InverseTableau, v: &mut [C], q: usize, forced: bool) -> bool { + let p1 = probability_one(v, q); + let random = p1 > 1e-9 && p1 < 1.0 - 1e-9; + if random { + assert!( + (p1 - 0.5).abs() < 1e-9, + "random outcome must be 50/50, got {p1}" + ); + } + let mut called = false; + let m = t.measure(q, || { + called = true; + forced + }); + assert_eq!(called, random, "coin called iff the outcome is random"); + if !random { + assert_eq!(m, p1 > 0.5, "deterministic outcome"); + } + project(v, q, m); + m +} + +/// Random three-qubit circuits with measurements and resets: after every step, +/// all 64 Pauli expectations from the tableau match the state vector. +#[test] +fn measurements_match_the_state_vector() { + let n = 3; + let gates = all_gates(n); + let paulis = Paulis::new(n); + let x = gate_matrices()[0]; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as usize + }; + for round in 0..30 { + let mut t = InverseTableau::new(n); + let mut v = vec![C::default(); 1 << n]; + v[0] = c(1.0, 0.0); + for step in 0..60 { + let (q, forced) = (next() % n, next() % 2 == 1); + match next() % 10 { + 0..7 => { + let gate = gates[next() % gates.len()]; + apply(&mut t, gate); + v = apply_to_state(&matrix(gate, n), &v); + } + 7..9 => { + measure_both(&mut t, &mut v, q, forced); + } + _ => { + let m = measure_both(&mut t, &mut v, q, forced); + let mut t_reset = t.clone(); + t_reset.reset(q, || unreachable!("qubit was just measured")); + if m { + t.x(q); + v = apply_to_state(&single(x, q, n), &v); + } + assert_eq!(t, t_reset, "reset = measure + conditional X"); + } + } + for code in 0..1usize << (2 * n) { + let (from_rows, from_state) = ( + tableau_expectation(&t, code, &paulis), + state_expectation(&v, &paulis.table[code]), + ); + assert!( + (from_rows - from_state).norm() < 1e-9, + "round {round} step {step}: Pauli {code:#b}: tableau {from_rows}, state {from_state}" + ); + } + } + } +} + +type Sim = GeneralizedTableau>; + +/// `|χ⟩ = |φ⟩ ⊗ |0…0⟩` as a vector over all virtual qubits. +fn virtual_state(s: &Sim) -> Vec { + let (active, phi) = (s.state().active(), s.state().phi().amplitudes()); + let mut chi = vec![C::default(); 1 << s.num_qubits()]; + for (alpha, &) in phi.iter().enumerate() { + let i: usize = (0..active.len()) + .map(|j| ((alpha >> j) & 1) << active[j]) + .sum(); + chi[i] = amp; + } + chi +} + +/// Code (`x | z << n`) of the Pauli `axis` on qubit `q`. +fn pauli_code(axis: Pauli, q: usize, n: usize) -> usize { + let (x, z) = match axis { + Pauli::I => (0, 0), + Pauli::X => (1, 0), + Pauli::Y => (1, 1), + Pauli::Z => (0, 1), + }; + x << q | z << (n + q) +} + +/// `exp(−i θ/2 P) = cos(θ/2)·I − i sin(θ/2)·P`. +fn rotation(p: &Mat, theta: f64) -> Mat { + let (s, co) = (theta / 2.0).sin_cos(); + let mut m = p.clone(); + for (k, e) in m.a.iter_mut().enumerate() { + let identity = f64::from(u8::from(k % (p.d + 1) == 0)); + *e = c(co * identity, 0.0) + c(0.0, -s) * *e; + } + m +} + +/// Random three-qubit circuits of Cliffords, `T`, `T†`, one- and two-qubit +/// Pauli rotations, `U3`, `R(φ, θ)` and measurements: after every step, all 64 Pauli +/// expectations of `C |χ⟩` match the state vector, and before every +/// measurement the outcome weights match the Born probabilities. +#[test] +fn rotations_match_the_state_vector() { + let n = 3; + let gates = all_gates(n); + let paulis = Paulis::new(n); + let axes = [Pauli::I, Pauli::X, Pauli::Y, Pauli::Z]; + let w = C::from_polar(1.0, std::f64::consts::FRAC_PI_4); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as usize + }; + let (mut max_axes, mut retired, mut stabilizer_measurements) = (0, 0, 0); + for round in 0..40 { + let mut s = Sim::new_with_seed(n, round); + let mut v = vec![C::default(); 1 << n]; + v[0] = c(1.0, 0.0); + for step in 0..40 { + let (a, theta) = (next() % n, (next() % 1000) as f64 * 0.00628); + let b = (a + 1 + next() % (n - 1)) % n; + let (pa, pb) = (axes[next() % 4], axes[next() % 4]); + let axes_before = s.state().active().len(); + let (phi, lambda) = ( + (next() % 1000) as f64 * 0.00628, + (next() % 1000) as f64 * 0.00628, + ); + let m = match next() % 12 { + 0..3 => { + let gate = gates[next() % gates.len()]; + apply(&mut s, gate); + matrix(gate, n) + } + 3 => { + s.t(a); + single([[c(1.0, 0.0), c(0.0, 0.0)], [c(0.0, 0.0), w]], a, n) + } + 4 => { + s.t_dag(a); + single([[c(1.0, 0.0), c(0.0, 0.0)], [c(0.0, 0.0), w.conj()]], a, n) + } + 5 | 6 => { + s.rotate_1(pa, a, theta); + rotation(&paulis.table[pauli_code(pa, a, n)], theta) + } + 7 => { + s.rotate_2(pa, pb, a, b, theta); + let code = pauli_code(pa, a, n) | pauli_code(pb, b, n); + rotation(&paulis.table[code], theta) + } + 8 => { + s.u3(a, theta, phi, lambda); + let (sn, co) = (theta / 2.0).sin_cos(); + let e = |x: f64| C::from_polar(1.0, x); + let u = [ + [c(co, 0.0), -e(lambda) * sn], + [e(phi) * sn, e(phi + lambda) * co], + ]; + single(u, a, n) + } + 9 => { + // R(φ, θ) = cos(θ/2)·I − i sin(θ/2)·(cos φ·X + sin φ·Y). + s.r(a, phi, theta); + let (sn, co) = (theta / 2.0).sin_cos(); + let off = |x: f64| c(0.0, -sn) * C::from_polar(1.0, x); + single([[c(co, 0.0), off(-phi)], [off(phi), c(co, 0.0)]], a, n) + } + _ => { + let [w0, w1] = s + .state() + .clone() + .z_weights(&mut s.tableau().clone().virtual_view(), a); + let p1 = probability_one(&v, a); + assert!( + (w1 / (w0 + w1) - p1).abs() < 1e-9, + "round {round} step {step}: P(1) simulator {}, state {p1}", + w1 / (w0 + w1) + ); + stabilizer_measurements += usize::from(s.state().active().is_empty()); + let outcome = s.measure(a).expect("no loss"); + assert!( + (if outcome { p1 } else { 1.0 - p1 }) > 1e-9, + "round {round} step {step}: sampled an impossible outcome" + ); + project(&mut v, a, outcome); + Mat::identity(n) + } + }; + retired += axes_before.saturating_sub(s.state().active().len()); + v = apply_to_state(&m, &v); + max_axes = max_axes.max(s.state().active().len()); + let chi = virtual_state(&s); + for code in 0..1usize << (2 * n) { + let (from_sim, from_state) = ( + state_expectation(&chi, &conjugated(s.tableau(), code, &paulis)), + state_expectation(&v, &paulis.table[code]), + ); + assert!( + (from_sim - from_state).norm() < 1e-9, + "round {round} step {step}: Pauli {code:#b}: simulator {from_sim}, state {from_state}" + ); + } + } + } + assert_eq!(max_axes, n, "the circuits activate every qubit"); + assert!(retired > 0, "measurements retire active axes"); + assert!( + stabilizer_measurements > 0, + "some measurements see a stabilizer state" + ); +} + +/// Asymmetric loss against its Kraus operators on random three-qubit states +/// from Cliffords and `T`: the survival branch equals `K₀|v⟩/‖K₀|v⟩‖` with +/// `K₀ = √(1−p0)|0⟩⟨0| + √(1−p1)|1⟩⟨1|`, a loss branch equals `|v⟩` projected +/// onto some `|m⟩` with `q` reset, `|χ⟩` stays normalized, and losses occur +/// with probability `p0·P(0) + p1·P(1)`. +#[test] +fn asymmetric_loss_matches_the_kraus_operators() { + let n = 3; + let gates = all_gates(n); + let paulis = Paulis::new(n); + let x = gate_matrices()[0]; + let w = C::from_polar(1.0, std::f64::consts::FRAC_PI_4); + let mut seed = 0x6a09_e667_f3bc_c908u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as usize + }; + let (mut expected, mut variance, mut observed) = (0.0, 0.0, 0); + for round in 0..600 { + let (p0, p1) = [(0.15, 0.6), (0.3, 0.3), (0.0, 1.0)][round % 3]; + let mut s = Sim::new_with_seed(n, round as u64); + let mut v = vec![C::default(); 1 << n]; + v[0] = c(1.0, 0.0); + for _ in 0..12 { + let q = next() % n; + let m = if next() % 3 == 0 { + s.t(q); + single([[c(1.0, 0.0), c(0.0, 0.0)], [c(0.0, 0.0), w]], q, n) + } else { + let gate = gates[next() % gates.len()]; + apply(&mut s, gate); + matrix(gate, n) + }; + v = apply_to_state(&m, &v); + } + let q = next() % n; + let pop = [1.0 - probability_one(&v, q), probability_one(&v, q)]; + let p_lost = p0 * pop[0] + p1 * pop[1]; + (expected, variance) = (expected + p_lost, variance + p_lost * (1.0 - p_lost)); + + s.asymmetric_loss_channel(q, p0, p1); + + let candidates: Vec> = if s.is_lost(q) { + observed += 1; + [false, true] + .into_iter() + .filter(|&m| pop[usize::from(m)] > 1e-9) + .map(|m| { + let mut u = v.clone(); + project(&mut u, q, m); + if m { + u = apply_to_state(&single(x, q, n), &u); + } + u + }) + .collect() + } else { + let (s0, s1) = ((1.0 - p0).sqrt(), (1.0 - p1).sqrt()); + let k0 = single([[c(s0, 0.0), c(0.0, 0.0)], [c(0.0, 0.0), c(s1, 0.0)]], q, n); + let mut u = apply_to_state(&k0, &v); + let norm = u.iter().map(|a| a.norm_sqr()).sum::().sqrt(); + u.iter_mut().for_each(|a| *a /= norm); + vec![u] + }; + let chi = virtual_state(&s); + let norm: f64 = chi.iter().map(|a| a.norm_sqr()).sum(); + assert!((norm - 1.0).abs() < 1e-9, "round {round}: ‖χ‖² = {norm}"); + let matches = |u: &Vec| { + (0..1usize << (2 * n)).all(|code| { + let from_sim = state_expectation(&chi, &conjugated(s.tableau(), code, &paulis)); + (from_sim - state_expectation(u, &paulis.table[code])).norm() < 1e-9 + }) + }; + assert!( + candidates.iter().any(matches), + "round {round}: lost = {}, the state matches no Kraus branch", + s.is_lost(q) + ); + } + assert!( + (observed as f64 - expected).abs() < 5.0 * variance.sqrt(), + "{observed} losses, {expected:.1} expected" + ); +} diff --git a/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs b/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs index 674bce625..9c59d2714 100644 --- a/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs +++ b/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: 2026 The PPVM Authors // SPDX-License-Identifier: Apache-2.0 -//! [`ApplyGateRule`]: the one trait a Pauli container implements to get [`Clifford`]. +//! [`ApplyGateRule`]: the one trait a type implements to get [`Clifford`]. //! -//! The gate formulas live once, in `ppvm_pauli_kernels::heisenberg`. A container -//! only says how to visit its bits: it receives a whole rule and runs it in its +//! The gate formulas live once, in `ppvm_pauli_kernels::heisenberg`. A type +//! only says how to apply a rule: it receives a whole rule and runs it in its //! own loop, so every gate stays a single fused pass. The blanket impl below //! maps each gate to its rule. @@ -12,18 +12,27 @@ use ppvm_pauli_kernels::{Bits, heisenberg}; use super::Clifford; -/// A container of Pauli operators that can run a Heisenberg gate rule on them. +/// A type that applies a Clifford gate given by its Heisenberg rule. /// -/// For each Pauli it holds, `apply1(q, rule)` reads that Pauli's bits at qubit -/// `q` as `(x, z)`, calls `rule`, writes the returned bits back, and multiplies -/// the Pauli's sign by `(−1)^flip`. With `B = bool` the container visits its -/// Paulis one at a time; with an integer `B` each bit position is a separate -/// Pauli. A container without signs ignores the flip. +/// `apply1(q, rule)` applies the gate whose rule is `rule` (it maps `P` to +/// `G† P G`) at qubit `q`; `apply2` does the same for two qubits. How depends on +/// the type: /// -/// With `B = bool`, `apply1` and `apply2` must call `rule` exactly once if they -/// apply the gate, and not at all if they skip it (e.g. on a lost site). Check -/// for loss before calling `rule`. Wrappers such as `Phased` take the sign flip -/// from that one call, so an extra or early call gives a wrong sign. +/// - A container of Pauli operators reads each Pauli's bits at `q` as `(x, z)`, +/// calls `rule`, writes the returned bits back, and multiplies the Pauli's sign +/// by `(−1)^flip`. With `B = bool` it visits its Paulis one at a time; with an +/// integer `B` each bit position is a separate Pauli. A container without +/// signs ignores the flip. +/// - Other types may evaluate `rule` on fixed inputs instead, e.g. an inverse +/// tableau evaluates it on the gate's generators to find which rows to +/// multiply. +/// +/// A container of Pauli operators with `B = bool` must call `rule` exactly once +/// in `apply1` and `apply2` if it applies the gate, and not at all if it skips +/// it (e.g. on a lost site). Check for loss before calling `rule`. Wrappers such +/// as `Phased` take the sign flip from that one call, so an extra or early call +/// gives a wrong sign. Types that evaluate `rule` on fixed inputs are not +/// bound by this and cannot be wrapped that way. /// /// Implementing this trait gives [`Clifford`] through the blanket impl, so a /// type must not also implement [`Clifford`] by hand. @@ -31,11 +40,11 @@ pub trait ApplyGateRule { /// The value one rule call works on: `bool` or a bit-sliced integer. type B: Bits; - /// Run a one-qubit rule on qubit `q`. + /// Apply a one-qubit rule at qubit `q`. fn apply1(&mut self, q: usize, rule: impl Fn(Self::B, Self::B) -> ([Self::B; 2], Self::B)); - /// Run a two-qubit rule on the bits `[x_a, z_a, x_b, z_b]`. For controlled - /// gates `a` is the control. + /// Apply a two-qubit rule at qubits `a`, `b`; the rule's bits are + /// `[x_a, z_a, x_b, z_b]`. For controlled gates `a` is the control. fn apply2( &mut self, a: usize, diff --git a/crates/ppvm-traits-2/src/gates/channel.rs b/crates/ppvm-traits-2/src/gates/channel.rs index 3ab12f9f9..dac3f15aa 100644 --- a/crates/ppvm-traits-2/src/gates/channel.rs +++ b/crates/ppvm-traits-2/src/gates/channel.rs @@ -130,7 +130,24 @@ pub trait ResetLossChannel { /// The total loss probability depends on the populations, so the channel reads `⟨Z⟩`. pub trait AsymmetricLossChannel { /// Apply asymmetric loss to `qubit`, with `p0` / `p1` the loss probabilities - /// from `|0⟩` / `|1⟩`. See the backend impl for the trajectory approximation - /// used (the survival back-action is omitted). + /// from `|0⟩` / `|1⟩`. Backends document whether they apply the survival + /// back-action. fn asymmetric_loss_channel(&mut self, qubit: usize, p0: C, p1: C); } + +/// Single-qubit leakage: with probability `p0` the qubit leaks and is pinned to +/// `|0⟩`, with `p1` to `|1⟩`. A leaked qubit stays measurable and returns the +/// pinned bit; gates skip it. +pub trait LeakageChannel { + /// Apply leakage to `qubit`, with `p0` / `p1` the probabilities of leaking + /// into `|0⟩` / `|1⟩`. + fn leakage_channel(&mut self, qubit: usize, p0: C, p1: C); +} + +/// Return a leaked qubit to the computational subspace in `|0⟩`, modelling a +/// leakage-reduction step. +pub trait ResetLeakageChannel { + /// Clear leakage at `qubit` and reset it to `|0⟩`. No-op on a live qubit; a + /// lost qubit is not recovered. + fn reset_leakage_channel(&mut self, qubit: usize); +} diff --git a/crates/ppvm-traits-2/src/gates/clifford.rs b/crates/ppvm-traits-2/src/gates/clifford.rs index 431f21f4d..74f6167f4 100644 --- a/crates/ppvm-traits-2/src/gates/clifford.rs +++ b/crates/ppvm-traits-2/src/gates/clifford.rs @@ -2,7 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 /// The Clifford gate set, applied in the Heisenberg picture. -/// Consumers implement the gate methods directly; aliases delegate to those methods. +/// +/// Every gate acts by its Heisenberg rule `P ↦ G† P G`; where the gate composes +/// sets the call order. Pauli words and sums apply it to their evolved operators, +/// outside the gates seen so far, so a circuit is fed last gate first. An inverse +/// tableau applies it to the fixed generators, inside, so a circuit is fed in order. +/// +/// Types get this trait from [`ApplyGateRule`](super::ApplyGateRule) through its +/// blanket impl; aliases delegate to the gate methods. pub trait Clifford { /// Apply Pauli `X` to one qubit. fn x(&mut self, qubit: usize); diff --git a/crates/ppvm-traits-2/src/gates/mod.rs b/crates/ppvm-traits-2/src/gates/mod.rs index d2df415c5..253fba25d 100644 --- a/crates/ppvm-traits-2/src/gates/mod.rs +++ b/crates/ppvm-traits-2/src/gates/mod.rs @@ -12,7 +12,8 @@ mod rot; pub use apply_gate_rule::ApplyGateRule; pub use channel::{ AmplitudeDamping, AsymmetricLossChannel, CorrelatedLossChannel, Depolarizing, Depolarizing2, - LossChannel, PauliError, ResetLossChannel, TwoQubitPauliError, + LeakageChannel, LossChannel, PauliError, ResetLeakageChannel, ResetLossChannel, + TwoQubitPauliError, }; pub use clifford::{Clifford, CliffordBatch}; pub use measure::{Measure, Projection, Reset, ResetState}; diff --git a/crates/ppvm-traits-2/src/lib.rs b/crates/ppvm-traits-2/src/lib.rs index 56842b500..65ea43520 100644 --- a/crates/ppvm-traits-2/src/lib.rs +++ b/crates/ppvm-traits-2/src/lib.rs @@ -21,9 +21,10 @@ pub use containers::{ }; pub use gates::{ AmplitudeDamping, ApplyGateRule, AsymmetricLossChannel, Bits, CRx, Clifford, CliffordBatch, - CorrelatedLossChannel, Depolarizing, Depolarizing2, LossChannel, Measure, PauliError, - Projection, Reset, ResetLossChannel, ResetState, RotXY, RotationOne, RotationOneBatch, - RotationTwo, RotationTwoBatch, TGate, TwoQubitPauliError, U3Gate, + CorrelatedLossChannel, Depolarizing, Depolarizing2, LeakageChannel, LossChannel, Measure, + PauliError, Projection, Reset, ResetLeakageChannel, ResetLossChannel, ResetState, RotXY, + RotationOne, RotationOneBatch, RotationTwo, RotationTwoBatch, TGate, TwoQubitPauliError, + U3Gate, }; pub use loss::{LossState, LossySite}; pub use pauli::Pauli; diff --git a/scripts/fetch_clifft_bench.sh b/scripts/fetch_clifft_bench.sh new file mode 100755 index 000000000..32937b74a --- /dev/null +++ b/scripts/fetch_clifft_bench.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Fetch clifft-bench workload circuits into target/clifft-bench/ (not committed). +set -euo pipefail +dest="$(git rev-parse --show-toplevel)/target/clifft-bench" +mkdir -p "$dest" +base=https://raw.githubusercontent.com/unitaryfoundation/clifft-bench/main/workloads/circuits +for name in "${@:-pure_surface_d7_r7_p1e-3}"; do + curl -fsSL "$base/$name.stim" -o "$dest/$name.stim" + echo "$dest/$name.stim" +done diff --git a/scripts/samply_top.py b/scripts/samply_top.py old mode 100644 new mode 100755