Within Weyl’s four-layer IR stack, weyl-canonical and weyl-egraph play strictly complementary roles. weyl-canonical provides a single unique normal form for monomials inside high-throughput KIR term streams. At the symbolic template layer (SIR), however, a single physical Hamiltonian admits an exponential family of algebraically equivalent forms—differing in translation-orbit representatives, scalar factorizations, operator reorderings, and tensor contraction schedules. Fixed-order rewrite passes suffer from the classic phase-ordering problem. weyl-egraph uses equality saturation to represent all equivalent forms simultaneously in a compact graph, then extracts the globally optimal expression for each downstream backend.
| Dimension | weyl-canonical (Normal Forms) | weyl-egraph (Equality Saturation) |
|---|---|---|
| Target IR Layer | KIR flat term-stream kernel | SIR template layer (prior to KIR / TIR / Lean lowering) |
| Representation | Single unique canonical word | Exponential equivalence family in polynomial space |
| TCB Status | Trusted kernel (TCB) | Untrusted search; certified by verify_sir_equivalence |
| Optimization Goal | Throughput ( terms/s) & byte uniqueness | Global cost minimization (support width, FLOPs, rank) |
Compact Equivalence Families: E-Graph & Operator Language
weyl-egraph is built on egg with its deterministic feature enabled (weyl/crates/weyl-egraph/src/egraph.rs). An e-graph partitions expressions into e-classes of semantically equivalent e-nodes, whose children reference e-class IDs (Id) rather than concrete trees—compressing exponentially many equivalent expressions into polynomial memory.
The SIR local-operator language is defined as:
/// Lattice site inside a template: unit-cell offset (dx, dy) + sublattice name
pub type SiteKey = (CellOffset, SmolStr);
pub struct Factor {
pub site: SiteKey,
pub axis: PauliAxis,
}
define_language! {
pub enum ENode {
"word" = Word(Box<[Id]>), // ordered product of factor classes (empty = identity 1)
"i" = I1(Id), // +i times child class
"neg" = I2(Id), // -1 times child class
"neg-i" = I3(Id), // -i times child class
Factor(Factor), // single-site Pauli generator, e.g. X@0,1,h
}
}To uphold Weyl’s determinism guarantee (bit-identical output across machines), saturation never uses wall-clock timeouts; termination is bounded purely by iteration count and node quota:
pub struct Limits {
pub max_iterations: usize, // default: 64
pub max_nodes: usize, // default: 20_000
}
/// Single rewrite application recorded during saturation for auditable proof traces
pub struct Applied {
pub rule: &'static str, // "pauli-mul" | "sort-disjoint" | "phase-flatten"
pub from: Id,
pub to: Id,
}Each iteration uses the custom Composite searcher to locate e-classes containing Word or phase wrappers, then runs PauliRule to equate equivalent targets via egraph.union(class, target). With egg’s deterministic hashing and SimpleScheduler, identical inputs always yield identical saturated graphs, extractions, and Applied traces.
AC and Graded-Commutation Rewrite Rules
Unlike destructive term rewriting, e-graph rules perform only monotonic unions and congruence closure, never discarding prior representations. weyl-egraph organizes rules into two layers:
1. Local Operator Algebra Rules (Inside E-Graph Saturation)
Inside e-graph saturation, three local operator algebra rules govern how words simplify. The pauli-mul rule contracts adjacent same-site factors (, , ), inserting the reduced Word alongside phase wrappers I1/I2/I3. Complementing it, sort-disjoint applies associative-commutative (AC) reordering across disjoint sites, (), with Majorana and CAR fermionic extensions introducing I2 () according to inversion parity under graded commutation. Meanwhile, phase-flatten hoists nested I1/I2/I3 nodes out of Word products and folds them modulo 4 in (for example, i(neg(w)) neg-i(w)).
2. Model-Level SIR Canonicalization Rules (KNOWN_RULES)
Following e-graph extraction, model-level passes apply the rules cataloged in weyl-egraph/src/proof.rs:
| Rule Identifier | Scope | Algebraic Action |
|---|---|---|
pauli-mul / sort-disjoint / phase-flatten | E-graph local word | Same-site contraction, disjoint AC sort, phase hoisting |
phase-fold | Template coefficient | Absorbs outer phases into exact ParamPoly |
orbit-shift | Translation orbit | Shifts template offsets to the lexicographically minimal representative |
coeff-normal / drop-zero | Linear combination | Canonicalizes multivariate polynomials and prunes zero templates |
merge-coeff / factor-scalar | SIR model | Combines identical normal words or factors shared scalar prefactors |
external-candidate | MCP sandbox | Untrusted candidate rewrite submitted via weyl.rewrite.propose |
Cost Functions and Extraction for SIR KIR / TIR
Once saturation finishes, egg::Extractor recursively selects the minimum-cost representative of each e-class. Swapping only the CostFunction tailors extraction to each lowering target without phase-ordering regressions:
| Lowering Target | Primary Cost Objective | Physical / Computational Payoff |
|---|---|---|
| SIR KIR (Perturbation) | $\text{cost}(w) = ( | \mathrm{supp}(w) |
| SIR TIR (Tensor Network) | Jointly optimizes contraction order, intermediate rank, and bond dimension | |
| String-Diagram SIR Lean 4 | Minimum non-trivial rewrite steps | Shortens exported MonoidalCategory equality chains |
Below is the SIR KIR support-minimizing CostFunction: its lexicographic tuple minimizes operator factor count first (directly shrinking cluster length), phase nesting depth second, and breaks ties deterministically:
struct NormalFormCost;
impl CostFunction<ENode> for NormalFormCost {
type Cost = (usize, usize, usize); // (factor_count, phase_depth, tie_breaker)
fn cost<C>(&mut self, enode: &ENode, mut costs: C) -> Self::Cost
where
C: FnMut(Id) -> Self::Cost,
{
match enode {
ENode::Factor(_) => (1, 0, 1),
ENode::Word(children) => {
let (mut f, mut p, mut t) = (0, 0, 1);
for &id in children.iter() {
let (cf, cp, ct) = costs(id);
f += cf; p += cp; t += ct;
}
(f, p, t)
}
ENode::I1(c) | ENode::I2(c) | ENode::I3(c) => {
let (cf, cp, ct) = costs(*c);
(cf, cp + 1, ct + 1)
}
}
}
}Eliminating Phase-Ordering Bugs
In sequential pass pipelines, “factor scalars before orbit-shifting” and “orbit-shift before merging like terms” frequently block each other: unshifted templates hide identical orbits, while eager merging can obscure lower-rank tensor factorizations. Equality saturation explores all rule interleavings concurrently until saturation or node limit, letting Extractor choose the globally optimal form in one pass.
Trusted Equivalence Checker & LLM-Proposed Rewrites
Weyl adheres strictly to the de Bruijn criterion: neither the e-graph search nor an LLM is inside the trusted computing base. Every rewrite—whether discovered by built-in saturation or proposed by an LLM through weyl.rewrite.propose—must pass verify_sir_equivalence in weyl-egraph/src/proof.rs:
pub struct EquivalenceProof {
pub steps: Vec<ProofStep>, // step-by-step trace (rule, template, before, after)
pub verified: bool, // set true ONLY by verify_sir_equivalence succeeding
}
pub enum RewriteRejection {
UnknownRule(String), // trace cites a rule unknown to the kernel
NotEquivalent(String), // source and target differ in normal form at named word
TypeNotPreserved(String), // output template lost grade/charge/Hermiticity tags
}The checker enforces two non-negotiable run-time invariants (corresponding to Conjecture 2: Preservation under Rewriting in Type System §8; this is a per-rewrite run-time check, not a proven static metatheorem). First, exact normal-form equivalence expands both the source and rewritten SirModels into linear combinations keyed by NormalKey with exact ParamPoly coefficients and checks that ; numerical oracles such as ED can never approve a rewrite:
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct NormalKey {
pub region: RegionClassId, // translation-equivalence region class
pub is_unperturbed: bool, // belongs to H₀ vs perturbation V
pub word: Vec<(i32, i32, SmolStr, u8)>, // canonically sorted local operator word
}Second, type-tag preservation re-verifies every output template’s GradeSet, Herm, and SuppTemplate so that no rewrite can weaken physical guarantees or inflate error grades .
Below is an untrusted LLM proposal submitted via weyl-mcp (weyl.rewrite.propose) before kernel certification:
{
"schema": "weyl.action",
"kind": "rewrite.propose",
"graph": "toric_boundary@a1b2c3",
"rule": "external-candidate",
"template": "boundary_perturbation_0",
"before": "X@0,0,d * Z@1,0,h * Y@0,0,d",
"after": "i * Z@0,0,d * Z@1,0,h",
"rationale": "commute Z@1,0,h past Y@0,0,d and contract X*Y = iZ to shrink support"
}The compiler ignores rationale completely and passes before/after to verify_sir_equivalence, returning RewriteRejection::NotEquivalent if the normal-form difference is non-zero or RewriteRejection::TypeNotPreserved if Hermiticity or grade tags fail to match.
Worked Example: Saturating and Certifying a Boundary Template
Consider an unsimplified local boundary product generated during symbolic composition:
Once ENode::Word([X@0,0,d, Z@1,0,h, Y@0,0,d]) enters the e-graph, saturation unfolds in three steps: sort-disjoint commutes the disjoint factors into [X@0,0,d, Y@0,0,d, Z@1,0,h], pauli-mul contracts same-site X·Y into I1(Z@0,0,d), and phase-flatten hoists i to produce I1(Word([Z@0,0,d, Z@1,0,h])). Extraction then chooses the 2-site word i · Z@0,0,d Z@1,0,h over the 3-factor original, and phase-fold absorbs into the template’s coefficient polynomial while recording each ProofStep. Finally, verify_sir_equivalence independently evaluates canonical_word and ParamPoly for both models, confirms exact equality and preserved Herm tags, sets verified = true, and clears the rewritten SIR for KIR lowering.