Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
25877c1
feat(ppvm-tableau-2): add the inverse tableau with physical gates
david-pl Nov 11, 2026
e60089f
perf(ppvm-tableau-2): fuse each physical gate into one pass
david-pl Nov 11, 2026
ae2cf03
refactor(ppvm-tableau-2): share the bit split and name the word product
david-pl Nov 11, 2026
6317ecc
feat(ppvm-tableau-2): add changes of basis on virtual qubits
david-pl Nov 11, 2026
10b0a52
refactor(ppvm-tableau-2): split the inverse tableau into a module
david-pl Nov 11, 2026
facff5f
feat(ppvm-tableau-2): measure and reset the stabilizer state
david-pl Nov 11, 2026
c95c3de
perf(ppvm-tableau-2): cut physical-gate bookkeeping; add a Stim harness
david-pl Nov 11, 2026
1b5afe0
refactor(ppvm-tableau-2): rename virtual_side to virtual
david-pl Nov 11, 2026
9276d04
refactor(ppvm-tableau-2): name the gate modules physical_gates and vi…
david-pl Nov 11, 2026
790c8af
perf(ppvm-tableau-2): fuse the pivot fan-out into one pass
david-pl Nov 11, 2026
ffcf16b
bench(ppvm-tableau-2): add microbenchmark circuits
david-pl Nov 11, 2026
5d3eef1
perf(ppvm-tableau-2): multiply rows in place when the pattern allows
david-pl Nov 11, 2026
ea825b7
bench(ppvm-tableau-2): add an all-gates microbenchmark
david-pl Nov 11, 2026
c4bf473
perf(ppvm-tableau-2): let each gate's row pattern fold to constants
david-pl Nov 11, 2026
f31acf1
perf(ppvm-tableau-2): check gate qubits instead of rows
david-pl Nov 11, 2026
184b6b5
perf(ppvm-tableau-2): tighten the strided column updates
david-pl Nov 11, 2026
50e192b
feat(ppvm-tableau-2): add measure_many and CliffordBatch
david-pl Nov 11, 2026
cbdd79f
test(ppvm-tableau-2): avoid a clippy false positive in measure_many test
david-pl Nov 11, 2026
21e6b3c
test(ppvm-tableau-2): allow a clippy false positive in measure_many test
david-pl Nov 11, 2026
5c53a29
perf(ppvm-tableau-2): batch random collapses on a column-major copy
david-pl Nov 11, 2026
da76493
bench(ppvm-tableau-2): port the Stim comparison from PR 236
david-pl Nov 11, 2026
1ad3b2d
bench(ppvm-tableau-2): compare against a native Stim build
david-pl Nov 11, 2026
2022ef2
feat(ppvm-tableau-2): add the active state with a dense backend
david-pl Nov 11, 2026
94d5ee3
feat(ppvm-tableau-2): add GeneralizedTableau over a VirtualState
david-pl Nov 12, 2026
f94103b
feat(ppvm-tableau-2): add T and Pauli rotations with localization
david-pl Nov 13, 2026
f36bc8e
feat(ppvm-tableau-2): measure with active qubits
david-pl Nov 13, 2026
487d2d7
refactor(ppvm-tableau-2): implement Measure and Reset on GeneralizedT…
david-pl Nov 13, 2026
a3fc560
feat(ppvm-tableau-2): add rotation, U3 and Pauli-noise traits to Gene…
david-pl Nov 13, 2026
96e0b31
bench(ppvm-tableau-2): add a clifft-bench runner on GeneralizedTableau
david-pl Nov 13, 2026
2288b46
bench(ppvm-tableau-2): add the clifft-bench comparison script
david-pl Nov 16, 2026
0e08ea0
docs(ppvm-tableau-2): drop the design-doc reference from the crate docs
david-pl Nov 16, 2026
66c4421
refactor(ppvm-tableau-2): drop the unused truncation_error hook
david-pl Nov 16, 2026
e07221e
feat(ppvm-traits-2): add leakage channel traits
david-pl Nov 16, 2026
31b15a5
feat(ppvm-tableau-2): track lost qubits and skip gates on them
david-pl Nov 16, 2026
303ef98
feat(ppvm-tableau-2): add leakage and leakage reduction
david-pl Nov 16, 2026
7512393
refactor(ppvm-tableau-2): move GeneralizedTableau into data.rs
david-pl Nov 16, 2026
249a2f4
feat(ppvm-tableau-2): add correlated loss
david-pl Nov 16, 2026
3567165
feat(ppvm-tableau-2): add asymmetric loss with its survival back-action
david-pl Nov 16, 2026
3c63093
perf(ppvm-tableau-2): skip the survival rotation when p0 == p1
david-pl Nov 16, 2026
f58b335
feat(ppvm-tableau-2): add Display for the simulator and its parts
david-pl Nov 16, 2026
6fee2ec
chore(ppvm-tableau-2): mark unpublished and drop the version
david-pl Nov 16, 2026
c525666
feat(ppvm-tableau-2): add fork to GeneralizedTableau
david-pl Nov 16, 2026
8566728
perf(ppvm-tableau-2): split the fan-out on the pivot's X bit
david-pl Nov 16, 2026
9411c15
perf(ppvm-tableau-2): measure on the tableau alone with no active qubits
david-pl Nov 16, 2026
4489784
perf(ppvm-tableau-2): batch measurements on GeneralizedTableau
david-pl Nov 16, 2026
b11e9cc
chore(ppvm-tableau-2): drop the Stim driver source and its README
david-pl Nov 16, 2026
63860be
Remove stim files
david-pl Nov 18, 2026
56c076f
perf(ppvm-tableau-2): batch live targets in measure_many with lost qu…
david-pl Nov 18, 2026
bd381b1
bench(ppvm-tableau-2): add --loss to run_clifft
david-pl Nov 18, 2026
98cc632
fix(ppvm-tableau-2): keep dense branch weights non-negative
david-pl Nov 18, 2026
9275f14
fix(ppvm-tableau-2): range-check qubits in apply_sign1, ix and iz
david-pl Nov 18, 2026
db75eb3
docs(ppvm-traits-2): limit the call-rule-once contract to Pauli conta…
david-pl Nov 18, 2026
0b37e19
perf(ppvm-tableau-2): skip-sample batched one-qubit Pauli channels
david-pl Nov 18, 2026
2e47c09
perf(ppvm-tableau-2): skip-sample batched two-qubit Pauli channels
david-pl Nov 18, 2026
754e90b
bench(ppvm-tableau-2): batch noise instructions in run_clifft
david-pl Nov 18, 2026
d33ccc0
perf(ppvm-tableau-2): transpose four 64x64 blocks at once
david-pl Nov 18, 2026
d52b3fe
perf(ppvm-tableau-2): scan only the X words in the transposed iz_x_su…
david-pl Nov 18, 2026
60dcf57
docs(ppvm-traits-2): explain gate order across Clifford implementors
david-pl Nov 19, 2026
27be797
refactor(ppvm-tableau-2): rename Rotation to RotationCollapse
david-pl Nov 19, 2026
7bb9f38
fix(ppvm-tableau-2): revive lost qubits on MR in run_clifft
david-pl Nov 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions crates/ppvm-tableau-2/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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" }
1 change: 1 addition & 0 deletions crates/ppvm-tableau-2/benches/circuits/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.stim
52 changes: 52 additions & 0 deletions crates/ppvm-tableau-2/benches/circuits/gen.py
Original file line number Diff line number Diff line change
@@ -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])
56 changes: 56 additions & 0 deletions crates/ppvm-tableau-2/benches/stim-compare/circuits.py
Original file line number Diff line number Diff line change
@@ -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
84 changes: 84 additions & 0 deletions crates/ppvm-tableau-2/benches/stim-compare/clifft.py
Original file line number Diff line number Diff line change
@@ -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()
58 changes: 58 additions & 0 deletions crates/ppvm-tableau-2/benches/stim-compare/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Running the timing tools: a ppvm example (`run_stim`, `run_clifft`) and
reference binaries with the same CLI (`<tool> <circuit> <shots>`, printing
`<x> µs/shot` or `<x> 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))))
62 changes: 62 additions & 0 deletions crates/ppvm-tableau-2/benches/stim-compare/gates.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading