High-order perturbative expansions (such as 14th-order pCUT) simultaneously face two classic computer-algebra bottlenecks: intermediate expression swell (tens or hundreds of millions of terms that overwhelm in-memory hash tables) and coefficient swell (arbitrary-precision rationals growing to thousands of bits before cancellation). Weyl eliminates both bottlenecks through three tightly integrated crates: weyl-canonical, weyl-cas, and weyl-num.
Graded Operator Canonicalization (weyl-canonical)
Every operator algebra implements the zero-allocation GradedAlgebra trait (weyl-canonical/src/algebra.rs), reducing products and adjoints directly into canonical monomial byte strings plus an exact phase:
pub trait GradedAlgebra {
type Word: AsRef<[u8]> + Ord + Hash;
type Phase: Copy;
fn grade(w: &Self::Word) -> Grade;
fn mul(a: &Self::Word, b: &Self::Word, out: &mut WordBuf) -> Self::Phase;
fn commutes(a: &Self::Word, b: &Self::Word) -> bool;
fn adjoint(w: &Self::Word, out: &mut WordBuf) -> Self::Phase;
}Physical operator families map onto GradedAlgebra as follows:
| Algebra Family | Canonical Word Encoding | Multiplication & Normal-Form Rule | Complexity |
|---|---|---|---|
| Pauli (Spin-1/2) | Site-sorted big-endian u32 list (site << 2) | code (X=1, Y=2, Z=3); global phase in | Linear merge of two sorted lists; phase table on colliding sites; commutation is parity of differing shared sites | |
| Majorana Fermions | Sorted u32 mode-index list | Linear merge counting inversions for and cancelling | |
| CAR Fermions | Normal-ordered creation-left, annihilation-right list | Koszul sign on disjoint supports; recursive contractions on overlaps | Local-support polynomial |
| CCR Bosons | Normal-ordered creation-left, annihilation-right (truncated at ) | Commute on disjoint supports; Wick contractions via on overlaps | Local-support polynomial |
Group Algebra GroupQudit<G> | Tensor product of unique single-site basis () | in lookup; coefficients in |
Byte Order Equals Lexicographic Order
Encoding each Pauli factor as a big-endian u32 (site << 2) | code guarantees that lexicographic order on canonical Pauli words matches raw byte-wise memcmp. Downstream term-stream sorters can therefore radix-sort flat byte buffers directly without deserializing AST nodes.
Worked Example: Linear Pauli Merge and Phase Table
Consider two sparse Pauli words ([0x00000009, 0x00000017]) and ([0x0000000A, 0x00000017, 0x00000025]). GradedAlgebra::mul sweeps both sorted slices with two pointers, consulting the single-site table on colliding sites:
| Left \ Right | (01) | (10) | (11) |
|---|---|---|---|
(01) | |||
(10) | |||
(11) |
As the two-pointer sweep advances, site 2 collides first with , so the merge appends (2 << 2) | 3 to WordBuf and advances the phase by (). Next, site 5 collides with , causing exact cancellation: nothing is emitted to WordBuf and the phase remains unchanged. Site 9 appears only in , so X_9 is copied directly into WordBuf. The sweep concludes with ; because the two words share 1 differing site (site 2), commutes(A, B) == false, and the entire operation completes in time with zero heap allocations.
FORM-Inspired Streaming Term Architecture (weyl-cas)
Conventional CAS engines built on global hash tables thrash CPU caches and exhaust RAM once intermediate terms reach . Inspired by FORM, weyl-cas represents streams as flat, 8-byte-aligned records:
/// Fixed 8-byte aligned record header; flat wire layout:
/// [TermHeader (8B)][coeff: [u64; K]][mono: mono_len bytes][pad to 8]
#[repr(C, align(8))]
pub struct TermHeader {
pub len: u32, // aligned record size: (8 + 8*K + mono_len + 7) & !7
pub mono_len: u16, // parameter monomial prefix + canonical operator bytes
pub flags: u16, // bit 0 = FLAG_IMAGINARY separating real & imag parts (i^2 = -1)
}
/// One-word wire coefficient trait: each slot fixes its prime context PrimeId once per stream
pub trait WireCoeff: Field + Send + Sync {
type Ctx: Copy + Eq + Send + Sync;
fn ctx(self) -> Self::Ctx;
fn join_ctx(a: Self::Ctx, b: Self::Ctx) -> Option<Self::Ctx>;
fn to_word(self) -> u64;
fn from_word(word: u64, ctx: Self::Ctx) -> Self;
}In memory, a compact TermRecord carries an 8-byte TermHeader plus lightweight slice/vector metadata (a 24-byte structural footprint for compact records). Inside the flat sort buffer, for 63-bit primes (32-byte coefficient vector) and a 12-byte monomial, each record occupies 56 contiguous bytes:
Offset (bytes): 0..4 4..6 6..8 8..40 40..52 52..56
Field: [len=56] [mono=12] [flags=0] [coeff: [u64;4]] [mono: 12 bytes] [pad: 4B]There is zero pointer chasing; perturbative parameter monomials (such as ) are prepended directly onto mono, so multivariate series combine like terms automatically without polynomial interpolation.
Sort-Merge and External NVMe Spill Pipeline
SortingSink normalizes arbitrary incoming term streams in four deterministic stages. Generated terms first append sequentially into a fixed-size buffer (DEFAULT_BUFFER_BYTES = 256 MiB) to maximize write bandwidth. Once the buffer fills, it is sorted in place by key (mono, flags & FLAG_IMAGINARY) using most-significant-digit radix sort (MAX_RADIX_DEPTH = 64, falling back to comparison sort for buckets SMALL_BUCKET = 48), followed by a single linear scan that merges adjacent like-term coefficient vectors and drops all-zero terms. Whenever accumulated sorted runs exceed MemBudget, runs spill sequentially to SpillDir on NVMe storage, and SortingSink::finish merges all in-memory and on-disk runs through a -way loser tree (FAN_IN = 256), combining like terms across runs on the fly. For buffers containing at least PARALLEL_MIN_TERMS (4096) terms, splitter sampling partitions disjoint monomial ranges across worker threads and concatenates their outputs directly; because byte order is total and addition is commutative and associative, the resulting output bytes are invariant to buffer size, spill boundaries, and thread count.
| Reduction Strategy | Peak Memory Behavior | Cache Locality | Measured Single-Core Throughput |
|---|---|---|---|
Naive hash table (normalize_naive) | Linear in distinct terms; high-load thrashing | Random pointer chasing | L3 differential reference only |
In-RAM MSD radix sort-merge (weyl-cas) | Hard-capped by MemBudget | Sequential writes + contiguous buckets | 1.21 × 10⁷ terms/s (1M terms in 82.89 ms) |
| External -way loser-tree spill | Bounded working set ( terms ) | Large sequential NVMe I/O | Bounded by NVMe sequential bandwidth |
Tuning Constants and Streaming Execution Model
weyl-cas/src/sort.rs centralizes the external-memory tuning constants to align with CPU cache lines and NVMe transfer blocks:
pub const DEFAULT_BUFFER_BYTES: usize = 256 << 20; // 256 MiB per-chunk sort buffer
const FAN_IN: usize = 256; // max ways merged per loser-tree pass
const SMALL_BUCKET: usize = 48; // MSD radix fallback to comparison sort
const MAX_RADIX_DEPTH: usize = 64; // max radix depth guarding long prefixes
const PARALLEL_MIN_TERMS: usize = 1 << 12; // keep < 4096 terms single-threadedAs KirOp::Apply streams perturbative operators onto state vectors, outputs flow directly into SortingSink. Whenever spilled runs exceed FAN_IN = 256, multi-pass merging keeps open file descriptors and merge buffers strictly within MemBudget. The KIR execution engine composes five pure streaming operators into a single pipeline: KirOp::Load(SourceRef) seeds initial vacuum or single-quasiparticle state streams from SIR templates; KirOp::Apply acts with local operators on syndrome bitstrings while filtering allowed components dynamically via without materializing projectors; KirOp::Project(Sector) filters streams by conserved charges and quasiparticle sector; KirOp::Normalize drives the chunked MSD radix sort, NVMe spill, and -way loser-tree merge; and KirOp::Reconstruct invokes multi-prime CRT or Wang rational reconstruction on the final reduced stream to emit exact rational series tables.
63-Bit Modular Arithmetic, CRT, and Wang Reconstruction (weyl-num)
To avoid big-integer GCD overhead during intermediate accumulation, rational coefficients are accumulated simultaneously across coprime 63-bit prime fields (, curated in weyl-num/src/fp.rs as PRIMES_63: ):
// weyl-num/src/fp.rs: curated 63-bit primes (< 2^63, leaving headroom for u128 reduction)
pub const PRIMES_63: &[u64] = &[
9_223_372_036_854_775_783, // 2^63 - 25
9_223_372_036_854_775_643, // 2^63 - 165
9_223_372_036_854_775_549, // 2^63 - 259
9_223_372_036_854_775_507, // 2^63 - 301
// ... 16 verified 63-bit primes (> 1000 bits of combined CRT capacity)
];
// Pick the first k 63-bit primes coprime to the per-order common denominator D_k
let primes: Vec<PrimeId> = PrimeTable::select_coprime(k, common_denom_d_k);Intermediate Pauli phases are tracked via FLAG_IMAGINARY, keeping real and imaginary residues separate in with multiplication obeying . Real physical observables verify that all imaginary residues vanish identically across all primes.
A Priori Bounds and Guaranteed Uniqueness
Weyl never stops heuristically when an extra prime happens to agree; instead, prime counts are fixed statically before expansion using a priori bounds. When a common denominator is known in advance—as in pCUT, where exact rational tables , energy scaling , cluster embedding counts, and inclusion-exclusion weights determine both and a strict integer numerator bound on -scaled outputs—centered CRT lifting applies directly. Choosing primes such that
guarantees that combining residues via the Chinese Remainder Theorem into and taking the centered representative
recovers the exact rational with mathematical certainty.
When no common denominator is known in advance and only a numerator bound and denominator bound are available, Wang’s rational reconstruction selects primes with and runs the extended Euclidean recurrence on ,
terminating at the first step satisfying and . Provided , this uniquely recovers (normalized with ); if the modulus product is insufficient, the reconstructor fails explicitly with NumError::InsufficientPrimes rather than guessing.
pub enum NumError {
DivisionByZero,
NonCoprimeModuli,
EmptyResidues,
InsufficientPrimes, // prime product cannot exceed the a priori bound
DenominatorMismatch, // recovered denominator does not divide declared D_k
}Worked Example: Recovering an Order-10 pCUT Coefficient
Suppose an order- linked-cluster expansion has a priori common denominator and integer numerator bound . Since each 63-bit prime supplies decimal digits of dynamic range, coprime primes yield . During execution, weyl-cas accumulates all four prime lanes in parallel and reduces the target monomial’s residue vector to . Finally, weyl-num::crt_centered combines those residues into the unique centered integer and constructs the reduced Rational::new(n, D_10). Because was proven before expansion, modular wraparound is mathematically impossible.
Certification Gate for Symbolic Interpolation
Any rational-function interpolation over symbolic parameters requires independent degree bounds and exact algebraic identity verification; unverified interpolants are never tagged Exact.