From 5d23d7db871065c77aa5499cd498300a59bbe252 Mon Sep 17 00:00:00 2001 From: David Plankensteiner Date: Tue, 10 Nov 2026 14:58:31 +0100 Subject: [PATCH 1/7] Add ppvm-pauli-kernels: shared Clifford rules and Pauli row product MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dependency-free crate with the bit-level kernels that Pauli containers share: - `Bits`: the bitwise operators plus `popcount`, for `bool` and the unsigned integers. An integer holds one independent Pauli per bit. - `heisenberg`: one fused rule per Clifford gate (X, Y, Z, H, S, S†, √X, √X†, √Y, √Y†, CX, CZ, CY) for `P ↦ G† P G`, returning the new X/Z bits and a sign-flip mask. - `row_product` / `row_product_phase`: the packed Pauli-word product and the exponent of its iᵏ phase. Rows up to 8 words use an iterator loop and longer rows an indexed one, which benchmarked fastest on each side (arm64). The formulas are proved in a new core-Lean project (`lean/`, no Mathlib) against exact Gaussian-integer gate matrices: each rule equals G† P G, every gate is unitary, and the product phase matches the matrix product per site, on two sites, and as a popcount sum for any length. The Rust tests check the code against tables generated from that matrix model (`mise run lean-tables`) plus algebraic invariants. `lean/README.md` lists what the proofs do not cover. `mise.toml` gains elan and the `lean-build` / `lean-tables` tasks. Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 4 + Cargo.toml | 2 +- crates/ppvm-pauli-kernels/Cargo.toml | 12 ++ crates/ppvm-pauli-kernels/src/bits.rs | 38 ++++ crates/ppvm-pauli-kernels/src/heisenberg.rs | 103 +++++++++++ crates/ppvm-pauli-kernels/src/lib.rs | 31 ++++ crates/ppvm-pauli-kernels/src/product.rs | 86 +++++++++ crates/ppvm-pauli-kernels/tests/common/mod.rs | 27 +++ .../tests/generated/tables.rs | 154 ++++++++++++++++ crates/ppvm-pauli-kernels/tests/product.rs | 151 ++++++++++++++++ crates/ppvm-pauli-kernels/tests/rules.rs | 171 ++++++++++++++++++ lean/.gitignore | 1 + lean/PPVM.lean | 3 + lean/PPVM/Kernels/Model.lean | 158 ++++++++++++++++ lean/PPVM/Kernels/RowProduct.lean | 57 ++++++ lean/PPVM/Kernels/Rules.lean | 119 ++++++++++++ lean/README.md | 77 ++++++++ lean/lake-manifest.json | 6 + lean/lakefile.toml | 11 ++ lean/lean-toolchain | 1 + lean/scripts/GenTables.lean | 88 +++++++++ mise.toml | 18 ++ 22 files changed, 1317 insertions(+), 1 deletion(-) create mode 100644 crates/ppvm-pauli-kernels/Cargo.toml create mode 100644 crates/ppvm-pauli-kernels/src/bits.rs create mode 100644 crates/ppvm-pauli-kernels/src/heisenberg.rs create mode 100644 crates/ppvm-pauli-kernels/src/lib.rs create mode 100644 crates/ppvm-pauli-kernels/src/product.rs create mode 100644 crates/ppvm-pauli-kernels/tests/common/mod.rs create mode 100644 crates/ppvm-pauli-kernels/tests/generated/tables.rs create mode 100644 crates/ppvm-pauli-kernels/tests/product.rs create mode 100644 crates/ppvm-pauli-kernels/tests/rules.rs create mode 100644 lean/.gitignore create mode 100644 lean/PPVM.lean create mode 100644 lean/PPVM/Kernels/Model.lean create mode 100644 lean/PPVM/Kernels/RowProduct.lean create mode 100644 lean/PPVM/Kernels/Rules.lean create mode 100644 lean/README.md create mode 100644 lean/lake-manifest.json create mode 100644 lean/lakefile.toml create mode 100644 lean/lean-toolchain create mode 100644 lean/scripts/GenTables.lean diff --git a/Cargo.lock b/Cargo.lock index b6c938c04..1f88df32e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2214,6 +2214,10 @@ dependencies = [ "ppvm-traits-2", ] +[[package]] +name = "ppvm-pauli-kernels" +version = "0.3.0" + [[package]] name = "ppvm-pauli-sum" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index e0410d99f..ff106b1a7 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", + "skills/ppvm-usage/examples/rust", "crates/ppvm-lossy-pauli-word-2", "crates/ppvm-phased-pauli-word-2", "crates/ppvm-pauli-kernels", ] # Single version for every crate and the `bloqade-ppvm` Python package diff --git a/crates/ppvm-pauli-kernels/Cargo.toml b/crates/ppvm-pauli-kernels/Cargo.toml new file mode 100644 index 000000000..81bc2ff7f --- /dev/null +++ b/crates/ppvm-pauli-kernels/Cargo.toml @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2026 The PPVM Authors +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "ppvm-pauli-kernels" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[dependencies] diff --git a/crates/ppvm-pauli-kernels/src/bits.rs b/crates/ppvm-pauli-kernels/src/bits.rs new file mode 100644 index 000000000..6121846c9 --- /dev/null +++ b/crates/ppvm-pauli-kernels/src/bits.rs @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The value types the kernels run on. + +use std::ops::{BitAnd, BitOr, BitXor, Not}; + +/// A value supporting the Boolean operations the kernels use. +/// +/// `bool` holds one Pauli's bit; an integer holds one bit per position, each +/// position an independent Pauli. The operations act bitwise, so a rule on an +/// integer is the rule applied to each bit position. +pub trait Bits: + Copy + BitAnd + BitOr + BitXor + Not +{ + /// The number of set bits. + fn popcount(self) -> u32; // needs its own method since no rust trait guarantees this; can't use num::PrimInt because of bool +} + +impl Bits for bool { + #[inline(always)] + fn popcount(self) -> u32 { + self as u32 + } +} + +macro_rules! impl_int { + ($($t:ty),*) => {$( + impl Bits for $t { + #[inline(always)] + fn popcount(self) -> u32 { + self.count_ones() + } + } + )*}; +} + +impl_int!(u8, u16, u32, u64, u128, usize); diff --git a/crates/ppvm-pauli-kernels/src/heisenberg.rs b/crates/ppvm-pauli-kernels/src/heisenberg.rs new file mode 100644 index 000000000..3549f6cf5 --- /dev/null +++ b/crates/ppvm-pauli-kernels/src/heisenberg.rs @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! One update rule per Clifford gate, in the Heisenberg picture `P ↦ G† P G`. +//! +//! A one-qubit rule takes the pre-gate bits `(x, z)` and returns +//! `([x', z'], flip)` with `G† P G = (−1)^flip · P'`. A two-qubit rule takes +//! `[x_a, z_a, x_b, z_b]` (for controlled gates `a` is the control) and returns +//! the four new bits and the flip. +//! +//! Each rule is named for its gate `G`, so `s` computes `S† P S`. For a forward +//! update `G P G†`, use the rule of `G†` (e.g. `s_dag` for an `S` gate); the +//! self-inverse gates X, Y, Z, H, CX, CZ, CY are the same in both directions. +//! +//! Bits encode the Hermitian Paulis I = (0,0), X = (1,0), Z = (0,1), +//! Y = (1,1); `S† X S = −Y`. +//! +//! Each rule is proved against its gate matrix in +//! `lean/PPVM/Kernels/Rules.lean`; the theorem is named on each function. + +use crate::Bits; + +/// `X`: sign flip where the Pauli has a Z. (`ruleX_correct`) +#[inline(always)] +pub fn x(x: B, z: B) -> ([B; 2], B) { + ([x, z], z) +} + +/// `Y`: sign flip where the Pauli has exactly one of X, Z. (`ruleY_correct`) +#[inline(always)] +pub fn y(x: B, z: B) -> ([B; 2], B) { + ([x, z], x ^ z) +} + +/// `Z`: sign flip where the Pauli has an X. (`ruleZ_correct`) +#[inline(always)] +pub fn z(x: B, z: B) -> ([B; 2], B) { + ([x, z], x) +} + +/// `H`: swaps X and Z; `Y ↦ −Y`. (`ruleH_correct`) +#[inline(always)] +pub fn h(x: B, z: B) -> ([B; 2], B) { + ([z, x], x & z) +} + +/// `S† P S`: `X ↦ −Y`, `Y ↦ X`. (`ruleS_correct`) +#[inline(always)] +pub fn s(x: B, z: B) -> ([B; 2], B) { + ([x, z ^ x], x & !z) +} + +/// `S P S†`: `X ↦ Y`, `Y ↦ −X`. (`ruleSdag_correct`) +#[inline(always)] +pub fn s_dag(x: B, z: B) -> ([B; 2], B) { + ([x, z ^ x], x & z) +} + +/// `√X† P √X`: `Y ↦ −Z`, `Z ↦ Y`. (`ruleSqrtX_correct`) +#[inline(always)] +pub fn sqrt_x(x: B, z: B) -> ([B; 2], B) { + ([x ^ z, z], x & z) +} + +/// `√X P √X†`: `Y ↦ Z`, `Z ↦ −Y`. (`ruleSqrtXdag_correct`) +#[inline(always)] +pub fn sqrt_x_dag(x: B, z: B) -> ([B; 2], B) { + ([x ^ z, z], !x & z) +} + +/// `√Y† P √Y`: `X ↦ Z`, `Z ↦ −X`. (`ruleSqrtY_correct`) +#[inline(always)] +pub fn sqrt_y(x: B, z: B) -> ([B; 2], B) { + ([z, x], !x & z) +} + +/// `√Y P √Y†`: `X ↦ −Z`, `Z ↦ X`. (`ruleSqrtYdag_correct`) +#[inline(always)] +pub fn sqrt_y_dag(x: B, z: B) -> ([B; 2], B) { + ([z, x], x & !z) +} + +/// `CX` with control `c` and target `t`: `z_c ^= z_t`, `x_t ^= x_c`. +/// (`ruleCnot_correct`) +#[inline(always)] +pub fn cnot([xc, zc, xt, zt]: [B; 4]) -> ([B; 4], B) { + ([xc, zc ^ zt, xt ^ xc, zt], xc & zt & !(xt ^ zc)) +} + +/// `CZ` on `a`, `b`: `z_a ^= x_b`, `z_b ^= x_a`. (`ruleCz_correct`) +#[inline(always)] +pub fn cz([xa, za, xb, zb]: [B; 4]) -> ([B; 4], B) { + ([xa, za ^ xb, xb, zb ^ xa], xa & xb & (za ^ zb)) +} + +/// `CY` with control `c` and target `t`. (`ruleCy_correct`) +#[inline(always)] +pub fn cy([xc, zc, xt, zt]: [B; 4]) -> ([B; 4], B) { + ( + [xc, zc ^ xt ^ zt, xt ^ xc, zt ^ xc], + xc & (xt ^ zt) & !(zc ^ zt), + ) +} diff --git a/crates/ppvm-pauli-kernels/src/lib.rs b/crates/ppvm-pauli-kernels/src/lib.rs new file mode 100644 index 000000000..ff8112aab --- /dev/null +++ b/crates/ppvm-pauli-kernels/src/lib.rs @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Bit-level Pauli kernels shared by every PPVM container that conjugates or +//! multiplies Pauli operators. +//! +//! - [`heisenberg`]: one Boolean update rule per Clifford gate, in the +//! Heisenberg picture `P ↦ G† P G` (so `heisenberg::s` computes `S† P S`). +//! A rule maps the pre-gate X/Z bits of a Pauli to its post-gate bits and a +//! sign-flip mask. It is generic over [`Bits`], so the same formula updates +//! one Pauli (`bool`) or 64 at once (`u64`, one per bit position). +//! - [`row_product`] / [`row_product_phase`]: the packed Pauli-word product and +//! the exponent `k` of the phase `iᵏ` it emits. +//! +//! The crate has no PPVM dependencies; containers wire the rules into their own +//! loops. +//! +//! # Verification +//! +//! The formulas are proved in `lean/PPVM/Kernels/` against exact Gaussian-integer +//! matrices: each rule equals `G† P G` for its gate, and the product phase +//! equals the matrix product's. The tests in `tests/` compare the Rust code +//! against tables generated from that matrix model. `lean/README.md` lists +//! what is not covered by the proofs. + +mod bits; +pub mod heisenberg; +mod product; + +pub use bits::Bits; +pub use product::{row_product, row_product_phase}; diff --git a/crates/ppvm-pauli-kernels/src/product.rs b/crates/ppvm-pauli-kernels/src/product.rs new file mode 100644 index 000000000..9190d0ef8 --- /dev/null +++ b/crates/ppvm-pauli-kernels/src/product.rs @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The packed Pauli-word product and its phase. +//! +//! For words `P = ⊗ p_k`, `Q = ⊗ q_k` stored as X/Z bit planes, +//! `P · Q = iᵏ · ⊗ (p_k ⊕ q_k)`. Each site contributes `2·sign + imag` to `k` +//! (`site_product` in `lean/PPVM/Kernels/RowProduct.lean`), so `k` is +//! `2·popcount(sign) + popcount(imag)` mod 4 (`popcount_exponent`). Unused +//! (padding) bits must be zero; zero sites contribute nothing and stay zero. + +use crate::Bits; + +/// Rows up to this many words use an iterator loop, longer rows an indexed one. +/// Measured on arm64: the iterator loop is faster on short rows, the indexed +/// loop (which LLVM unrolls further) on long rows. +const SHORT_ROW: usize = 8; + +/// The `(sign, imag)` masks for `p = (a, b)`, `q = (c, d)`. +#[inline(always)] +fn masks(a: W, b: W, c: W, d: W) -> (W, W) { + let sign = (a & b & c & !d) | (a & !b & !c & d) | (!a & b & c & d); + let imag = (a & !b & d) | (a & !c & d) | (!a & b & c) | (b & c & !d); + (sign, imag) +} + +/// The exponent `k mod 4` from the mask counts. 4 divides 2³², so wrapping is exact. +#[inline(always)] +fn exponent(sign_count: u32, imag_count: u32) -> u8 { + (sign_count.wrapping_mul(2).wrapping_add(imag_count) % 4) as u8 +} + +/// `dst ← dst · src`. Returns `k ∈ 0..4` with `dst · src = iᵏ · (dst ⊕ src)`. +/// +/// All four slices must have the same length. +#[inline] +pub fn row_product(dst_x: &mut [W], dst_z: &mut [W], src_x: &[W], src_z: &[W]) -> u8 { + debug_assert!( + dst_x.len() == dst_z.len() && src_x.len() == dst_x.len() && src_z.len() == dst_x.len() + ); + let mut sign_count = 0u32; + let mut imag_count = 0u32; + if dst_x.len() <= SHORT_ROW { + for (((dx, dz), &sx), &sz) in dst_x.iter_mut().zip(dst_z.iter_mut()).zip(src_x).zip(src_z) { + let (sign, imag) = masks(*dx, *dz, sx, sz); + sign_count = sign_count.wrapping_add(sign.popcount()); + imag_count = imag_count.wrapping_add(imag.popcount()); + *dx = *dx ^ sx; + *dz = *dz ^ sz; + } + } else { + for i in 0..dst_x.len() { + let (a, b, c, d) = (dst_x[i], dst_z[i], src_x[i], src_z[i]); + let (sign, imag) = masks(a, b, c, d); + sign_count = sign_count.wrapping_add(sign.popcount()); + imag_count = imag_count.wrapping_add(imag.popcount()); + dst_x[i] = a ^ c; + dst_z[i] = b ^ d; + } + } + exponent(sign_count, imag_count) +} + +/// The phase exponent of `a · b` without computing the product's bits. +/// +/// All four slices must have the same length. +#[inline] +pub fn row_product_phase(a_x: &[W], a_z: &[W], b_x: &[W], b_z: &[W]) -> u8 { + debug_assert!(a_x.len() == a_z.len() && b_x.len() == a_x.len() && b_z.len() == a_x.len()); + let mut sign_count = 0u32; + let mut imag_count = 0u32; + if a_x.len() <= SHORT_ROW { + for (((&ax, &az), &bx), &bz) in a_x.iter().zip(a_z).zip(b_x).zip(b_z) { + let (sign, imag) = masks(ax, az, bx, bz); + sign_count = sign_count.wrapping_add(sign.popcount()); + imag_count = imag_count.wrapping_add(imag.popcount()); + } + } else { + for i in 0..a_x.len() { + let (sign, imag) = masks(a_x[i], a_z[i], b_x[i], b_z[i]); + sign_count = sign_count.wrapping_add(sign.popcount()); + imag_count = imag_count.wrapping_add(imag.popcount()); + } + } + exponent(sign_count, imag_count) +} diff --git a/crates/ppvm-pauli-kernels/tests/common/mod.rs b/crates/ppvm-pauli-kernels/tests/common/mod.rs new file mode 100644 index 000000000..08cf3059b --- /dev/null +++ b/crates/ppvm-pauli-kernels/tests/common/mod.rs @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Shared test helpers. + +#![allow(dead_code)] + +/// SplitMix64: a small deterministic generator, so tests need no dependency. +pub struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Self { + Self(seed) + } + + pub fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + pub fn words(&mut self, len: usize) -> Vec { + (0..len).map(|_| self.next_u64()).collect() + } +} diff --git a/crates/ppvm-pauli-kernels/tests/generated/tables.rs b/crates/ppvm-pauli-kernels/tests/generated/tables.rs new file mode 100644 index 000000000..5f2009326 --- /dev/null +++ b/crates/ppvm-pauli-kernels/tests/generated/tables.rs @@ -0,0 +1,154 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +// @generated by lean/scripts/GenTables.lean from the matrix model in +// lean/PPVM/Kernels/Model.lean. Do not edit by hand. +// +// One-qubit rows: [x, z, x', z', flip] with G† P G = (−1)^flip · P'. +// Two-qubit rows: [xa, za, xb, zb, xa', za', xb', zb', flip]. + +pub const X: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, false, true, true], + [true, false, true, false, false], + [true, true, true, true, true], +]; + +pub const Y: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, false, true, true], + [true, false, true, false, true], + [true, true, true, true, false], +]; + +pub const Z: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, false, true, false], + [true, false, true, false, true], + [true, true, true, true, true], +]; + +pub const H: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, true, false, false], + [true, false, false, true, false], + [true, true, true, true, true], +]; + +pub const S: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, false, true, false], + [true, false, true, true, true], + [true, true, true, false, false], +]; + +pub const S_DAG: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, false, true, false], + [true, false, true, true, false], + [true, true, true, false, true], +]; + +pub const SQRT_X: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, true, true, false], + [true, false, true, false, false], + [true, true, false, true, true], +]; + +pub const SQRT_X_DAG: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, true, true, true], + [true, false, true, false, false], + [true, true, false, true, false], +]; + +pub const SQRT_Y: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, true, false, true], + [true, false, false, true, false], + [true, true, true, true, false], +]; + +pub const SQRT_Y_DAG: [[bool; 5]; 4] = [ + [false, false, false, false, false], + [false, true, true, false, false], + [true, false, false, true, true], + [true, true, true, true, false], +]; + +pub const CX: [[bool; 9]; 16] = [ + [false, false, false, false, false, false, false, false, false], + [false, false, false, true, false, true, false, true, false], + [false, false, true, false, false, false, true, false, false], + [false, false, true, true, false, true, true, true, false], + [false, true, false, false, false, true, false, false, false], + [false, true, false, true, false, false, false, true, false], + [false, true, true, false, false, true, true, false, false], + [false, true, true, true, false, false, true, true, false], + [true, false, false, false, true, false, true, false, false], + [true, false, false, true, true, true, true, true, true], + [true, false, true, false, true, false, false, false, false], + [true, false, true, true, true, true, false, true, false], + [true, true, false, false, true, true, true, false, false], + [true, true, false, true, true, false, true, true, false], + [true, true, true, false, true, true, false, false, false], + [true, true, true, true, true, false, false, true, true], +]; + +pub const CZ: [[bool; 9]; 16] = [ + [false, false, false, false, false, false, false, false, false], + [false, false, false, true, false, false, false, true, false], + [false, false, true, false, false, true, true, false, false], + [false, false, true, true, false, true, true, true, false], + [false, true, false, false, false, true, false, false, false], + [false, true, false, true, false, true, false, true, false], + [false, true, true, false, false, false, true, false, false], + [false, true, true, true, false, false, true, true, false], + [true, false, false, false, true, false, false, true, false], + [true, false, false, true, true, false, false, false, false], + [true, false, true, false, true, true, true, true, false], + [true, false, true, true, true, true, true, false, true], + [true, true, false, false, true, true, false, true, false], + [true, true, false, true, true, true, false, false, false], + [true, true, true, false, true, false, true, true, true], + [true, true, true, true, true, false, true, false, false], +]; + +pub const CY: [[bool; 9]; 16] = [ + [false, false, false, false, false, false, false, false, false], + [false, false, false, true, false, true, false, true, false], + [false, false, true, false, false, true, true, false, false], + [false, false, true, true, false, false, true, true, false], + [false, true, false, false, false, true, false, false, false], + [false, true, false, true, false, false, false, true, false], + [false, true, true, false, false, false, true, false, false], + [false, true, true, true, false, true, true, true, false], + [true, false, false, false, true, false, true, true, false], + [true, false, false, true, true, true, true, false, false], + [true, false, true, false, true, true, false, true, true], + [true, false, true, true, true, false, false, false, false], + [true, true, false, false, true, true, true, true, false], + [true, true, false, true, true, false, true, false, true], + [true, true, true, false, true, false, false, true, false], + [true, true, true, true, true, true, false, false, false], +]; + +pub const SITE_PRODUCT: [([bool; 4], u8); 16] = [ + ([false, false, false, false], 0), + ([false, false, false, true], 0), + ([false, false, true, false], 0), + ([false, false, true, true], 0), + ([false, true, false, false], 0), + ([false, true, false, true], 0), + ([false, true, true, false], 1), + ([false, true, true, true], 3), + ([true, false, false, false], 0), + ([true, false, false, true], 3), + ([true, false, true, false], 0), + ([true, false, true, true], 1), + ([true, true, false, false], 0), + ([true, true, false, true], 1), + ([true, true, true, false], 3), + ([true, true, true, true], 0), +]; diff --git a/crates/ppvm-pauli-kernels/tests/product.rs b/crates/ppvm-pauli-kernels/tests/product.rs new file mode 100644 index 000000000..b69241c63 --- /dev/null +++ b/crates/ppvm-pauli-kernels/tests/product.rs @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The row product against the matrix-model site table, and group invariants. + +mod common; +#[allow(dead_code)] +#[path = "generated/tables.rs"] +#[rustfmt::skip] +mod tables; + +use common::Rng; +use ppvm_pauli_kernels::{row_product, row_product_phase}; + +/// A Pauli word on `64 · len` qubits as X and Z planes. +#[derive(Clone, PartialEq, Debug)] +struct Row { + x: Vec, + z: Vec, +} + +impl Row { + fn random(rng: &mut Rng, len: usize) -> Self { + Self { + x: rng.words(len), + z: rng.words(len), + } + } + + /// `self ← self · other`, returning the phase exponent. + fn mul_assign(&mut self, other: &Row) -> u8 { + row_product(&mut self.x, &mut self.z, &other.x, &other.z) + } +} + +/// Row lengths in words, on both sides of the kernel's short/long-row switch (8 words). +const LENS: [usize; 7] = [1, 2, 5, 8, 9, 16, 64]; + +fn site_exponent(a: bool, b: bool, c: bool, d: bool) -> u8 { + tables::SITE_PRODUCT + .iter() + .find(|(k, _)| *k == [a, b, c, d]) + .unwrap() + .1 +} + +#[test] +fn single_site_matches_matrix_model() { + for ([a, b, c, d], e) in tables::SITE_PRODUCT { + let (mut x, mut z) = ([a as u8], [b as u8]); + let k = row_product(&mut x, &mut z, &[c as u8], &[d as u8]); + assert_eq!(k, e, "site {:?}", [a, b, c, d]); + assert_eq!((x[0], z[0]), ((a ^ c) as u8, (b ^ d) as u8)); + } +} + +#[test] +fn phase_is_sum_of_site_phases() { + let mut rng = Rng::new(3); + for len in LENS { + let (p, q) = (Row::random(&mut rng, len), Row::random(&mut rng, len)); + let mut expected = 0u32; + for w in 0..len { + for i in 0..64 { + let bit = |v: &[u64]| (v[w] >> i) & 1 == 1; + expected += site_exponent(bit(&p.x), bit(&p.z), bit(&q.x), bit(&q.z)) as u32; + } + } + let mut prod = p.clone(); + let k = prod.mul_assign(&q); + assert_eq!(k as u32, expected % 4); + let xor = |a: &[u64], b: &[u64]| a.iter().zip(b).map(|(a, b)| a ^ b).collect::>(); + assert_eq!( + prod, + Row { + x: xor(&p.x, &q.x), + z: xor(&p.z, &q.z) + } + ); + assert_eq!(row_product_phase(&p.x, &p.z, &q.x, &q.z), k); + } +} + +#[test] +fn product_is_associative_with_phase() { + let mut rng = Rng::new(5); + for len in LENS { + let (a, b, c) = ( + Row::random(&mut rng, len), + Row::random(&mut rng, len), + Row::random(&mut rng, len), + ); + let mut left = a.clone(); + let k1 = left.mul_assign(&b); + let k2 = left.mul_assign(&c); + let mut bc = b.clone(); + let k3 = bc.mul_assign(&c); + let mut right = a.clone(); + let k4 = right.mul_assign(&bc); + assert_eq!(left, right); + assert_eq!((k1 + k2) % 4, (k3 + k4) % 4); + } +} + +#[test] +fn hermitian_paulis_square_to_identity() { + let mut rng = Rng::new(9); + for len in LENS { + let p = Row::random(&mut rng, len); + let mut sq = p.clone(); + assert_eq!(sq.mul_assign(&p), 0); + assert!(sq.x.iter().chain(&sq.z).all(|&w| w == 0)); + } +} + +#[test] +fn commutator_phase_is_symplectic_form() { + let mut rng = Rng::new(13); + for len in LENS { + let (a, b) = (Row::random(&mut rng, len), Row::random(&mut rng, len)); + let omega: u32 = (0..len) + .map(|w| ((a.x[w] & b.z[w]) ^ (a.z[w] & b.x[w])).count_ones()) + .sum::() + % 2; + let kab = row_product_phase(&a.x, &a.z, &b.x, &b.z) as u32; + let kba = row_product_phase(&b.x, &b.z, &a.x, &a.z) as u32; + assert_eq!((kab + 4 - kba) % 4, 2 * omega); + } +} + +/// Zero words change nothing. Padding a row from 8 to 9 or 16 words also moves it +/// from the short-row loop to the long-row loop, so this compares the two. +#[test] +fn padding_bits_contribute_nothing() { + let mut rng = Rng::new(17); + for len in LENS { + let (p, q) = (Row::random(&mut rng, len), Row::random(&mut rng, len)); + let k = row_product_phase(&p.x, &p.z, &q.x, &q.z); + for padded in [len + 1, 2 * len, len + 9] { + let pad = |v: &[u64]| { + let mut w = v.to_vec(); + w.resize(padded, 0); + w + }; + let (mut px, mut pz) = (pad(&p.x), pad(&p.z)); + assert_eq!(row_product_phase(&px, &pz, &pad(&q.x), &pad(&q.z)), k); + assert_eq!(row_product(&mut px, &mut pz, &pad(&q.x), &pad(&q.z)), k); + assert!(px[len..].iter().chain(&pz[len..]).all(|&w| w == 0)); + } + } +} diff --git a/crates/ppvm-pauli-kernels/tests/rules.rs b/crates/ppvm-pauli-kernels/tests/rules.rs new file mode 100644 index 000000000..5fe4d2a9b --- /dev/null +++ b/crates/ppvm-pauli-kernels/tests/rules.rs @@ -0,0 +1,171 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The rules against the matrix-model tables, and integer widths against `bool`. + +mod common; +#[allow(dead_code)] +#[path = "generated/tables.rs"] +#[rustfmt::skip] +mod tables; + +use common::Rng; +use ppvm_pauli_kernels::{Bits, heisenberg}; + +type Rule1 = fn(B, B) -> ([B; 2], B); +type Rule2 = fn([B; 4]) -> ([B; 4], B); +/// A gate's name, its rule at two widths, and its matrix-model table. +type Case1 = ( + &'static str, + Rule1, + Rule1, + &'static [[bool; 5]; 4], +); +type Case2 = ( + &'static str, + Rule2, + Rule2, + &'static [[bool; 9]; 16], +); + +fn one_qubit() -> [Case1; 10] { + [ + ("X", heisenberg::x, heisenberg::x, &tables::X), + ("Y", heisenberg::y, heisenberg::y, &tables::Y), + ("Z", heisenberg::z, heisenberg::z, &tables::Z), + ("H", heisenberg::h, heisenberg::h, &tables::H), + ("S", heisenberg::s, heisenberg::s, &tables::S), + ( + "S_DAG", + heisenberg::s_dag, + heisenberg::s_dag, + &tables::S_DAG, + ), + ( + "SQRT_X", + heisenberg::sqrt_x, + heisenberg::sqrt_x, + &tables::SQRT_X, + ), + ( + "SQRT_X_DAG", + heisenberg::sqrt_x_dag, + heisenberg::sqrt_x_dag, + &tables::SQRT_X_DAG, + ), + ( + "SQRT_Y", + heisenberg::sqrt_y, + heisenberg::sqrt_y, + &tables::SQRT_Y, + ), + ( + "SQRT_Y_DAG", + heisenberg::sqrt_y_dag, + heisenberg::sqrt_y_dag, + &tables::SQRT_Y_DAG, + ), + ] +} + +fn two_qubit() -> [Case2; 3] { + [ + ("CX", heisenberg::cnot, heisenberg::cnot, &tables::CX), + ("CZ", heisenberg::cz, heisenberg::cz, &tables::CZ), + ("CY", heisenberg::cy, heisenberg::cy, &tables::CY), + ] +} + +#[test] +fn one_qubit_rules_match_matrix_model() { + for (name, rule, _, table) in one_qubit() { + for row in table { + let (bits, flip) = rule(row[0], row[1]); + assert_eq!( + (bits, flip), + ([row[2], row[3]], row[4]), + "{name} on {:?}", + &row[..2] + ); + } + } +} + +#[test] +fn two_qubit_rules_match_matrix_model() { + for (name, rule, _, table) in two_qubit() { + for row in table { + let (bits, flip) = rule([row[0], row[1], row[2], row[3]]); + assert_eq!( + (bits, flip), + ([row[4], row[5], row[6], row[7]], row[8]), + "{name} on {:?}", + &row[..4] + ); + } + } +} + +fn bit(w: u64, i: usize) -> bool { + (w >> i) & 1 == 1 +} + +#[test] +fn u64_rules_equal_bool_rules_per_bit() { + let mut rng = Rng::new(7); + for _ in 0..64 { + let [x, z] = [rng.next_u64(), rng.next_u64()]; + for (name, rule_b, rule_w, _) in one_qubit() { + let ([xw, zw], fw) = rule_w(x, z); + for i in 0..64 { + let expect = rule_b(bit(x, i), bit(z, i)); + assert_eq!( + ([bit(xw, i), bit(zw, i)], bit(fw, i)), + expect, + "{name} bit {i}" + ); + } + } + let input = [ + rng.next_u64(), + rng.next_u64(), + rng.next_u64(), + rng.next_u64(), + ]; + for (name, rule_b, rule_w, _) in two_qubit() { + let (out, fw) = rule_w(input); + for i in 0..64 { + let expect = rule_b(input.map(|w| bit(w, i))); + assert_eq!( + (out.map(|w| bit(w, i)), bit(fw, i)), + expect, + "{name} bit {i}" + ); + } + } + } +} + +/// The rules only use `Bits`, so narrower integers behave like `u64`. +fn narrow_matches + TryFrom>(rng: &mut Rng) +where + >::Error: std::fmt::Debug, +{ + let mask = |w: u64| w & (u64::MAX >> (64 - 8 * std::mem::size_of::())); + let to_b = |w: u64| B::try_from(mask(w)).unwrap(); + let (x, z) = (rng.next_u64(), rng.next_u64()); + let (out, f) = heisenberg::cy([to_b(x), to_b(z), to_b(!x), to_b(z ^ x)]); + let (out_w, f_w) = heisenberg::cy([x, z, !x, z ^ x]); + assert_eq!(out.map(Into::into), out_w.map(mask)); + assert_eq!(f.into(), mask(f_w)); +} + +#[test] +fn narrow_integer_rules_equal_u64_rules() { + let mut rng = Rng::new(11); + for _ in 0..64 { + narrow_matches::(&mut rng); + narrow_matches::(&mut rng); + narrow_matches::(&mut rng); + } +} diff --git a/lean/.gitignore b/lean/.gitignore new file mode 100644 index 000000000..bfb30ec8c --- /dev/null +++ b/lean/.gitignore @@ -0,0 +1 @@ +/.lake diff --git a/lean/PPVM.lean b/lean/PPVM.lean new file mode 100644 index 000000000..3ef5f6b6c --- /dev/null +++ b/lean/PPVM.lean @@ -0,0 +1,3 @@ +import PPVM.Kernels.Model +import PPVM.Kernels.Rules +import PPVM.Kernels.RowProduct diff --git a/lean/PPVM/Kernels/Model.lean b/lean/PPVM/Kernels/Model.lean new file mode 100644 index 000000000..95e73d1be --- /dev/null +++ b/lean/PPVM/Kernels/Model.lean @@ -0,0 +1,158 @@ +/- +Copyright (c) 2026 The PPVM Authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: The PPVM Authors +-/ +/-! +The ground-truth model for `ppvm-pauli-kernels`: exact matrices over the +Gaussian integers, the Pauli matrices, and every supported Clifford gate as a +scaled unitary `G = M / √c` with Gaussian-integer entries. + +Everything here is computable, so all facts about it are checked by `decide` +in the kernel. No Mathlib. +-/ + +namespace PPVM.Kernels + +/-! ## Gaussian integers -/ + +/-- `re + im·i` with integer parts. -/ +structure GI where + re : Int + im : Int + deriving DecidableEq, Repr + +namespace GI + +def zero : GI := ⟨0, 0⟩ +def one : GI := ⟨1, 0⟩ +def I : GI := ⟨0, 1⟩ +def ofInt (n : Int) : GI := ⟨n, 0⟩ + +def add (a b : GI) : GI := ⟨a.re + b.re, a.im + b.im⟩ +def neg (a : GI) : GI := ⟨-a.re, -a.im⟩ +def mul (a b : GI) : GI := ⟨a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re⟩ +def conj (a : GI) : GI := ⟨a.re, -a.im⟩ + +instance : Add GI := ⟨add⟩ +instance : Neg GI := ⟨neg⟩ +instance : Mul GI := ⟨mul⟩ +instance : OfNat GI 0 := ⟨zero⟩ +instance : OfNat GI 1 := ⟨one⟩ + +/-- `iᵏ` for `k` taken modulo four. -/ +def iPow (k : Nat) : GI := + match k % 4 with + | 0 => ⟨1, 0⟩ + | 1 => ⟨0, 1⟩ + | 2 => ⟨-1, 0⟩ + | _ => ⟨0, -1⟩ + +end GI + +/-! ## Matrices -/ + +/-- An `n × n` matrix with Gaussian-integer entries. -/ +abbrev Mat (n : Nat) := Fin n → Fin n → GI + +namespace Mat + +/-- Row-major entries, for decidable equality and printing. -/ +def toList {n : Nat} (A : Mat n) : List (List GI) := + (List.finRange n).map fun i => (List.finRange n).map fun j => A i j + +def mul {n : Nat} (A B : Mat n) : Mat n := + fun i j => (List.finRange n).foldl (fun acc k => acc + A i k * B k j) 0 + +/-- Conjugate transpose. -/ +def adj {n : Nat} (A : Mat n) : Mat n := fun i j => (A j i).conj + +def smul {n : Nat} (c : GI) (A : Mat n) : Mat n := fun i j => c * A i j + +def id (n : Nat) : Mat n := fun i j => if i = j then 1 else 0 + +/-- Kronecker product; the first factor is the more significant index bit. -/ +def kron (A B : Mat 2) : Mat 4 := + fun i j => + A ⟨i.val / 2, by omega⟩ ⟨j.val / 2, by omega⟩ * B ⟨i.val % 2, by omega⟩ ⟨j.val % 2, by omega⟩ + +def of2 (a b c d : GI) : Mat 2 := + fun i j => + match i.val, j.val with + | 0, 0 => a | 0, _ => b | _, 0 => c | _, _ => d + +def of4 (rows : List (List GI)) : Mat 4 := + fun i j => (rows.getD i.val []).getD j.val 0 + +end Mat + +/-- Matrix equality, decided on entries. -/ +def Mat.Eq {n : Nat} (A B : Mat n) : Prop := A.toList = B.toList + +instance {n : Nat} (A B : Mat n) : Decidable (Mat.Eq A B) := + inferInstanceAs (Decidable (A.toList = B.toList)) + +/-! ## Paulis -/ + +/-- `(−1)^f` as a Gaussian integer. -/ +def sgn (f : Bool) : GI := if f then ⟨-1, 0⟩ else ⟨1, 0⟩ + +/-- The Hermitian Pauli with bits `(x, z)`: I = (0,0), X = (1,0), Z = (0,1), +and the Hermitian Y = (1,1) (not `XZ`). -/ +def pauli (x z : Bool) : Mat 2 := + match x, z with + | false, false => Mat.of2 1 0 0 1 + | true, false => Mat.of2 0 1 1 0 + | false, true => Mat.of2 1 0 0 ⟨-1, 0⟩ + | true, true => Mat.of2 0 ⟨0, -1⟩ ⟨0, 1⟩ 0 + +/-- A two-qubit Pauli; `(xa, za)` is the more significant qubit. -/ +def pauli2 (xa za xb zb : Bool) : Mat 4 := Mat.kron (pauli xa za) (pauli xb zb) + +/-! ## Gates + +Each gate is `G = M / √c` for an integer matrix `M` with `M† M = c · I` +(proved in `Rules.lean`). The Heisenberg action is then +`G† P G = (M† P M) / c`. -/ + +/-- A gate as a scaled unitary: `G = mat / √scale`. -/ +structure Gate (n : Nat) where + mat : Mat n + scale : Int + +def gX : Gate 2 := ⟨pauli true false, 1⟩ +def gY : Gate 2 := ⟨pauli true true, 1⟩ +def gZ : Gate 2 := ⟨pauli false true, 1⟩ +def gH : Gate 2 := ⟨Mat.of2 1 1 1 ⟨-1, 0⟩, 2⟩ +def gS : Gate 2 := ⟨Mat.of2 1 0 0 ⟨0, 1⟩, 1⟩ +def gSdag : Gate 2 := ⟨Mat.of2 1 0 0 ⟨0, -1⟩, 1⟩ +/-- `√X = ½ [[1+i, 1−i], [1−i, 1+i]]`. -/ +def gSqrtX : Gate 2 := ⟨Mat.of2 ⟨1, 1⟩ ⟨1, -1⟩ ⟨1, -1⟩ ⟨1, 1⟩, 4⟩ +def gSqrtXdag : Gate 2 := ⟨Mat.of2 ⟨1, -1⟩ ⟨1, 1⟩ ⟨1, 1⟩ ⟨1, -1⟩, 4⟩ +/-- `√Y = ½ [[1+i, −1−i], [1+i, 1+i]]`. -/ +def gSqrtY : Gate 2 := ⟨Mat.of2 ⟨1, 1⟩ ⟨-1, -1⟩ ⟨1, 1⟩ ⟨1, 1⟩, 4⟩ +def gSqrtYdag : Gate 2 := ⟨Mat.of2 ⟨1, -1⟩ ⟨1, -1⟩ ⟨-1, 1⟩ ⟨1, -1⟩, 4⟩ + +private def o : GI := 1 +private def z : GI := 0 +private def m : GI := ⟨-1, 0⟩ + +/-- `CX` with the control as the more significant qubit. -/ +def gCX : Gate 4 := ⟨Mat.of4 [[o, z, z, z], [z, o, z, z], [z, z, z, o], [z, z, o, z]], 1⟩ +def gCZ : Gate 4 := ⟨Mat.of4 [[o, z, z, z], [z, o, z, z], [z, z, o, z], [z, z, z, m]], 1⟩ +/-- `CY = |0⟩⟨0| ⊗ I + |1⟩⟨1| ⊗ Y`. -/ +def gCY : Gate 4 := + ⟨Mat.of4 [[o, z, z, z], [z, o, z, z], [z, z, z, ⟨0, -1⟩], [z, z, ⟨0, 1⟩, z]], 1⟩ + +/-- `M† M = c · I`: the gate is unitary after scaling. -/ +def Gate.Unitary {n : Nat} (g : Gate n) : Prop := + Mat.Eq (Mat.mul (Mat.adj g.mat) g.mat) (Mat.smul (GI.ofInt g.scale) (Mat.id n)) + +instance {n : Nat} (g : Gate n) : Decidable g.Unitary := + inferInstanceAs (Decidable (Mat.Eq _ _)) + +/-- `M† P M`, which is `c · G† P G`. -/ +def Gate.heis {n : Nat} (g : Gate n) (P : Mat n) : Mat n := + Mat.mul (Mat.adj g.mat) (Mat.mul P g.mat) + +end PPVM.Kernels diff --git a/lean/PPVM/Kernels/RowProduct.lean b/lean/PPVM/Kernels/RowProduct.lean new file mode 100644 index 000000000..0a13921b2 --- /dev/null +++ b/lean/PPVM/Kernels/RowProduct.lean @@ -0,0 +1,57 @@ +/- +Copyright (c) 2026 The PPVM Authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: The PPVM Authors +-/ +import PPVM.Kernels.Model + +/-! +The phase of the packed Pauli-word product in `ppvm-pauli-kernels` +(`crates/ppvm-pauli-kernels/src/product.rs`, `row_product`). + +For words `P = ⊗ p_k` and `Q = ⊗ q_k` the product is `P · Q = iᵉ · ⊗ (p_k ⊕ q_k)`. +The kernel computes two masks per site, `sign` and `imag`, and returns +`e = (2 · popcount(sign) + popcount(imag)) mod 4`. +-/ + +namespace PPVM.Kernels + +/-- The `sign` mask at one site, for `p = (a, b)` and `q = (c, d)`. -/ +def siteSign (a b c d : Bool) : Bool := + (a && b && c && !d) || (a && !b && !c && d) || (!a && b && c && d) + +/-- The `imag` mask at one site. -/ +def siteImag (a b c d : Bool) : Bool := + (a && !b && d) || (a && !c && d) || (!a && b && c) || (b && c && !d) + +/-- The phase exponent one site contributes. -/ +def siteExp (a b c d : Bool) : Nat := 2 * (siteSign a b c d).toNat + (siteImag a b c d).toNat + +/-- One site: `p · q = i^{siteExp} · (p ⊕ q)`, against the Pauli matrices. -/ +theorem site_product : ∀ a b c d : Bool, + Mat.Eq (Mat.mul (pauli a b) (pauli c d)) + (Mat.smul (GI.iPow (siteExp a b c d)) (pauli (a ^^ c) (b ^^ d))) := by + decide + +/-- Two sites: the exponents add across a tensor product (all 256 cases). -/ +theorem two_site_product : ∀ a b a' b' c d c' d' : Bool, + Mat.Eq (Mat.mul (pauli2 a b a' b') (pauli2 c d c' d')) + (Mat.smul (GI.iPow (siteExp a b c d + siteExp a' b' c' d')) + (pauli2 (a ^^ c) (b ^^ d) (a' ^^ c') (b' ^^ d'))) := by + decide + +/-- Any width: summing the per-site exponents is what the popcounts compute. +A site is `(a, b, c, d)`; `countP` is the popcount of the mask. -/ +theorem popcount_exponent (sites : List (Bool × Bool × Bool × Bool)) : + 2 * sites.countP (fun s => siteSign s.1 s.2.1 s.2.2.1 s.2.2.2) + + sites.countP (fun s => siteImag s.1 s.2.1 s.2.2.1 s.2.2.2) + = (sites.map fun s => siteExp s.1 s.2.1 s.2.2.1 s.2.2.2).sum := by + induction sites with + | nil => simp + | cons s rest ih => + rw [List.countP_cons, List.countP_cons, List.map_cons, List.sum_cons, ← ih] + unfold siteExp + cases siteSign s.1 s.2.1 s.2.2.1 s.2.2.2 <;> + cases siteImag s.1 s.2.1 s.2.2.1 s.2.2.2 <;> simp <;> omega + +end PPVM.Kernels diff --git a/lean/PPVM/Kernels/Rules.lean b/lean/PPVM/Kernels/Rules.lean new file mode 100644 index 000000000..c7dae7db7 --- /dev/null +++ b/lean/PPVM/Kernels/Rules.lean @@ -0,0 +1,119 @@ +/- +Copyright (c) 2026 The PPVM Authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: The PPVM Authors +-/ +import PPVM.Kernels.Model + +/-! +The gate rules of `ppvm-pauli-kernels` (`crates/ppvm-pauli-kernels/src/heisenberg.rs`), +transcribed one-to-one as Boolean functions, and proved equal to the +Heisenberg conjugation `G† P G` computed from the gate matrices in `Model.lean`. + +A rule maps the pre-gate bits of one Pauli to its post-gate bits and a sign +flip `f`, meaning `G† P G = (−1)^f · P'`. Inputs are listed in the Rust order: +`(x, z)` for one qubit, `(x_a, z_a, x_b, z_b)` for two. +-/ + +namespace PPVM.Kernels + +/-- A one-qubit rule: `(x, z) ↦ ((x', z'), flip)`. -/ +abbrev Rule1 := Bool → Bool → (Bool × Bool) × Bool + +/-- A two-qubit rule: `(x_a, z_a, x_b, z_b) ↦ ((x_a', z_a', x_b', z_b'), flip)`. -/ +abbrev Rule2 := Bool → Bool → Bool → Bool → (Bool × Bool × Bool × Bool) × Bool + +/-- `rule` is the Heisenberg action of `g` on every one-qubit Pauli. -/ +def Correct1 (g : Gate 2) (rule : Rule1) : Prop := + ∀ x z : Bool, + Mat.Eq (g.heis (pauli x z)) + (Mat.smul (GI.ofInt g.scale * sgn (rule x z).2) (pauli (rule x z).1.1 (rule x z).1.2)) + +/-- `rule` is the Heisenberg action of `g` on every two-qubit Pauli. -/ +def Correct2 (g : Gate 4) (rule : Rule2) : Prop := + ∀ xa za xb zb : Bool, + let r := rule xa za xb zb + Mat.Eq (g.heis (pauli2 xa za xb zb)) + (Mat.smul (GI.ofInt g.scale * sgn r.2) (pauli2 r.1.1 r.1.2.1 r.1.2.2.1 r.1.2.2.2)) + +instance (g : Gate 2) (rule : Rule1) : Decidable (Correct1 g rule) := by + unfold Correct1; infer_instance + +instance (g : Gate 4) (rule : Rule2) : Decidable (Correct2 g rule) := by + unfold Correct2; infer_instance + +/-! ## The rules, as in `heisenberg.rs` -/ + +def ruleX : Rule1 := fun x z => ((x, z), z) +def ruleY : Rule1 := fun x z => ((x, z), x ^^ z) +def ruleZ : Rule1 := fun x z => ((x, z), x) +def ruleH : Rule1 := fun x z => ((z, x), x && z) +def ruleS : Rule1 := fun x z => ((x, z ^^ x), x && !z) +def ruleSdag : Rule1 := fun x z => ((x, z ^^ x), x && z) +def ruleSqrtX : Rule1 := fun x z => ((x ^^ z, z), x && z) +def ruleSqrtXdag : Rule1 := fun x z => ((x ^^ z, z), !x && z) +def ruleSqrtY : Rule1 := fun x z => ((z, x), !x && z) +def ruleSqrtYdag : Rule1 := fun x z => ((z, x), x && !z) + +def ruleCnot : Rule2 := fun xc zc xt zt => + ((xc, zc ^^ zt, xt ^^ xc, zt), xc && zt && !(xt ^^ zc)) +def ruleCz : Rule2 := fun xa za xb zb => + ((xa, za ^^ xb, xb, zb ^^ xa), xa && xb && (za ^^ zb)) +def ruleCy : Rule2 := fun xc zc xt zt => + ((xc, zc ^^ xt ^^ zt, xt ^^ xc, zt ^^ xc), xc && (xt ^^ zt) && !(zc ^^ zt)) + +/-! ## The gates are unitary after scaling -/ + +theorem gX_unitary : gX.Unitary := by decide +theorem gY_unitary : gY.Unitary := by decide +theorem gZ_unitary : gZ.Unitary := by decide +theorem gH_unitary : gH.Unitary := by decide +theorem gS_unitary : gS.Unitary := by decide +theorem gSdag_unitary : gSdag.Unitary := by decide +theorem gSqrtX_unitary : gSqrtX.Unitary := by decide +theorem gSqrtXdag_unitary : gSqrtXdag.Unitary := by decide +theorem gSqrtY_unitary : gSqrtY.Unitary := by decide +theorem gSqrtYdag_unitary : gSqrtYdag.Unitary := by decide +theorem gCX_unitary : gCX.Unitary := by decide +theorem gCZ_unitary : gCZ.Unitary := by decide +theorem gCY_unitary : gCY.Unitary := by decide + +/-! ## Each rule is its gate's conjugation -/ + +theorem ruleX_correct : Correct1 gX ruleX := by decide +theorem ruleY_correct : Correct1 gY ruleY := by decide +theorem ruleZ_correct : Correct1 gZ ruleZ := by decide +theorem ruleH_correct : Correct1 gH ruleH := by decide +theorem ruleS_correct : Correct1 gS ruleS := by decide +theorem ruleSdag_correct : Correct1 gSdag ruleSdag := by decide +theorem ruleSqrtX_correct : Correct1 gSqrtX ruleSqrtX := by decide +theorem ruleSqrtXdag_correct : Correct1 gSqrtXdag ruleSqrtXdag := by decide +theorem ruleSqrtY_correct : Correct1 gSqrtY ruleSqrtY := by decide +theorem ruleSqrtYdag_correct : Correct1 gSqrtYdag ruleSqrtYdag := by decide +theorem ruleCnot_correct : Correct2 gCX ruleCnot := by decide +theorem ruleCz_correct : Correct2 gCZ ruleCz := by decide +theorem ruleCy_correct : Correct2 gCY ruleCy := by decide + +/-! ## Sanity: the gate matrices are the intended gates + +The squares pin `√X` and `√Y` (and their daggers) to the right square roots, +and `S² = Z`, so a wrong matrix cannot slip through as "some other Clifford". -/ + +theorem gS_sq : Mat.Eq (Mat.mul gS.mat gS.mat) gZ.mat := by decide +theorem gSdag_mul_gS : Mat.Eq (Mat.mul gSdag.mat gS.mat) (Mat.id 2) := by decide +/-- `(2·√X)² = 4·X`, i.e. `√X² = X`. -/ +theorem gSqrtX_sq : Mat.Eq (Mat.mul gSqrtX.mat gSqrtX.mat) (Mat.smul (GI.ofInt 4) gX.mat) := by decide +theorem gSqrtXdag_mul_gSqrtX : + Mat.Eq (Mat.mul gSqrtXdag.mat gSqrtX.mat) (Mat.smul (GI.ofInt 4) (Mat.id 2)) := by decide +/-- `(2·√Y)² = 4·Y`, i.e. `√Y² = Y`. -/ +theorem gSqrtY_sq : Mat.Eq (Mat.mul gSqrtY.mat gSqrtY.mat) (Mat.smul (GI.ofInt 4) gY.mat) := by decide +theorem gSqrtYdag_mul_gSqrtY : + Mat.Eq (Mat.mul gSqrtYdag.mat gSqrtY.mat) (Mat.smul (GI.ofInt 4) (Mat.id 2)) := by decide +/-- `(√2·H)² = 2·I`, i.e. `H² = I`. -/ +theorem gH_sq : Mat.Eq (Mat.mul gH.mat gH.mat) (Mat.smul (GI.ofInt 2) (Mat.id 2)) := by decide +/-- `CY = (I ⊗ S) · CX · (I ⊗ S†)`. -/ +theorem gCY_eq : Mat.Eq gCY.mat + (Mat.mul (Mat.kron (Mat.id 2) gS.mat) (Mat.mul gCX.mat (Mat.kron (Mat.id 2) gSdag.mat))) := by + decide + +end PPVM.Kernels diff --git a/lean/README.md b/lean/README.md new file mode 100644 index 000000000..947b3f992 --- /dev/null +++ b/lean/README.md @@ -0,0 +1,77 @@ +# PPVM Lean formalization + +Proofs for `crates/ppvm-pauli-kernels`. Core Lean only (no Mathlib); every +fact is decided in the kernel. + +```sh +mise run lean-build # lake build +mise run lean-tables # regenerate crates/ppvm-pauli-kernels/tests/generated/tables.rs +``` + +## What is proved + +`PPVM/Kernels/Model.lean` is the ground truth: exact 2×2 and 4×4 matrices over +the Gaussian integers, the Hermitian Pauli matrices (Y = `[[0, −i], [i, 0]]`), +and each gate as an integer matrix `M` with `G = M / √c`. + +`PPVM/Kernels/Rules.lean`: + +- `g*_unitary`: `M† M = c · I` for all 13 gates, so each `G` is unitary. +- `rule*_correct`: for every input Pauli, the rule's output bits and sign flip + satisfy `G† P G = (−1)^flip · P'`, computed by matrix multiplication. This + covers X, Y, Z, H, S, S†, √X, √X†, √Y, √Y†, CX, CZ, CY. +- Identity checks on the matrices: `S² = Z`, `S† S = I`, `√X² = X`, + `√X† √X = I`, `√Y² = Y`, `√Y† √Y = I`, `H² = I`, and + `CY = (I ⊗ S) · CX · (I ⊗ S†)`. + +`PPVM/Kernels/RowProduct.lean`: + +- `site_product`: at one site, `p · q = i^{2·sign + imag} · (p ⊕ q)`, with the + kernel's `sign` and `imag` masks. +- `two_site_product`: on two sites the exponents add (all 256 cases). +- `popcount_exponent`: for any number of sites, + `2·popcount(sign) + popcount(imag)` equals the sum of the site exponents. + +All theorems depend only on `propext` and `Quot.sound`; none uses `sorry` or +`native_decide`. + +## How the Rust code is tied to the proofs + +The Lean rules are transcriptions of `src/heisenberg.rs`. The Rust tests do not rely +on that transcription: `scripts/GenTables.lean` builds the conjugation and +product tables from the matrix model by searching over all candidate images, +and `tests/rules.rs` and `tests/product.rs` check the Rust code against those +tables on every `bool` input. + +## Gaps + +1. **Rust ↔ Lean transcription.** The rule bodies in `Rules.lean` are copied by + hand from `heisenberg.rs`; nothing links them mechanically. The exhaustive Rust + tests against the generated tables cover the `bool` case independently. +2. **Generated tables.** `GenTables.lean` runs as compiled code (`lean --run`), + so the tables rely on the Lean compiler, not the kernel. The file is checked + in; regenerate it after changing the model. +3. **Integer widths.** That a rule on `u8`…`u128` equals the rule applied to each + bit position follows from Rust's bitwise operators. It is not formalized; + `tests/rules.rs` checks `u64` against per-bit `bool` and narrower widths + against `u64` on random inputs. +4. **Locality.** The proofs are on the one- and two-qubit spaces. That a gate on + sites `a`, `b` of an `n`-qubit word acts as the rule on those sites and as the + identity elsewhere (`G ⊗ I`) is not formalized. +5. **Row product for `n` sites.** One site is proved against matrices, two sites + against the 4×4 tensor product, and the popcount aggregation for any length. + The general `n`-fold tensor-product statement is not formalized. +6. **Word packing and arithmetic.** That the Rust loop's per-word `count_ones` + sums to the per-site count, and that wrapping `u32` arithmetic preserves the + exponent mod 4 (4 divides 2³²), is argued in comments and tested, not proved. +7. **Gate identity.** The matrices are checked for unitarity and the identities + above. That they are the gates PPVM and Stim name `SQRT_Y`, `CY`, … is a + convention, fixed by those identities and the conjugation tables. + +## Relation to #204 + +PR #204 has a separate, Mathlib-based development (`lean/PPVM/Pauli/*`). Its +two-qubit conjugations are defined by their bit and sign formulas and pinned +via the group-homomorphism property and textbook images of the generators. +The proofs here instead compute every conjugation from gate matrices, so no +conjugation table is assumed. diff --git a/lean/lake-manifest.json b/lean/lake-manifest.json new file mode 100644 index 000000000..58b950321 --- /dev/null +++ b/lean/lake-manifest.json @@ -0,0 +1,6 @@ +{"version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "ppvm", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/lean/lakefile.toml b/lean/lakefile.toml new file mode 100644 index 000000000..74a13fb96 --- /dev/null +++ b/lean/lakefile.toml @@ -0,0 +1,11 @@ +name = "ppvm" +version = "0.1.0" +keywords = ["quantum", "pauli", "clifford"] +defaultTargets = ["PPVM"] + +[leanOptions] +pp.unicode.fun = true +relaxedAutoImplicit = false + +[[lean_lib]] +name = "PPVM" diff --git a/lean/lean-toolchain b/lean/lean-toolchain new file mode 100644 index 000000000..18640c8b0 --- /dev/null +++ b/lean/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.31.0 diff --git a/lean/scripts/GenTables.lean b/lean/scripts/GenTables.lean new file mode 100644 index 000000000..1d141e823 --- /dev/null +++ b/lean/scripts/GenTables.lean @@ -0,0 +1,88 @@ +/- +Copyright (c) 2026 The PPVM Authors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: The PPVM Authors +-/ +import PPVM.Kernels.Model + +/-! +Prints `crates/ppvm-pauli-kernels/tests/generated/tables.rs`: the conjugation +and product tables of the matrix model in `PPVM.Kernels.Model`, found by search +over all candidate images. It never reads the rule transcriptions, so the Rust +tests compare the Rust rules against the matrices, not against themselves. + +Run from `lean/`: + lake env lean --run scripts/GenTables.lean > ../crates/ppvm-pauli-kernels/tests/generated/tables.rs +-/ + +open PPVM.Kernels + +def bools : List Bool := [false, true] + +def b (v : Bool) : String := if v then "true" else "false" + +/-- The `(x', z', flip)` with `G† P G = (−1)^flip · P'`, by search. -/ +def image1 (g : Gate 2) (x z : Bool) : Option (Bool × Bool × Bool) := + let cands := bools.flatMap fun x' => bools.flatMap fun z' => bools.map fun f => (x', z', f) + cands.find? fun (x', z', f) => + decide (Mat.Eq (g.heis (pauli x z)) (Mat.smul (GI.ofInt g.scale * sgn f) (pauli x' z'))) + +def image2 (g : Gate 4) (xa za xb zb : Bool) : Option (List Bool) := + let cands := bools.flatMap fun a => bools.flatMap fun c => bools.flatMap fun d => + bools.flatMap fun e => bools.map fun f => [a, c, d, e, f] + cands.find? fun v => + decide (Mat.Eq (g.heis (pauli2 xa za xb zb)) + (Mat.smul (GI.ofInt g.scale * sgn v[4]!) (pauli2 v[0]! v[1]! v[2]! v[3]!))) + +def table1 (name : String) (g : Gate 2) : String := Id.run do + let mut s := s!"pub const {name}: [[bool; 5]; 4] = [\n" + for x in bools do + for z in bools do + match image1 g x z with + | some (x', z', f) => s := s ++ s!" [{b x}, {b z}, {b x'}, {b z'}, {b f}],\n" + | none => s := s ++ " compile_error!(\"no Pauli image\"),\n" + s ++ "];\n" + +def table2 (name : String) (g : Gate 4) : String := Id.run do + let mut s := s!"pub const {name}: [[bool; 9]; 16] = [\n" + for xa in bools do + for za in bools do + for xb in bools do + for zb in bools do + match image2 g xa za xb zb with + | some v => + let row := ([xa, za, xb, zb] ++ v).map b + s := s ++ " [" ++ ", ".intercalate row ++ "],\n" + | none => s := s ++ " compile_error!(\"no Pauli image\"),\n" + s ++ "];\n" + +/-- `(a, b, c, d, e)` with `pauli a b · pauli c d = iᵉ · pauli (a ⊕ c) (b ⊕ d)`. -/ +def siteTable : String := Id.run do + let mut s := "pub const SITE_PRODUCT: [([bool; 4], u8); 16] = [\n" + for a in bools do + for bb in bools do + for c in bools do + for d in bools do + let e := [0, 1, 2, 3].find? fun k => + decide (Mat.Eq (Mat.mul (pauli a bb) (pauli c d)) + (Mat.smul (GI.iPow k) (pauli (a ^^ c) (bb ^^ d)))) + match e with + | some k => s := s ++ s!" ([{b a}, {b bb}, {b c}, {b d}], {k}),\n" + | none => s := s ++ " compile_error!(\"no phase\"),\n" + s ++ "];\n" + +def main : IO Unit := do + IO.print "// SPDX-FileCopyrightText: 2026 The PPVM Authors\n" + IO.print "// SPDX-License-Identifier: Apache-2.0\n\n" + IO.print "// @generated by lean/scripts/GenTables.lean from the matrix model in\n" + IO.print "// lean/PPVM/Kernels/Model.lean. Do not edit by hand.\n" + IO.print "//\n" + IO.print "// One-qubit rows: [x, z, x', z', flip] with G† P G = (−1)^flip · P'.\n" + IO.print "// Two-qubit rows: [xa, za, xb, zb, xa', za', xb', zb', flip].\n\n" + for (n, g) in [("X", gX), ("Y", gY), ("Z", gZ), ("H", gH), ("S", gS), ("S_DAG", gSdag), + ("SQRT_X", gSqrtX), ("SQRT_X_DAG", gSqrtXdag), ("SQRT_Y", gSqrtY), + ("SQRT_Y_DAG", gSqrtYdag)] do + IO.print (table1 n g ++ "\n") + for (n, g) in [("CX", gCX), ("CZ", gCZ), ("CY", gCY)] do + IO.print (table2 n g ++ "\n") + IO.print siteTable diff --git a/mise.toml b/mise.toml index cb7a32d3d..d9b2a932d 100644 --- a/mise.toml +++ b/mise.toml @@ -8,3 +8,21 @@ prek = "0.4.14" "cargo:cargo-machete" = "0.9.2" # Local release preview (`release-plz update`); same version the CI action uses release-plz = "0.3.169" +# Lean toolchain manager. `elan` reads `lean/lean-toolchain` and provisions the +# pinned Lean/Lake proxies into `~/.elan/bin`. +"github:leanprover/elan" = "4.2.4" + +[env] +# Put the elan-managed `lean` / `lake` proxies on PATH for mise tasks and shells. +_.path = ["~/.elan/bin"] + +# Runs inside `lean/` so elan picks up `lean/lean-toolchain`. +[tasks.lean-build] +description = "Build the PPVM Lean formalization (lake build)." +dir = "lean" +run = "lake build" + +[tasks.lean-tables] +description = "Regenerate the ppvm-pauli-kernels test tables from the Lean matrix model." +dir = "lean" +run = "lake env lean --run scripts/GenTables.lean > ../crates/ppvm-pauli-kernels/tests/generated/tables.rs" From 8a23d68e14e28d06b9865624f93df9bd4a0f5e92 Mon Sep 17 00:00:00 2001 From: David Plankensteiner Date: Tue, 10 Nov 2026 15:34:25 +0100 Subject: [PATCH 2/7] Add ApplyGateRule and a blanket Clifford impl to ppvm-traits-2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Pauli container now gets `Clifford` by implementing `ApplyGateRule`: `apply1` and `apply2` run a whole gate rule over its bits in one pass, and `apply_sign1` (defaulting to `apply1`) lets sign-only gates skip the bit writes. The blanket impl maps each of the 13 gates to its rule in `ppvm_pauli_kernels::heisenberg`, so the formulas exist once and the existing Heisenberg convention is kept. The step is additive: nothing implements `ApplyGateRule` yet, and the hand-written `Clifford` impls in the word crates compile unchanged next to the blanket impl. `CliffordBatch` is not blanket-implemented, so containers can still provide fused batch methods. `Bits` is re-exported so containers need not depend on the kernel crate directly. Tests check gate identities through `Clifford` (S² = Z, √X = HSH, CY = (I⊗S)·CX·(I⊗S†), ...) on every signed two-qubit Pauli, and that a bit-sliced u64 container matches 64 single words on random circuits. Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 1 + crates/ppvm-traits-2/Cargo.toml | 1 + .../src/gates/apply_gate_rule.rs | 105 +++++++++ crates/ppvm-traits-2/src/gates/mod.rs | 4 + crates/ppvm-traits-2/src/lib.rs | 8 +- crates/ppvm-traits-2/tests/apply_gate_rule.rs | 216 ++++++++++++++++++ 6 files changed, 331 insertions(+), 4 deletions(-) create mode 100644 crates/ppvm-traits-2/src/gates/apply_gate_rule.rs create mode 100644 crates/ppvm-traits-2/tests/apply_gate_rule.rs diff --git a/Cargo.lock b/Cargo.lock index 1f88df32e..5d2a35594 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2394,6 +2394,7 @@ name = "ppvm-traits-2" version = "0.4.0" dependencies = [ "num", + "ppvm-pauli-kernels", ] [[package]] diff --git a/crates/ppvm-traits-2/Cargo.toml b/crates/ppvm-traits-2/Cargo.toml index 0110c292a..e47a03cba 100644 --- a/crates/ppvm-traits-2/Cargo.toml +++ b/crates/ppvm-traits-2/Cargo.toml @@ -11,3 +11,4 @@ publish = false [dependencies] num = "0.4" +ppvm-pauli-kernels = { path = "../ppvm-pauli-kernels" } diff --git a/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs b/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs new file mode 100644 index 000000000..6b9c7fc57 --- /dev/null +++ b/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! [`ApplyGateRule`]: the one trait a Pauli container 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 +//! own loop, so every gate stays a single fused pass. The blanket impl below +//! maps each gate to its rule. + +use ppvm_pauli_kernels::{Bits, heisenberg}; + +use super::Clifford; + +/// A container of Pauli operators that can run a Heisenberg gate rule on them. +/// +/// 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. +/// +/// Implementing this trait gives [`Clifford`] through the blanket impl, so a +/// type must not also implement [`Clifford`] by hand. +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`. + 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. + fn apply2( + &mut self, + a: usize, + b: usize, + rule: impl Fn([Self::B; 4]) -> ([Self::B; 4], Self::B), + ); + + /// Run a rule that leaves the bits unchanged and only flips signs (X, Y, Z). + /// Override it to skip the bit writes. + fn apply_sign1( + &mut self, + q: usize, + rule: impl Fn(Self::B, Self::B) -> ([Self::B; 2], Self::B), + ) { + self.apply1(q, rule) + } +} + +impl Clifford for T { + #[inline] + fn x(&mut self, qubit: usize) { + self.apply_sign1(qubit, heisenberg::x) + } + #[inline] + fn y(&mut self, qubit: usize) { + self.apply_sign1(qubit, heisenberg::y) + } + #[inline] + fn z(&mut self, qubit: usize) { + self.apply_sign1(qubit, heisenberg::z) + } + #[inline] + fn h(&mut self, qubit: usize) { + self.apply1(qubit, heisenberg::h) + } + #[inline] + fn s(&mut self, qubit: usize) { + self.apply1(qubit, heisenberg::s) + } + #[inline] + fn cnot(&mut self, control: usize, target: usize) { + self.apply2(control, target, heisenberg::cnot) + } + #[inline] + fn cz(&mut self, qubit0: usize, qubit1: usize) { + self.apply2(qubit0, qubit1, heisenberg::cz) + } + #[inline] + fn s_dag(&mut self, qubit: usize) { + self.apply1(qubit, heisenberg::s_dag) + } + #[inline] + fn sqrt_x(&mut self, qubit: usize) { + self.apply1(qubit, heisenberg::sqrt_x) + } + #[inline] + fn sqrt_x_dag(&mut self, qubit: usize) { + self.apply1(qubit, heisenberg::sqrt_x_dag) + } + #[inline] + fn sqrt_y(&mut self, qubit: usize) { + self.apply1(qubit, heisenberg::sqrt_y) + } + #[inline] + fn sqrt_y_dag(&mut self, qubit: usize) { + self.apply1(qubit, heisenberg::sqrt_y_dag) + } + #[inline] + fn cy(&mut self, control: usize, target: usize) { + self.apply2(control, target, heisenberg::cy) + } +} diff --git a/crates/ppvm-traits-2/src/gates/mod.rs b/crates/ppvm-traits-2/src/gates/mod.rs index e645f0c9e..d2df415c5 100644 --- a/crates/ppvm-traits-2/src/gates/mod.rs +++ b/crates/ppvm-traits-2/src/gates/mod.rs @@ -3,17 +3,21 @@ //! Gate, measurement, reset, and noise-channel interfaces. +mod apply_gate_rule; mod channel; mod clifford; mod measure; mod rot; +pub use apply_gate_rule::ApplyGateRule; pub use channel::{ AmplitudeDamping, AsymmetricLossChannel, CorrelatedLossChannel, Depolarizing, Depolarizing2, LossChannel, PauliError, ResetLossChannel, TwoQubitPauliError, }; pub use clifford::{Clifford, CliffordBatch}; pub use measure::{Measure, Projection, Reset, ResetState}; +/// The value type of [`ApplyGateRule`], re-exported so containers need not depend on the kernels. +pub use ppvm_pauli_kernels::Bits; pub use rot::{ CRx, RotXY, RotationOne, RotationOneBatch, RotationTwo, RotationTwoBatch, TGate, U3Gate, }; diff --git a/crates/ppvm-traits-2/src/lib.rs b/crates/ppvm-traits-2/src/lib.rs index a50a56515..27d9c5f57 100644 --- a/crates/ppvm-traits-2/src/lib.rs +++ b/crates/ppvm-traits-2/src/lib.rs @@ -20,10 +20,10 @@ pub use containers::{ TermSink, }; pub use gates::{ - AmplitudeDamping, AsymmetricLossChannel, CRx, Clifford, CliffordBatch, CorrelatedLossChannel, - Depolarizing, Depolarizing2, LossChannel, Measure, PauliError, Projection, Reset, - ResetLossChannel, ResetState, RotXY, RotationOne, RotationOneBatch, RotationTwo, - RotationTwoBatch, TGate, TwoQubitPauliError, U3Gate, + 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, }; pub use loss::{LossState, LossySite}; pub use pauli::{Pauli, PhaseTrack, SymplecticColumns}; diff --git a/crates/ppvm-traits-2/tests/apply_gate_rule.rs b/crates/ppvm-traits-2/tests/apply_gate_rule.rs new file mode 100644 index 000000000..187518c7b --- /dev/null +++ b/crates/ppvm-traits-2/tests/apply_gate_rule.rs @@ -0,0 +1,216 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! The blanket `Clifford` impl over `ApplyGateRule`, checked through gate identities +//! and through agreement between a `bool` and a bit-sliced `u64` container. + +use ppvm_traits_2::{ApplyGateRule, Clifford}; + +/// One signed Pauli on `n` qubits. +#[derive(Clone, PartialEq, Debug)] +struct OnePauli { + x: Vec, + z: Vec, + neg: bool, +} + +impl ApplyGateRule for OnePauli { + type B = bool; + + fn apply1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + let ([x, z], flip) = rule(self.x[q], self.z[q]); + (self.x[q], self.z[q]) = (x, z); + self.neg ^= flip; + } + + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([bool; 4]) -> ([bool; 4], bool)) { + let ([xa, za, xb, zb], flip) = rule([self.x[a], self.z[a], self.x[b], self.z[b]]); + (self.x[a], self.z[a], self.x[b], self.z[b]) = (xa, za, xb, zb); + self.neg ^= flip; + } +} + +/// 64 signed Paulis on `n` qubits, bit `i` of every word belonging to Pauli `i`. +#[derive(Clone, PartialEq, Debug)] +struct Sliced { + x: Vec, + z: Vec, + neg: u64, +} + +impl ApplyGateRule for Sliced { + type B = u64; + + fn apply1(&mut self, q: usize, rule: impl Fn(u64, u64) -> ([u64; 2], u64)) { + let ([x, z], flip) = rule(self.x[q], self.z[q]); + (self.x[q], self.z[q]) = (x, z); + self.neg ^= flip; + } + + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([u64; 4]) -> ([u64; 4], u64)) { + let ([xa, za, xb, zb], flip) = rule([self.x[a], self.z[a], self.x[b], self.z[b]]); + (self.x[a], self.z[a], self.x[b], self.z[b]) = (xa, za, xb, zb); + self.neg ^= flip; + } + + /// Sign-only gates skip the bit writes. + fn apply_sign1(&mut self, q: usize, rule: impl Fn(u64, u64) -> ([u64; 2], u64)) { + self.neg ^= rule(self.x[q], self.z[q]).1; + } +} + +impl Sliced { + fn pauli(&self, i: usize) -> OnePauli { + let bit = |w: u64| (w >> i) & 1 == 1; + OnePauli { + x: self.x.iter().map(|&w| bit(w)).collect(), + z: self.z.iter().map(|&w| bit(w)).collect(), + neg: bit(self.neg), + } + } +} + +/// SplitMix64, so the tests need no dependency. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn sliced(&mut self, n: usize) -> Sliced { + Sliced { + x: (0..n).map(|_| self.next()).collect(), + z: (0..n).map(|_| self.next()).collect(), + neg: self.next(), + } + } +} + +const N: usize = 3; + +/// Every signed Pauli on two qubits (32 of them), padded to `N` qubits. +fn all_paulis() -> Vec { + (0..32u32) + .map(|k| { + let bit = |i: u32| (k >> i) & 1 == 1; + OnePauli { + x: vec![bit(0), bit(2), false], + z: vec![bit(1), bit(3), true], + neg: bit(4), + } + }) + .collect() +} + +/// `lhs` and `rhs` conjugate every Pauli the same way. +fn same_conjugation(lhs: impl Fn(&mut OnePauli), rhs: impl Fn(&mut OnePauli), what: &str) { + for p in all_paulis() { + let (mut a, mut b) = (p.clone(), p.clone()); + lhs(&mut a); + rhs(&mut b); + assert_eq!(a, b, "{what} on {p:?}"); + } +} + +#[test] +fn single_qubit_identities() { + let id = |_: &mut OnePauli| {}; + same_conjugation(|p| (p.s(0), p.s(0)).1, |p| p.z(0), "S·S = Z"); + same_conjugation(|p| (p.s(0), p.s_dag(0)).1, id, "S·S† = I"); + same_conjugation(|p| (p.s_dag(0), p.s(0)).1, id, "S†·S = I"); + same_conjugation(|p| (p.sqrt_x(0), p.sqrt_x(0)).1, |p| p.x(0), "√X·√X = X"); + same_conjugation(|p| (p.sqrt_x(0), p.sqrt_x_dag(0)).1, id, "√X·√X† = I"); + same_conjugation(|p| (p.sqrt_y(0), p.sqrt_y(0)).1, |p| p.y(0), "√Y·√Y = Y"); + same_conjugation(|p| (p.sqrt_y(0), p.sqrt_y_dag(0)).1, id, "√Y·√Y† = I"); + same_conjugation(|p| (p.h(0), p.h(0)).1, id, "H·H = I"); + same_conjugation(|p| (p.h(0), p.z(0), p.h(0)).2, |p| p.x(0), "H·Z·H = X"); + same_conjugation(|p| (p.x(0), p.y(0)).1, |p| p.z(0), "X·Y ∝ Z"); + same_conjugation( + |p| (p.h(0), p.s(0), p.h(0)).2, + |p| p.sqrt_x(0), + "H·S·H ∝ √X", + ); + // U = S·√X·S† conjugates as S first, then √X, then S†. + same_conjugation( + |p| (p.s(0), p.sqrt_x(0), p.s_dag(0)).2, + |p| p.sqrt_y(0), + "S·√X·S† ∝ √Y", + ); +} + +#[test] +fn two_qubit_identities() { + same_conjugation( + |p| (p.h(1), p.cnot(0, 1), p.h(1)).2, + |p| p.cz(0, 1), + "(I⊗H)·CX·(I⊗H) = CZ", + ); + same_conjugation( + |p| (p.s(1), p.cnot(0, 1), p.s_dag(1)).2, + |p| p.cy(0, 1), + "(I⊗S)·CX·(I⊗S†) = CY", + ); + same_conjugation( + |p| (p.cz(0, 1), p.cz(1, 0)).1, + |_| {}, + "CZ is symmetric and self-inverse", + ); + same_conjugation(|p| p.cx(0, 1), |p| p.cnot(0, 1), "cx alias"); + same_conjugation(|p| p.zcy(0, 1), |p| p.cy(0, 1), "zcy alias"); +} + +#[test] +fn sign_only_gates_keep_bits() { + for p in all_paulis() { + for gate in [OnePauli::x, OnePauli::y, OnePauli::z] { + let mut q = p.clone(); + gate(&mut q, 0); + assert_eq!((&q.x, &q.z), (&p.x, &p.z)); + } + } +} + +/// Applies gate `g` (an index into the 13 gates) on random qubits. +fn apply_gate(c: &mut C, g: u64, a: usize, b: usize) { + match g { + 0 => c.x(a), + 1 => c.y(a), + 2 => c.z(a), + 3 => c.h(a), + 4 => c.s(a), + 5 => c.s_dag(a), + 6 => c.sqrt_x(a), + 7 => c.sqrt_x_dag(a), + 8 => c.sqrt_y(a), + 9 => c.sqrt_y_dag(a), + 10 => c.cnot(a, b), + 11 => c.cz(a, b), + _ => c.cy(a, b), + } +} + +#[test] +fn sliced_container_matches_single_paulis() { + let mut rng = Rng(42); + for _ in 0..16 { + let mut sliced = rng.sliced(N); + let mut singles: Vec = (0..64).map(|i| sliced.pauli(i)).collect(); + for _ in 0..200 { + let g = rng.next() % 13; + let a = (rng.next() % N as u64) as usize; + let b = (a + 1 + (rng.next() % (N as u64 - 1)) as usize) % N; + apply_gate(&mut sliced, g, a, b); + for p in &mut singles { + apply_gate(p, g, a, b); + } + } + for (i, p) in singles.iter().enumerate() { + assert_eq!(&sliced.pauli(i), p, "Pauli {i}"); + } + } +} From 489b85e701e1403676e8debe8e4dabb79572e87c Mon Sep 17 00:00:00 2001 From: David Plankensteiner Date: Tue, 10 Nov 2026 16:20:01 +0100 Subject: [PATCH 3/7] Port PauliWord to ApplyGateRule and the shared product kernel `PauliWord` now gets `Clifford` from the `ApplyGateRule` blanket impl instead of 13 hand-written gate methods; each gate's bits come from `ppvm_pauli_kernels::heisenberg`. `apply1`/`apply2` XOR in only the bits that change, drop the sign flip, and keep the existing panics on out-of-range or repeated qubits before any mutation. X, Y and Z stay no-ops via `apply_sign1`. Gates that change no bit skip the hash refresh when the storage is larger than one word; for a single word the branch cost more than the hash, so it always rehashes (measured on arm64). `key_mul_assign` loops over the new per-word kernel `ppvm_pauli_kernels::word_product` instead of carrying its own masks. It keeps the loop local rather than calling `row_product`: behind the call, the hash refresh that follows was ~4 ns slower at 1024 qubits. `row_product` shares the mask formula with `word_product`. `PauliStorage` now also requires `Bits` of its word type, which every storage word already satisfies. Against the previous commit (arm64): mixed gate sequences are unchanged at 64 qubits and 24-34% faster at 256 and 1024; single h/s/cnot at 64 qubits are 10-15% slower in isolation; the product is within ~3%. New tests: the cached hash stays structural after random circuits, one- and four-word storage agree on random circuits (this catches a broken skip condition), and `word_product` matches the matrix-model site table. Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 1 + crates/ppvm-pauli-kernels/src/lib.rs | 5 +- crates/ppvm-pauli-kernels/src/product.rs | 20 ++ crates/ppvm-pauli-kernels/tests/product.rs | 25 ++- crates/ppvm-pauli-word-2/Cargo.toml | 1 + crates/ppvm-pauli-word-2/src/clifford.rs | 205 ++++++++++++--------- crates/ppvm-pauli-word-2/src/data.rs | 2 +- crates/ppvm-pauli-word-2/src/product.rs | 55 ++---- crates/ppvm-pauli-word-2/src/storage.rs | 7 +- 9 files changed, 188 insertions(+), 133 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d2a35594..80c5f4d06 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2263,6 +2263,7 @@ dependencies = [ "foldhash", "fxhash", "num", + "ppvm-pauli-kernels", "ppvm-traits-2", ] diff --git a/crates/ppvm-pauli-kernels/src/lib.rs b/crates/ppvm-pauli-kernels/src/lib.rs index ff8112aab..77f35cd15 100644 --- a/crates/ppvm-pauli-kernels/src/lib.rs +++ b/crates/ppvm-pauli-kernels/src/lib.rs @@ -10,7 +10,8 @@ //! sign-flip mask. It is generic over [`Bits`], so the same formula updates //! one Pauli (`bool`) or 64 at once (`u64`, one per bit position). //! - [`row_product`] / [`row_product_phase`]: the packed Pauli-word product and -//! the exponent `k` of the phase `iᵏ` it emits. +//! the exponent `k` of the phase `iᵏ` it emits, built on the per-word +//! [`word_product`]. //! //! The crate has no PPVM dependencies; containers wire the rules into their own //! loops. @@ -28,4 +29,4 @@ pub mod heisenberg; mod product; pub use bits::Bits; -pub use product::{row_product, row_product_phase}; +pub use product::{row_product, row_product_phase, word_product}; diff --git a/crates/ppvm-pauli-kernels/src/product.rs b/crates/ppvm-pauli-kernels/src/product.rs index 9190d0ef8..17b129018 100644 --- a/crates/ppvm-pauli-kernels/src/product.rs +++ b/crates/ppvm-pauli-kernels/src/product.rs @@ -30,6 +30,26 @@ fn exponent(sign_count: u32, imag_count: u32) -> u8 { (sign_count.wrapping_mul(2).wrapping_add(imag_count) % 4) as u8 } +/// One storage word of the product `dst · src`. +/// +/// Returns the product's bits `[dst_x ⊕ src_x, dst_z ⊕ src_z]` and this word's +/// contribution `2·popcount(sign) + popcount(imag)` to the phase exponent. A row's +/// exponent is the wrapping sum of its words' contributions, mod 4. +/// +/// For containers that write their own loop around the product, e.g. to follow +/// it with a hash of the same words: a loop the compiler sees inline lets that +/// work reuse the words still in registers, which a call to [`row_product`] did +/// not (measured on `PauliWord`). +#[inline(always)] +pub fn word_product(dst_x: W, dst_z: W, src_x: W, src_z: W) -> ([W; 2], u32) { + let (sign, imag) = masks(dst_x, dst_z, src_x, src_z); + let contribution = sign + .popcount() + .wrapping_mul(2) + .wrapping_add(imag.popcount()); + ([dst_x ^ src_x, dst_z ^ src_z], contribution) +} + /// `dst ← dst · src`. Returns `k ∈ 0..4` with `dst · src = iᵏ · (dst ⊕ src)`. /// /// All four slices must have the same length. diff --git a/crates/ppvm-pauli-kernels/tests/product.rs b/crates/ppvm-pauli-kernels/tests/product.rs index b69241c63..f7ee2c7b0 100644 --- a/crates/ppvm-pauli-kernels/tests/product.rs +++ b/crates/ppvm-pauli-kernels/tests/product.rs @@ -10,7 +10,7 @@ mod common; mod tables; use common::Rng; -use ppvm_pauli_kernels::{row_product, row_product_phase}; +use ppvm_pauli_kernels::{row_product, row_product_phase, word_product}; /// A Pauli word on `64 · len` qubits as X and Z planes. #[derive(Clone, PartialEq, Debug)] @@ -54,6 +54,29 @@ fn single_site_matches_matrix_model() { } } +/// One word's contribution, mod 4, is the sum of its 64 site exponents. +#[test] +fn word_product_matches_site_phases() { + let mut rng = Rng::new(19); + for _ in 0..256 { + let [a, b, c, d] = [ + rng.next_u64(), + rng.next_u64(), + rng.next_u64(), + rng.next_u64(), + ]; + let expected: u32 = (0..64) + .map(|i| { + let bit = |w: u64| (w >> i) & 1 == 1; + site_exponent(bit(a), bit(b), bit(c), bit(d)) as u32 + }) + .sum(); + let ([x, z], e) = word_product(a, b, c, d); + assert_eq!(e % 4, expected % 4); + assert_eq!([x, z], [a ^ c, b ^ d]); + } +} + #[test] fn phase_is_sum_of_site_phases() { let mut rng = Rng::new(3); diff --git a/crates/ppvm-pauli-word-2/Cargo.toml b/crates/ppvm-pauli-word-2/Cargo.toml index 0921be99e..237c54adf 100644 --- a/crates/ppvm-pauli-word-2/Cargo.toml +++ b/crates/ppvm-pauli-word-2/Cargo.toml @@ -8,6 +8,7 @@ publish = false [dependencies] ppvm-traits-2 = { path = "../ppvm-traits-2"} +ppvm-pauli-kernels = { path = "../ppvm-pauli-kernels" } bitvec = "1.0.1" bytemuck = { version = "1", features = ["min_const_generics"] } foldhash = "0.1.5" diff --git a/crates/ppvm-pauli-word-2/src/clifford.rs b/crates/ppvm-pauli-word-2/src/clifford.rs index 77a155c20..83690cc50 100644 --- a/crates/ppvm-pauli-word-2/src/clifford.rs +++ b/crates/ppvm-pauli-word-2/src/clifford.rs @@ -2,121 +2,68 @@ // SPDX-License-Identifier: Apache-2.0 //! Clifford conjugation of packed Pauli words, discarding all phase signs. -//! Fused gates refresh the eager hash once instead of hashing each primitive step. +//! `PauliWord` implements `ApplyGateRule`, so `Clifford` comes from the blanket impl +//! and each gate's bits from `ppvm_pauli_kernels::heisenberg`. The hash is +//! refreshed once per gate, and only when a bit changes. //! Symplectic bit operations remain available; `PhaseTrack` is a no-op. //! Phase signs must be handled separately by phased words or the sum engine. use std::hash::BuildHasher; -use ppvm_traits_2::{Clifford, PhaseTrack, SymplecticColumns}; +use ppvm_traits_2::{ApplyGateRule, PhaseTrack, SymplecticColumns}; -use crate::data::PauliWord; +use crate::data::{PauliWord, xor_bits2}; use crate::{HashFinalize, PauliStorage}; -impl Clifford for PauliWord +/// Whether a gate that changes no bit skips the hash refresh. Measured on arm64: +/// for one storage word the hash is cheaper than the unpredictable branch, for +/// larger storage skipping it is faster. +const fn skips_unchanged() -> bool { + std::mem::size_of::() > 8 +} + +impl ApplyGateRule for PauliWord where A: PauliStorage, H: BuildHasher + Default + HashFinalize, { - #[inline] - fn x(&mut self, q: usize) { - debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - } - - #[inline] - fn y(&mut self, q: usize) { - debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - } - - #[inline] - fn z(&mut self, q: usize) { - debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - } - - #[inline] - fn h(&mut self, q: usize) { - debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - let x = self.xbits[q]; - self.xbits.set(q, self.zbits[q]); - self.zbits.set(q, x); - self.refresh_hash(); - } + type B = bool; + /// The sign flip is dropped: an unsigned word has no sign. Only changed bits + /// are written, and the hash is refreshed once if any changed. #[inline] - fn s(&mut self, q: usize) { + fn apply1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - let z = self.zbits[q] ^ self.xbits[q]; - self.zbits.set(q, z); - self.refresh_hash(); - } - - #[inline] - fn cnot(&mut self, control: usize, target: usize) { - debug_assert_ne!(control, target, "CNOT requires distinct qubits"); - debug_assert!( - control < self.nqubits && target < self.nqubits, - "qubit out of bounds" - ); - let xt = self.xbits[target] ^ self.xbits[control]; - let zc = self.zbits[control] ^ self.zbits[target]; - self.xbits.set(target, xt); - self.zbits.set(control, zc); + let (x, z) = (self.xbits[q], self.zbits[q]); + let ([x2, z2], _) = rule(x, z); + let (tx, tz) = (x ^ x2, z ^ z2); + if skips_unchanged::() && !(tx || tz) { + return; + } + xor_bits2(&mut self.xbits, q, tx, q, false); + xor_bits2(&mut self.zbits, q, tz, q, false); self.refresh_hash(); } #[inline] - fn cz(&mut self, a: usize, b: usize) { - debug_assert_ne!(a, b, "CZ requires distinct qubits"); + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([bool; 4]) -> ([bool; 4], bool)) { + debug_assert_ne!(a, b, "two-qubit gates require distinct qubits"); debug_assert!(a < self.nqubits && b < self.nqubits, "qubit out of bounds"); - let za = self.zbits[a] ^ self.xbits[b]; - let zb = self.zbits[b] ^ self.xbits[a]; - self.zbits.set(a, za); - self.zbits.set(b, zb); + let old = [self.xbits[a], self.zbits[a], self.xbits[b], self.zbits[b]]; + let (new, _) = rule(old); + let [txa, tza, txb, tzb] = [0, 1, 2, 3].map(|i| old[i] ^ new[i]); + if skips_unchanged::() && !(txa || tza || txb || tzb) { + return; + } + xor_bits2(&mut self.xbits, a, txa, b, txb); + xor_bits2(&mut self.zbits, a, tza, b, tzb); self.refresh_hash(); } - #[inline] - fn s_dag(&mut self, q: usize) { - self.s(q); - } + /// X, Y and Z only flip signs, so they leave an unsigned word unchanged. #[inline] - fn sqrt_x(&mut self, q: usize) { + fn apply_sign1(&mut self, q: usize, _rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - let x = self.xbits[q] ^ self.zbits[q]; - self.xbits.set(q, x); - self.refresh_hash(); - } - - #[inline] - fn sqrt_x_dag(&mut self, q: usize) { - self.sqrt_x(q); - } - - #[inline] - fn sqrt_y(&mut self, q: usize) { - self.h(q); - } - - #[inline] - fn sqrt_y_dag(&mut self, q: usize) { - self.h(q); - } - - #[inline] - fn cy(&mut self, control: usize, target: usize) { - debug_assert_ne!(control, target, "CY requires distinct qubits"); - debug_assert!( - control < self.nqubits && target < self.nqubits, - "qubit out of bounds" - ); - let xc = self.xbits[control]; - let zc = self.zbits[control]; - let xt = self.xbits[target]; - let zt = self.zbits[target]; - self.zbits.set(control, zc ^ xt ^ zt); - self.xbits.set(target, xt ^ xc); - self.zbits.set(target, zt ^ xc); - self.refresh_hash(); } } @@ -364,4 +311,82 @@ mod tests { assert_eq!(conj(input, |w| w.z(0)), input); } } + + fn random_gate(c: &mut C, g: u64, a: usize, b: usize) { + match g % 13 { + 0 => c.x(a), + 1 => c.y(a), + 2 => c.z(a), + 3 => c.h(a), + 4 => c.s(a), + 5 => c.s_dag(a), + 6 => c.sqrt_x(a), + 7 => c.sqrt_x_dag(a), + 8 => c.sqrt_y(a), + 9 => c.sqrt_y_dag(a), + 10 => c.cnot(a, b), + 11 => c.cz(a, b), + _ => c.cy(a, b), + } + } + + /// Xorshift64, so the tests need no dependency. + fn rng(mut seed: u64) -> impl FnMut() -> u64 { + move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + } + } + + /// After any gate sequence the cached hash equals that of a freshly built word. + fn hash_stays_structural(n: usize) + where + PauliWord: Clifford, + { + let mut next = rng(0x9E37_79B9_7F4A_7C15); + for _ in 0..64 { + let start: String = (0..n) + .map(|_| ['I', 'X', 'Y', 'Z'][(next() % 4) as usize]) + .collect(); + let mut w = PauliWord::::from(start.as_str()); + for _ in 0..64 { + let a = (next() % n as u64) as usize; + let b = (a + 1 + (next() % (n as u64 - 1)) as usize) % n; + random_gate(&mut w, next(), a, b); + let fresh = PauliWord::::from(w.to_string().as_str()); + assert_eq!(w, fresh); + assert_eq!(w.key_hash(), fresh.key_hash()); + } + } + } + + /// One-word storage always writes; larger storage skips gates that change no + /// bit. Both must agree on every circuit. + #[test] + fn storage_sizes_agree() { + let mut next = rng(0xD1B5_4A32_D192_ED03); + for _ in 0..64 { + let start: String = (0..64) + .map(|_| ['I', 'X', 'Y', 'Z'][(next() % 4) as usize]) + .collect(); + let mut small = PauliWord::::from(start.as_str()); + let mut large = PauliWord::<[u64; 4]>::from(start.as_str()); + for _ in 0..256 { + let (g, a) = (next(), (next() % 64) as usize); + let b = (a + 1 + (next() % 63) as usize) % 64; + random_gate(&mut small, g, a, b); + random_gate(&mut large, g, a, b); + } + assert_eq!(small.to_string(), large.to_string()); + } + } + + #[test] + fn gates_keep_the_hash_structural() { + // One storage word always refreshes; larger storage skips unchanged gates. + hash_stays_structural::(5); + hash_stays_structural::<[u64; 4]>(200); + } } diff --git a/crates/ppvm-pauli-word-2/src/data.rs b/crates/ppvm-pauli-word-2/src/data.rs index 0af30f10e..4038478b8 100644 --- a/crates/ppvm-pauli-word-2/src/data.rs +++ b/crates/ppvm-pauli-word-2/src/data.rs @@ -54,7 +54,7 @@ fn bit_mask(offset: usize, toggle: bool) -> ::Sto /// Used for data-dependent Clifford toggles to avoid separate conditional writes. /// Rotation builders use direct flips instead; see `PauliWord::with_bits_toggled2`. #[inline(always)] -fn xor_bits2( +pub(crate) fn xor_bits2( plane: &mut BitArray, i: usize, toggle_i: bool, diff --git a/crates/ppvm-pauli-word-2/src/product.rs b/crates/ppvm-pauli-word-2/src/product.rs index a82b9245d..9f807dbb0 100644 --- a/crates/ppvm-pauli-word-2/src/product.rs +++ b/crates/ppvm-pauli-word-2/src/product.rs @@ -2,12 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 //! Packed Pauli multiplication: XOR the X/Z planes and return the residual phase. -//! One pass counts sign and imaginary masks to compute `i^k`, with `k` modulo four. -//! The coefficient absorbs the phase; zero unused bits remain zero after XOR. -//! Phase identities are verified in `lean/PPVM/Pauli/{Phase,Word}.lean`. +//! Each storage word goes through `ppvm_pauli_kernels::word_product`, proved in +//! `lean/PPVM/Kernels/RowProduct.lean`; zero unused bits remain zero after XOR. -use bitvec::view::BitView; -use num::PrimInt; +use ppvm_pauli_kernels::word_product; use ppvm_traits_2::{KeyProduct, Phase}; use std::hash::BuildHasher; @@ -16,7 +14,6 @@ use crate::{HashFinalize, PauliStorage, PauliWord}; impl KeyProduct for PauliWord where A: PauliStorage, - ::Store: PrimInt, H: BuildHasher + Default + HashFinalize, // `Eq` and `Clone` add no further bounds on `H`. { @@ -36,38 +33,24 @@ where "twisted product requires equal-width words", ); - let lhs_x = self.xbits.data.as_raw_mut_slice(); - let lhs_z = self.zbits.data.as_raw_mut_slice(); - let rhs_x = other.xbits.data.as_raw_slice(); - let rhs_z = other.zbits.data.as_raw_slice(); - - let mut sign_count = 0u32; - let mut imaginary_count = 0u32; - - // Each iteration multiplies a packed group of qubits in parallel. - for chunk in 0..lhs_x.len() { - let (left_x, left_z) = (lhs_x[chunk], lhs_z[chunk]); - let (right_x, right_z) = (rhs_x[chunk], rhs_z[chunk]); - - // Each set bit contributes a factor of -1 (i²) or i, respectively. - let sign_mask = (left_x & left_z & right_x & !right_z) - | (left_x & !left_z & !right_x & right_z) - | (!left_x & left_z & right_x & right_z); - let imaginary_mask = (left_x & !left_z & right_z) - | (left_x & !right_x & right_z) - | (!left_x & left_z & right_x) - | (left_z & right_x & !right_z); - sign_count += sign_mask.count_ones(); - imaginary_count += imaginary_mask.count_ones(); - - // XOR gives the product's Pauli letters; the masks account for phase. - lhs_x[chunk] = left_x ^ right_x; - lhs_z[chunk] = left_z ^ right_z; + let (lhs_x, lhs_z) = ( + self.xbits.data.as_raw_mut_slice(), + self.zbits.data.as_raw_mut_slice(), + ); + let (rhs_x, rhs_z) = ( + other.xbits.data.as_raw_slice(), + other.zbits.data.as_raw_slice(), + ); + // A local loop rather than `row_product`: inline, the hash below reuses the + // words still in registers (measured ~35% faster at 1024 qubits). + let mut k = 0u32; + for i in 0..lhs_x.len() { + let ([x, z], e) = word_product(lhs_x[i], lhs_z[i], rhs_x[i], rhs_z[i]); + (lhs_x[i], lhs_z[i]) = (x, z); + k = k.wrapping_add(e); } - self.refresh_hash(); - let phase_exponent = ((2 * sign_count + imaginary_count) % 4) as u8; - Phase::from_exponent(phase_exponent) + Phase::from_exponent((k % 4) as u8) } } diff --git a/crates/ppvm-pauli-word-2/src/storage.rs b/crates/ppvm-pauli-word-2/src/storage.rs index 7295d487c..070610894 100644 --- a/crates/ppvm-pauli-word-2/src/storage.rs +++ b/crates/ppvm-pauli-word-2/src/storage.rs @@ -3,6 +3,7 @@ use bitvec::view::{BitView, BitViewSized}; use num::PrimInt; +use ppvm_pauli_kernels::Bits; use std::hash::Hash; /// Default storage is `u64`, or `usize` on wasm32 where `bitvec` lacks `u64` support. @@ -14,10 +15,10 @@ pub type DefaultStorage = u64; pub type DefaultStorage = usize; /// Fixed-size storage for one Pauli bit plane: `u64`, `[u8; N]`, or `[u64; N]`. -/// `Pod` permits safe byte views for hashing; `PrimInt` enables whole-integer kernels. +/// `Pod` permits safe byte views for hashing; `PrimInt` and `Bits` enable whole-integer kernels. pub trait PauliStorage: BitViewSized - + BitView + + BitView + Copy + Hash + Eq @@ -30,7 +31,7 @@ pub trait PauliStorage: impl PauliStorage for A where A: BitViewSized - + BitView + + BitView + Copy + Hash + Eq From c7e74b5b2b06e1fb55ff31d03a32fca0158d0200 Mon Sep 17 00:00:00 2001 From: David Plankensteiner Date: Tue, 10 Nov 2026 16:39:13 +0100 Subject: [PATCH 4/7] Give LossyPauliWord Clifford via ApplyGateRule On main the lossy word implemented only the SymplecticColumns/PhaseTrack primitives, whose blanket Clifford impl never landed, so a bare lossy word had no Clifford; it took part only through Phased. It now implements ApplyGateRule: - a gate touching any lost site does nothing (as the primitives do); - out-of-range qubits panic via check_qubit, like its bit accessors; - the sign flip is dropped, and X/Y/Z only check bounds; - only changed bits are written, XORed into the raw storage words, and the lazy X/Z hash is invalidated branch-free when something changed. To share that write path, PauliWord's xor_bits2 is now public (doc-hidden) and re-exported from ppvm-pauli-word-2. Writing all four bits through bitvec made cnot 5.2 ns at 64 qubits; with the raw XOR writes the lossy word matches PauliWord (cnot ~2.4 ns, mixed ~2.6 ns/gate, arm64). Tests: a loss-free lossy word matches PauliWord on random circuits, every gate on a lost site is a no-op while gates elsewhere match a plain word, and the cached hash stays structural with lost sites present. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../ppvm-lossy-pauli-word-2/src/clifford.rs | 151 +++++++++++++++++- crates/ppvm-lossy-pauli-word-2/src/data.rs | 2 +- crates/ppvm-pauli-word-2/src/data.rs | 4 +- crates/ppvm-pauli-word-2/src/lib.rs | 2 + 4 files changed, 155 insertions(+), 4 deletions(-) diff --git a/crates/ppvm-lossy-pauli-word-2/src/clifford.rs b/crates/ppvm-lossy-pauli-word-2/src/clifford.rs index 173a48de2..1478823c1 100644 --- a/crates/ppvm-lossy-pauli-word-2/src/clifford.rs +++ b/crates/ppvm-lossy-pauli-word-2/src/clifford.rs @@ -3,9 +3,13 @@ //! X/Z bit operations skip lost qubits and invalidate only the X/Z hash. //! Lossy words store no phase, so phase updates do nothing. +//! +//! `LossyPauliWord` implements `ApplyGateRule`, so it gets `Clifford` from the +//! blanket impl: a gate touching a lost site does nothing; otherwise the bits come +//! from `ppvm_pauli_kernels::heisenberg` and the sign flip is dropped. -use ppvm_pauli_word_2::PauliStorage; -use ppvm_traits_2::{PhaseTrack, SymplecticColumns}; +use ppvm_pauli_word_2::{PauliStorage, xor_bits2}; +use ppvm_traits_2::{ApplyGateRule, PhaseTrack, SymplecticColumns}; use crate::LossyPauliWord; @@ -98,10 +102,153 @@ impl PhaseTrack for LossyPauliWord { fn z_phase(&mut self, _q: usize) {} } +impl ApplyGateRule for LossyPauliWord { + type B = bool; + + #[inline] + fn apply1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + if self.is_lost(q) { + return; + } + let (x, z) = (self.xbits[q], self.zbits[q]); + let ([x2, z2], _) = rule(x, z); + let (tx, tz) = (x ^ x2, z ^ z2); + xor_bits2(&mut self.xbits, q, tx, q, false); + xor_bits2(&mut self.zbits, q, tz, q, false); + // Branch-free: the lazy hash stays valid only if nothing changed. + *self.xz_hash_valid.get_mut() &= !(tx || tz); + } + + #[inline] + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([bool; 4]) -> ([bool; 4], bool)) { + debug_assert_ne!(a, b, "two-qubit gates require distinct qubits"); + if self.is_lost(a) || self.is_lost(b) { + return; + } + let old = [self.xbits[a], self.zbits[a], self.xbits[b], self.zbits[b]]; + let (new, _) = rule(old); + let [txa, tza, txb, tzb] = [0, 1, 2, 3].map(|i| old[i] ^ new[i]); + xor_bits2(&mut self.xbits, a, txa, b, txb); + xor_bits2(&mut self.zbits, a, tza, b, tzb); + *self.xz_hash_valid.get_mut() &= !(txa || tza || txb || tzb); + } + + /// X, Y and Z only flip signs, which a lossy word does not store. + #[inline] + fn apply_sign1(&mut self, q: usize, _rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + self.check_qubit(q); + } +} + #[cfg(test)] mod tests { use super::*; + use ppvm_pauli_word_2::PauliWord; + use ppvm_traits_2::{Clifford, Indexable}; + + fn random_gate(c: &mut C, g: u64, a: usize, b: usize) { + match g % 13 { + 0 => c.x(a), + 1 => c.y(a), + 2 => c.z(a), + 3 => c.h(a), + 4 => c.s(a), + 5 => c.s_dag(a), + 6 => c.sqrt_x(a), + 7 => c.sqrt_x_dag(a), + 8 => c.sqrt_y(a), + 9 => c.sqrt_y_dag(a), + 10 => c.cnot(a, b), + 11 => c.cz(a, b), + _ => c.cy(a, b), + } + } + + /// Xorshift64, so the tests need no dependency. + fn rng(mut seed: u64) -> impl FnMut() -> u64 { + move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + } + } + + fn random_paulis(next: &mut impl FnMut() -> u64, n: usize) -> String { + (0..n) + .map(|_| ['I', 'X', 'Y', 'Z'][(next() % 4) as usize]) + .collect() + } + + /// Without loss, a lossy word conjugates exactly like a plain `PauliWord`. + #[test] + fn loss_free_gates_match_pauli_word() { + let mut next = rng(0xD1B5_4A32_D192_ED03); + for _ in 0..64 { + let start = random_paulis(&mut next, 64); + let mut lossy = LossyPauliWord::::from(start.as_str()); + let mut plain = PauliWord::::from(start.as_str()); + for _ in 0..256 { + let (g, a) = (next(), (next() % 64) as usize); + let b = (a + 1 + (next() % 63) as usize) % 64; + random_gate(&mut lossy, g, a, b); + random_gate(&mut plain, g, a, b); + } + assert_eq!(lossy.to_string(), plain.to_string()); + } + } + + /// Every gate on a lost site does nothing; gates elsewhere still act. + #[test] + fn gates_touching_lost_sites_do_nothing() { + for g in 0..13 { + for input in ["XL", "LY", "ZL"] { + let mut word = LossyPauliWord::::from(input); + let lost = if word.is_lost(0) { 0 } else { 1 }; + random_gate(&mut word, g, lost, 1 - lost); + assert_eq!(word, LossyPauliWord::from(input), "gate {g} on {input}"); + } + } + // Gates away from the lost site act as on a plain word. + let (mut word, mut plain) = ( + LossyPauliWord::::from("XLZ"), + PauliWord::::from("XIZ"), + ); + word.h(0); + word.cnot(2, 0); + plain.h(0); + plain.cnot(2, 0); + let expected: String = plain + .to_string() + .chars() + .enumerate() + .map(|(i, c)| if i == 1 { 'L' } else { c }) + .collect(); + assert_eq!(word.to_string(), expected); + } + + /// After any circuit, with some sites lost, the cached hash matches a fresh word. + #[test] + fn gates_keep_the_hash_structural() { + let mut next = rng(0x9E37_79B9_7F4A_7C15); + for _ in 0..64 { + let mut start: Vec = random_paulis(&mut next, 40).chars().collect(); + for _ in 0..4 { + start[(next() % 40) as usize] = 'L'; + } + let start: String = start.into_iter().collect(); + let mut word = LossyPauliWord::::from(start.as_str()); + for _ in 0..64 { + let (g, a) = (next(), (next() % 40) as usize); + let b = (a + 1 + (next() % 39) as usize) % 40; + random_gate(&mut word, g, a, b); + let fresh = LossyPauliWord::::from(word.to_string().as_str()); + assert_eq!(word.key_hash(), fresh.key_hash()); + } + } + } + #[test] fn single_qubit_operations_transform_present_sites() { let mut word = LossyPauliWord::::from("XYZL"); diff --git a/crates/ppvm-lossy-pauli-word-2/src/data.rs b/crates/ppvm-lossy-pauli-word-2/src/data.rs index 165076e04..8349ebcb3 100644 --- a/crates/ppvm-lossy-pauli-word-2/src/data.rs +++ b/crates/ppvm-lossy-pauli-word-2/src/data.rs @@ -32,7 +32,7 @@ pub struct LossyPauliWord LossyPauliWord { #[inline] - fn check_qubit(&self, qubit: usize) { + pub(crate) fn check_qubit(&self, qubit: usize) { if qubit >= self.nqubits { panic!("qubit {qubit} out of bounds for {} sites", self.nqubits); } diff --git a/crates/ppvm-pauli-word-2/src/data.rs b/crates/ppvm-pauli-word-2/src/data.rs index 4038478b8..8a3181210 100644 --- a/crates/ppvm-pauli-word-2/src/data.rs +++ b/crates/ppvm-pauli-word-2/src/data.rs @@ -53,8 +53,10 @@ fn bit_mask(offset: usize, toggle: bool) -> ::Sto /// Combines masks with XOR so toggling the same bit twice cancels. /// Used for data-dependent Clifford toggles to avoid separate conditional writes. /// Rotation builders use direct flips instead; see `PauliWord::with_bits_toggled2`. +/// Shared with `ppvm-lossy-pauli-word-2`, whose planes use the same storage. +#[doc(hidden)] #[inline(always)] -pub(crate) fn xor_bits2( +pub fn xor_bits2( plane: &mut BitArray, i: usize, toggle_i: bool, diff --git a/crates/ppvm-pauli-word-2/src/lib.rs b/crates/ppvm-pauli-word-2/src/lib.rs index b74274dfd..064fc554d 100644 --- a/crates/ppvm-pauli-word-2/src/lib.rs +++ b/crates/ppvm-pauli-word-2/src/lib.rs @@ -13,5 +13,7 @@ mod storage; pub use column::PauliKeyColumn; pub use data::PauliWord; +#[doc(hidden)] +pub use data::xor_bits2; pub use hash::HashFinalize; pub use storage::{DefaultStorage, PauliStorage}; From 8d1f91d7c3e7df01039180197b8278d4c67fbb65 Mon Sep 17 00:00:00 2001 From: David Plankensteiner Date: Tue, 10 Nov 2026 16:47:26 +0100 Subject: [PATCH 5/7] Port Phased to ApplyGateRule, delegating bits to the word MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Phased` now gets `Clifford` from the `ApplyGateRule` blanket impl instead of 13 hand-written gates. `apply1`/`apply2` hand the rule to the word's own `ApplyGateRule`, wrapped to record its sign flip, so each word type keeps its tuned write path; `Phased` only updates its ℤ₄ phase. A word that skips a gate (a lost site) never calls the rule, so no flip is recorded. Sign-only gates (X/Y/Z) compute the flip in `Phased`, since `PauliWord` skips those rules entirely; they keep the lost-site check, which is redundant today because lost sites always hold zero X/Z bits. `W` must now also implement `ApplyGateRule`; both word types do. The flip is applied branch-free (`exponent + 2·flip`): on random Paulis it is a coin toss, and the branch mispredicted (~1 ns per gate, arm64). Against the previous commit, mixed gate sequences are 4-19% faster (Phased 64q 3.18 -> 3.04, 256q 4.58 -> 4.27 ns/gate; Phased 64q 3.29 -> 3.01, 256q 3.52 -> 2.84). Some single gates repeated in isolation are slower (e.g. h at 64 qubits), others faster. New test: Phased and a loss-free Phased agree on random circuits, phase included. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../ppvm-phased-pauli-word-2/src/clifford.rs | 232 ++++++------------ 1 file changed, 81 insertions(+), 151 deletions(-) diff --git a/crates/ppvm-phased-pauli-word-2/src/clifford.rs b/crates/ppvm-phased-pauli-word-2/src/clifford.rs index 652ce1464..4dc9e3f9f 100644 --- a/crates/ppvm-phased-pauli-word-2/src/clifford.rs +++ b/crates/ppvm-phased-pauli-word-2/src/clifford.rs @@ -2,177 +2,66 @@ // SPDX-License-Identifier: Apache-2.0 //! Phase-tracking Clifford conjugation. Gates touching lost sites are no-ops. -//! The base word must implement both `PauliBits` and `LossInfo`. +//! +//! `Phased` implements `ApplyGateRule`, so `Clifford` comes from the blanket +//! impl. The bit update is delegated to the word's own `ApplyGateRule`, so each +//! word type keeps its fastest write path; `Phased` only multiplies its `ℤ₄` +//! phase by −1 when the rule (from `ppvm_pauli_kernels::heisenberg`, +//! `S† X S = −Y`) reports a sign flip. -use ppvm_traits_2::{Clifford, PauliBits, Phase, loss::LossInfo}; +use std::cell::Cell; + +use ppvm_traits_2::{ApplyGateRule, PauliBits, Phase, loss::LossInfo}; use crate::data::Phased; -impl Phased { +impl Phased { + /// Branch-free: the flip is a coin toss on random Paulis, so a branch here + /// mispredicts often (measured ~1 ns per gate on arm64). #[inline] fn flip_sign_if(&mut self, cond: bool) { - if cond { - self.phase *= Phase::Neg1; - } + self.phase = Phase::from_exponent(self.phase.exponent() + 2 * cond as u8); } } -impl Clifford for Phased { - #[inline] - fn x(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - self.flip_sign_if(self.word.z_bit(q)); - } - - #[inline] - fn y(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - self.flip_sign_if(self.word.x_bit(q) ^ self.word.z_bit(q)); - } - - #[inline] - fn z(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - self.flip_sign_if(self.word.x_bit(q)); - } - - #[inline] - fn h(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - let x = self.word.x_bit(q); - let z = self.word.z_bit(q); - self.word.set_xz_bits(q, z, x); - self.flip_sign_if(x && z); - } - - // Heisenberg convention: S† X S = -Y. - #[inline] - fn s(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - let x = self.word.x_bit(q); - let z = self.word.z_bit(q); - self.word.set_z_bit(q, z ^ x); - self.flip_sign_if(x && !z); - } +/// A word that skips a gate (e.g. on a lost site) never calls the rule, so the +/// recorded flip stays `false` and the phase is untouched. +impl ApplyGateRule for Phased +where + W: ApplyGateRule + PauliBits + LossInfo, +{ + type B = bool; #[inline] - fn cnot(&mut self, ctrl: usize, tgt: usize) { - debug_assert_ne!(ctrl, tgt, "CNOT requires distinct qubits"); - debug_assert!( - ctrl < self.word.n_sites() && tgt < self.word.n_sites(), - "qubit out of bounds" - ); - if self.word.is_lost(ctrl) || self.word.is_lost(tgt) { - return; - } - let xc = self.word.x_bit(ctrl); - let zc = self.word.z_bit(ctrl); - let xt = self.word.x_bit(tgt); - let zt = self.word.z_bit(tgt); - self.word.set_x_bit_and_z_bit(tgt, xt ^ xc, ctrl, zc ^ zt); - self.flip_sign_if(xc && zt && (xt == zc)); + fn apply1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { + let flip = Cell::new(false); + self.word.apply1(q, |x, z| { + let out = rule(x, z); + flip.set(out.1); + out + }); + self.flip_sign_if(flip.get()); } #[inline] - fn cz(&mut self, a: usize, b: usize) { - debug_assert_ne!(a, b, "CZ requires distinct qubits"); - debug_assert!( - a < self.word.n_sites() && b < self.word.n_sites(), - "qubit out of bounds" - ); - if self.word.is_lost(a) || self.word.is_lost(b) { - return; - } - let xa = self.word.x_bit(a); - let za = self.word.z_bit(a); - let xb = self.word.x_bit(b); - let zb = self.word.z_bit(b); - self.word.set_z_bit_pair(a, za ^ xb, b, zb ^ xa); - self.flip_sign_if(xa && xb && (za ^ zb)); + fn apply2(&mut self, a: usize, b: usize, rule: impl Fn([bool; 4]) -> ([bool; 4], bool)) { + let flip = Cell::new(false); + self.word.apply2(a, b, |bits| { + let out = rule(bits); + flip.set(out.1); + out + }); + self.flip_sign_if(flip.get()); } + /// Words may skip sign-only rules entirely, so the flip is computed here. #[inline] - fn s_dag(&mut self, q: usize) { + fn apply_sign1(&mut self, q: usize, rule: impl Fn(bool, bool) -> ([bool; 2], bool)) { if self.word.is_lost(q) { return; } - let x = self.word.x_bit(q); - let z = self.word.z_bit(q); - self.word.set_z_bit(q, z ^ x); - self.flip_sign_if(x && z); - } - - #[inline] - fn sqrt_x(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - let x = self.word.x_bit(q); - let z = self.word.z_bit(q); - self.word.set_x_bit(q, x ^ z); - self.flip_sign_if(x && z); - } - - #[inline] - fn sqrt_x_dag(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - let x = self.word.x_bit(q); - let z = self.word.z_bit(q); - self.word.set_x_bit(q, x ^ z); - self.flip_sign_if(!x && z); - } - - #[inline] - fn sqrt_y(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - let x = self.word.x_bit(q); - let z = self.word.z_bit(q); - self.word.set_xz_bits(q, z, x); - self.flip_sign_if(!x && z); - } - - #[inline] - fn sqrt_y_dag(&mut self, q: usize) { - if self.word.is_lost(q) { - return; - } - let x = self.word.x_bit(q); - let z = self.word.z_bit(q); - self.word.set_xz_bits(q, z, x); - self.flip_sign_if(x && !z); - } - - #[inline] - fn cy(&mut self, control: usize, target: usize) { - debug_assert_ne!(control, target, "CY requires distinct qubits"); - debug_assert!( - control < self.word.n_sites() && target < self.word.n_sites(), - "qubit out of bounds" - ); - if self.word.is_lost(control) || self.word.is_lost(target) { - return; - } - let xc = self.word.x_bit(control); - let zc = self.word.z_bit(control); - let xt = self.word.x_bit(target); - let zt = self.word.z_bit(target); - self.word - .set_xz_bits2(control, xc, zc ^ xt ^ zt, target, xt ^ xc, zt ^ xc); - self.flip_sign_if(xc && (xt ^ zt) && !(zc ^ zt)); + let (_, flip) = rule(self.word.x_bit(q), self.word.z_bit(q)); + self.flip_sign_if(flip); } } @@ -184,6 +73,47 @@ mod tests { type TestWord = Phased; + /// Both word types under `Phased` agree on random circuits, phase included. + #[test] + fn word_types_agree_on_bits_and_phase() { + let mut seed = 0xD1B5_4A32_D192_ED03u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..64 { + let start: String = (0..64) + .map(|_| ['I', 'X', 'Y', 'Z'][(next() % 4) as usize]) + .collect(); + let mut plain = PhasedPauliWord::new(start.as_str().into()); + let mut lossy = TestWord::new(start.as_str().into()); + for _ in 0..256 { + let (g, a) = (next() % 13, (next() % 64) as usize); + let b = (a + 1 + (next() % 63) as usize) % 64; + for w in [&mut plain as &mut dyn Clifford, &mut lossy] { + match g { + 0 => w.x(a), + 1 => w.y(a), + 2 => w.z(a), + 3 => w.h(a), + 4 => w.s(a), + 5 => w.s_dag(a), + 6 => w.sqrt_x(a), + 7 => w.sqrt_x_dag(a), + 8 => w.sqrt_y(a), + 9 => w.sqrt_y_dag(a), + 10 => w.cnot(a, b), + 11 => w.cz(a, b), + _ => w.cy(a, b), + } + } + } + assert_eq!(plain.to_string(), lossy.to_string()); + } + } + #[test] fn gates_touching_lost_sites_preserve_word_and_phase() { use ppvm_traits_2::Phase; From 319ac3e47ee8885d8dc45328adf516e9f448ad11 Mon Sep 17 00:00:00 2001 From: David Plankensteiner Date: Tue, 10 Nov 2026 16:50:47 +0100 Subject: [PATCH 6/7] Remove the SymplecticColumns and PhaseTrack primitive traits They were the building blocks of a blanket Clifford impl that never landed on main, and since the ApplyGateRule ports nothing calls them: every word type now gets Clifford from ApplyGateRule, with the gate formulas in ppvm-pauli-kernels. Drops both traits from ppvm-traits-2 and their impls from PauliWord and LossyPauliWord. The bounds-check tests no longer list the primitives (they still cover all 13 gates), and the lossy word's three primitive tests now drive the corresponding gates (H, S, CNOT, CZ) with the same expected results. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../ppvm-lossy-pauli-word-2/src/clifford.rs | 117 ++---------------- crates/ppvm-pauli-word-2/src/clifford.rs | 102 +-------------- crates/ppvm-traits-2/src/lib.rs | 2 +- crates/ppvm-traits-2/src/pauli.rs | 48 ------- 4 files changed, 17 insertions(+), 252 deletions(-) diff --git a/crates/ppvm-lossy-pauli-word-2/src/clifford.rs b/crates/ppvm-lossy-pauli-word-2/src/clifford.rs index 1478823c1..146aba24c 100644 --- a/crates/ppvm-lossy-pauli-word-2/src/clifford.rs +++ b/crates/ppvm-lossy-pauli-word-2/src/clifford.rs @@ -1,107 +1,15 @@ // SPDX-FileCopyrightText: 2026 The PPVM Authors // SPDX-License-Identifier: Apache-2.0 -//! X/Z bit operations skip lost qubits and invalidate only the X/Z hash. -//! Lossy words store no phase, so phase updates do nothing. -//! //! `LossyPauliWord` implements `ApplyGateRule`, so it gets `Clifford` from the //! blanket impl: a gate touching a lost site does nothing; otherwise the bits come //! from `ppvm_pauli_kernels::heisenberg` and the sign flip is dropped. use ppvm_pauli_word_2::{PauliStorage, xor_bits2}; -use ppvm_traits_2::{ApplyGateRule, PhaseTrack, SymplecticColumns}; +use ppvm_traits_2::ApplyGateRule; use crate::LossyPauliWord; -impl SymplecticColumns for LossyPauliWord { - fn n_qubits(&self) -> usize { - self.nqubits - } - - fn swap_xz(&mut self, q: usize) { - debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - if self.is_lost(q) { - return; - } - let (x, z) = (self.xbits[q], self.zbits[q]); - self.xbits.set(q, z); - self.zbits.set(q, x); - self.invalidate_xz_hash(); - } - - fn xor_z_from_x(&mut self, q: usize) { - debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - if self.is_lost(q) { - return; - } - let z = self.zbits[q] ^ self.xbits[q]; - self.zbits.set(q, z); - self.invalidate_xz_hash(); - } - - fn xor_x_col(&mut self, control: usize, target: usize) { - debug_assert!( - control < self.nqubits && target < self.nqubits, - "qubit out of bounds" - ); - if self.is_lost(control) || self.is_lost(target) { - return; - } - let target_x = self.xbits[target] ^ self.xbits[control]; - self.xbits.set(target, target_x); - self.invalidate_xz_hash(); - } - - fn xor_z_col(&mut self, target: usize, control: usize) { - debug_assert!( - control < self.nqubits && target < self.nqubits, - "qubit out of bounds" - ); - if self.is_lost(control) || self.is_lost(target) { - return; - } - let control_z = self.zbits[control] ^ self.zbits[target]; - self.zbits.set(control, control_z); - self.invalidate_xz_hash(); - } - - fn cz_bits(&mut self, a: usize, b: usize) { - debug_assert!(a < self.nqubits && b < self.nqubits, "qubit out of bounds"); - if self.is_lost(a) || self.is_lost(b) { - return; - } - let z_a = self.zbits[a] ^ self.xbits[b]; - let z_b = self.zbits[b] ^ self.xbits[a]; - self.zbits.set(a, z_a); - self.zbits.set(b, z_b); - self.invalidate_xz_hash(); - } -} - -/// Phase updates are no-ops because the word stores only X, Z, and loss bits. -impl PhaseTrack for LossyPauliWord { - #[inline] - fn flip_phase_where_xz(&mut self, _q: usize) {} - - #[inline] - fn s_phase(&mut self, _q: usize) {} - - #[inline] - fn cnot_phase(&mut self, _ctrl: usize, _tgt: usize) {} - - #[inline] - fn cz_phase(&mut self, _a: usize, _b: usize) {} - - #[inline] - fn x_phase(&mut self, _q: usize) {} - - #[inline] - fn y_phase(&mut self, _q: usize) {} - - #[inline] - fn z_phase(&mut self, _q: usize) {} -} - impl ApplyGateRule for LossyPauliWord { type B = bool; @@ -253,12 +161,12 @@ mod tests { fn single_qubit_operations_transform_present_sites() { let mut word = LossyPauliWord::::from("XYZL"); - word.swap_xz(0); - word.swap_xz(2); + word.h(0); + word.h(2); assert_eq!(word.to_string(), "ZYXL"); - word.xor_z_from_x(1); - word.xor_z_from_x(2); + word.s(1); + word.s(2); assert_eq!(word.to_string(), "ZXYL"); } @@ -266,11 +174,10 @@ mod tests { fn two_qubit_operations_transform_present_sites() { let mut word = LossyPauliWord::::from("XZ"); - word.xor_x_col(0, 1); - word.xor_z_col(1, 0); + word.cnot(0, 1); assert_eq!(word.to_string(), "YY"); - word.cz_bits(0, 1); + word.cz(0, 1); assert_eq!(word.to_string(), "XX"); } @@ -280,11 +187,11 @@ mod tests { let mut word = LossyPauliWord::::from(input); let lost = if word.is_lost(0) { 0 } else { 1 }; - word.swap_xz(lost); - word.xor_z_from_x(lost); - word.xor_x_col(0, 1); - word.xor_z_col(1, 0); - word.cz_bits(0, 1); + word.h(lost); + word.s(lost); + word.cnot(0, 1); + word.cnot(1, 0); + word.cz(0, 1); assert_eq!(word, LossyPauliWord::from(input)); } diff --git a/crates/ppvm-pauli-word-2/src/clifford.rs b/crates/ppvm-pauli-word-2/src/clifford.rs index 83690cc50..d6498049b 100644 --- a/crates/ppvm-pauli-word-2/src/clifford.rs +++ b/crates/ppvm-pauli-word-2/src/clifford.rs @@ -5,12 +5,11 @@ //! `PauliWord` implements `ApplyGateRule`, so `Clifford` comes from the blanket impl //! and each gate's bits from `ppvm_pauli_kernels::heisenberg`. The hash is //! refreshed once per gate, and only when a bit changes. -//! Symplectic bit operations remain available; `PhaseTrack` is a no-op. //! Phase signs must be handled separately by phased words or the sum engine. use std::hash::BuildHasher; -use ppvm_traits_2::{ApplyGateRule, PhaseTrack, SymplecticColumns}; +use ppvm_traits_2::ApplyGateRule; use crate::data::{PauliWord, xor_bits2}; use crate::{HashFinalize, PauliStorage}; @@ -67,91 +66,6 @@ where } } -impl SymplecticColumns for PauliWord -where - A: PauliStorage, - H: BuildHasher + Default + HashFinalize, -{ - #[inline] - fn n_qubits(&self) -> usize { - self.nqubits - } - - /// `H` on `q`: swap the X and Z bits. Touches only in-range slot `q`, so the - /// canonical-unused-bits invariant is preserved. - #[inline] - fn swap_xz(&mut self, q: usize) { - debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - let xb = self.xbits[q]; - let zb = self.zbits[q]; - self.xbits.set(q, zb); - self.zbits.set(q, xb); - self.refresh_hash(); - } - - /// `S` on `q`: `z_q ⊕= x_q` (maps `X → Y`). - #[inline] - fn xor_z_from_x(&mut self, q: usize) { - debug_assert!(q < self.nqubits, "qubit {q} out of bounds"); - let z = self.zbits[q] ^ self.xbits[q]; - self.zbits.set(q, z); - self.refresh_hash(); - } - - /// `CNOT` bit rule, part one: `x_tgt ⊕= x_ctrl`. - #[inline] - fn xor_x_col(&mut self, ctrl: usize, tgt: usize) { - debug_assert!( - ctrl < self.nqubits && tgt < self.nqubits, - "qubit out of bounds" - ); - let x = self.xbits[tgt] ^ self.xbits[ctrl]; - self.xbits.set(tgt, x); - self.refresh_hash(); - } - - /// `CNOT` bit rule, part two: `z_ctrl ⊕= z_tgt`. - #[inline] - fn xor_z_col(&mut self, tgt: usize, ctrl: usize) { - debug_assert!( - ctrl < self.nqubits && tgt < self.nqubits, - "qubit out of bounds" - ); - let z = self.zbits[ctrl] ^ self.zbits[tgt]; - self.zbits.set(ctrl, z); - self.refresh_hash(); - } - - /// `CZ` on `(a, b)`: `z_a ⊕= x_b` and `z_b ⊕= x_a`. - #[inline] - fn cz_bits(&mut self, a: usize, b: usize) { - debug_assert!(a < self.nqubits && b < self.nqubits, "qubit out of bounds"); - let za = self.zbits[a] ^ self.xbits[b]; - let zb = self.zbits[b] ^ self.xbits[a]; - self.zbits.set(a, za); - self.zbits.set(b, zb); - self.refresh_hash(); - } -} - -/// Bare words store no phase, so phase updates deliberately do nothing. -impl PhaseTrack for PauliWord { - #[inline] - fn flip_phase_where_xz(&mut self, _q: usize) {} - #[inline] - fn s_phase(&mut self, _q: usize) {} - #[inline] - fn cnot_phase(&mut self, _ctrl: usize, _tgt: usize) {} - #[inline] - fn cz_phase(&mut self, _a: usize, _b: usize) {} - #[inline] - fn x_phase(&mut self, _q: usize) {} - #[inline] - fn y_phase(&mut self, _q: usize) {} - #[inline] - fn z_phase(&mut self, _q: usize) {} -} - #[cfg(test)] mod tests { use super::*; @@ -170,7 +84,7 @@ mod tests { #[test] fn single_qubit_operations_enforce_logical_bounds() { - let operations: [fn(&mut PauliWord, usize); 12] = [ + let operations: [fn(&mut PauliWord, usize); 10] = [ PauliWord::x, PauliWord::y, PauliWord::z, @@ -181,8 +95,6 @@ mod tests { PauliWord::sqrt_x_dag, PauliWord::sqrt_y, PauliWord::sqrt_y_dag, - PauliWord::swap_xz, - PauliWord::xor_z_from_x, ]; for operation in operations { for invalid in [1, 7, 63] { @@ -194,14 +106,8 @@ mod tests { #[test] fn two_qubit_operations_enforce_logical_bounds() { - let operations: [fn(&mut PauliWord, usize, usize); 6] = [ - PauliWord::cnot, - PauliWord::cy, - PauliWord::cz, - PauliWord::xor_x_col, - PauliWord::xor_z_col, - PauliWord::cz_bits, - ]; + let operations: [fn(&mut PauliWord, usize, usize); 3] = + [PauliWord::cnot, PauliWord::cy, PauliWord::cz]; for operation in operations { for input in ["X", "Y", "Z"] { for invalid in [1, 7, 63] { diff --git a/crates/ppvm-traits-2/src/lib.rs b/crates/ppvm-traits-2/src/lib.rs index 27d9c5f57..56842b500 100644 --- a/crates/ppvm-traits-2/src/lib.rs +++ b/crates/ppvm-traits-2/src/lib.rs @@ -26,7 +26,7 @@ pub use gates::{ RotationTwo, RotationTwoBatch, TGate, TwoQubitPauliError, U3Gate, }; pub use loss::{LossState, LossySite}; -pub use pauli::{Pauli, PhaseTrack, SymplecticColumns}; +pub use pauli::Pauli; pub use word::{PauliBits, Word}; /// Common traits and types for implementing and using the interfaces. diff --git a/crates/ppvm-traits-2/src/pauli.rs b/crates/ppvm-traits-2/src/pauli.rs index 74aa71e45..524c4aef0 100644 --- a/crates/ppvm-traits-2/src/pauli.rs +++ b/crates/ppvm-traits-2/src/pauli.rs @@ -14,51 +14,3 @@ pub enum Pauli { /// Pauli `Z`. Z, } -/// Phase-free symplectic operations on X/Z bit columns. -/// Shared by single-word bits and multi-row tableau columns. -pub trait SymplecticColumns { - /// Number of qubits (columns) this operator spans. - fn n_qubits(&self) -> usize; - - /// `H` on `q`: swap the X and Z columns. - fn swap_xz(&mut self, q: usize); - - /// S bit update on `q`: `z_q ⊕= x_q` (maps X to Y). - fn xor_z_from_x(&mut self, q: usize); - - /// `CNOT` bit rule, part one: `x_tgt ⊕= x_ctrl`. - fn xor_x_col(&mut self, ctrl: usize, tgt: usize); - - /// `CNOT` bit rule, part two: `z_ctrl ⊕= z_tgt`. - fn xor_z_col(&mut self, tgt: usize, ctrl: usize); - - /// CZ bit update: `z_a ⊕= x_b` and `z_b ⊕= x_a`. - fn cz_bits(&mut self, a: usize, b: usize); -} - -/// Extension-part: the phase algebra. `ℤ₄` for a phased word, `ℤ₂` + the -/// Aaronson–Gottesman `g`-rule for a tableau. One phase delta per gate; the -/// role-dependent half of conjugation, written **per type**. -pub trait PhaseTrack { - /// `H` phase delta: flip the sign of a component with both `x` and `z` set - /// (`Y → −Y`). - fn flip_phase_where_xz(&mut self, q: usize); - - /// `S` phase delta on `q`. - fn s_phase(&mut self, q: usize); - - /// `CNOT` phase delta on `(ctrl, tgt)`. - fn cnot_phase(&mut self, ctrl: usize, tgt: usize); - - /// `CZ` phase delta on `(a, b)`. - fn cz_phase(&mut self, a: usize, b: usize); - - /// `X` phase delta on `q` (pure sign; no bit change). - fn x_phase(&mut self, q: usize); - - /// `Y` phase delta on `q` (pure sign; no bit change). - fn y_phase(&mut self, q: usize); - - /// `Z` phase delta on `q` (pure sign; no bit change). - fn z_phase(&mut self, q: usize); -} From 03455a0645c2deb2fbf39bf382363276e6aa25be Mon Sep 17 00:00:00 2001 From: David Plankensteiner Date: Tue, 17 Nov 2026 13:39:53 +0100 Subject: [PATCH 7/7] docs(traits-2): document ApplyGateRule call-once contract; scope Lean mise config to lean/ Phased reads the sign flip from the rule call, so state that words must call the rule exactly once per applied gate and never on skipped ones. Move elan, its PATH entry and the lean-* tasks into lean/mise.toml so contributors who don't touch lean/ no longer install elan. Co-Authored-By: Claude Opus 5.5 --- .../ppvm-phased-pauli-word-2/src/clifford.rs | 3 ++- .../ppvm-traits-2/src/gates/apply_gate_rule.rs | 5 +++++ lean/README.md | 3 +++ lean/mise.toml | 17 +++++++++++++++++ mise.toml | 18 ------------------ 5 files changed, 27 insertions(+), 19 deletions(-) create mode 100644 lean/mise.toml diff --git a/crates/ppvm-phased-pauli-word-2/src/clifford.rs b/crates/ppvm-phased-pauli-word-2/src/clifford.rs index 4dc9e3f9f..32e343cd9 100644 --- a/crates/ppvm-phased-pauli-word-2/src/clifford.rs +++ b/crates/ppvm-phased-pauli-word-2/src/clifford.rs @@ -25,7 +25,8 @@ impl Phased { } /// A word that skips a gate (e.g. on a lost site) never calls the rule, so the -/// recorded flip stays `false` and the phase is untouched. +/// recorded flip stays `false` and the phase is untouched. This relies on `W` +/// calling the rule once per applied gate, as `ApplyGateRule` requires. impl ApplyGateRule for Phased where W: ApplyGateRule + PauliBits + LossInfo, 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 6b9c7fc57..674bce625 100644 --- a/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs +++ b/crates/ppvm-traits-2/src/gates/apply_gate_rule.rs @@ -20,6 +20,11 @@ use super::Clifford; /// Paulis one at a time; with an integer `B` each bit position is a separate /// Pauli. A container without signs ignores the flip. /// +/// 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. +/// /// Implementing this trait gives [`Clifford`] through the blanket impl, so a /// type must not also implement [`Clifford`] by hand. pub trait ApplyGateRule { diff --git a/lean/README.md b/lean/README.md index 947b3f992..1e79bb402 100644 --- a/lean/README.md +++ b/lean/README.md @@ -3,6 +3,9 @@ Proofs for `crates/ppvm-pauli-kernels`. Core Lean only (no Mathlib); every fact is decided in the kernel. +Run these from `lean/`; its `mise.toml` installs elan and defines the tasks +(run `mise trust` there once). + ```sh mise run lean-build # lake build mise run lean-tables # regenerate crates/ppvm-pauli-kernels/tests/generated/tables.rs diff --git a/lean/mise.toml b/lean/mise.toml new file mode 100644 index 000000000..4a2984543 --- /dev/null +++ b/lean/mise.toml @@ -0,0 +1,17 @@ +# Lean tooling, scoped to `lean/` so other contributors don't install elan. +[tools] +# Lean toolchain manager. `elan` reads `lean-toolchain` and provisions the +# pinned Lean/Lake proxies into `~/.elan/bin`. +"github:leanprover/elan" = "4.2.4" + +[env] +# Put the elan-managed `lean` / `lake` proxies on PATH for mise tasks and shells. +_.path = ["~/.elan/bin"] + +[tasks.lean-build] +description = "Build the PPVM Lean formalization (lake build)." +run = "lake build" + +[tasks.lean-tables] +description = "Regenerate the ppvm-pauli-kernels test tables from the Lean matrix model." +run = "lake env lean --run scripts/GenTables.lean > ../crates/ppvm-pauli-kernels/tests/generated/tables.rs" diff --git a/mise.toml b/mise.toml index d9b2a932d..cb7a32d3d 100644 --- a/mise.toml +++ b/mise.toml @@ -8,21 +8,3 @@ prek = "0.4.14" "cargo:cargo-machete" = "0.9.2" # Local release preview (`release-plz update`); same version the CI action uses release-plz = "0.3.169" -# Lean toolchain manager. `elan` reads `lean/lean-toolchain` and provisions the -# pinned Lean/Lake proxies into `~/.elan/bin`. -"github:leanprover/elan" = "4.2.4" - -[env] -# Put the elan-managed `lean` / `lake` proxies on PATH for mise tasks and shells. -_.path = ["~/.elan/bin"] - -# Runs inside `lean/` so elan picks up `lean/lean-toolchain`. -[tasks.lean-build] -description = "Build the PPVM Lean formalization (lake build)." -dir = "lean" -run = "lake build" - -[tasks.lean-tables] -description = "Regenerate the ppvm-pauli-kernels test tables from the Lean matrix model." -dir = "lean" -run = "lake env lean --run scripts/GenTables.lean > ../crates/ppvm-pauli-kernels/tests/generated/tables.rs"