Skip to content
Symbolic & Numerical Algorithms · Equality Saturation

E-Graph Equality Saturation & Canonical Rewriting

How weyl-egraph complements normal forms via deterministic equality saturation, eliminates phase-ordering bugs, optimizes SIR-to-KIR/TIR lowering, and certifies untrusted LLM rewrites.

Within Weyl’s four-layer IR stack, weyl-canonical and weyl-egraph play strictly complementary roles. weyl-canonical provides a single O(∣A∣+∣B∣)O(|A|+|B|) 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.

Dimensionweyl-canonical (Normal Forms)weyl-egraph (Equality Saturation)
Target IR LayerKIR flat term-stream kernelSIR template layer (prior to KIR / TIR / Lean lowering)
RepresentationSingle unique canonical wordExponential equivalence family in polynomial space
TCB StatusTrusted kernel (TCB)Untrusted search; certified by verify_sir_equivalence
Optimization GoalThroughput (≥107\ge 10^7 terms/s) & byte uniquenessGlobal 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:

rust
/// 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:

rust
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 (XsXs↔1X_s X_s \leftrightarrow 1, XsYs↔iZsX_s Y_s \leftrightarrow i Z_s, YsXs↔−iZsY_s X_s \leftrightarrow -i Z_s), inserting the reduced Word alongside phase wrappers I1/I2/I3. Complementing it, sort-disjoint applies associative-commutative (AC) reordering across disjoint sites, AsBt↔BtAsA_s B_t \leftrightarrow B_t A_s (s≠ts \neq t), with Majorana and CAR fermionic extensions introducing I2 (−1-1) 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 Z4\mathbb{Z}_4 (for example, i(neg(w)) ↔\leftrightarrow 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 IdentifierScopeAlgebraic Action
pauli-mul / sort-disjoint / phase-flattenE-graph local wordSame-site contraction, disjoint AC sort, Z4\mathbb{Z}_4 phase hoisting
phase-foldTemplate coefficientAbsorbs outer ±1,±i\pm 1, \pm i phases into exact ParamPoly
orbit-shiftTranslation orbitShifts template offsets to the lexicographically minimal representative
coeff-normal / drop-zeroLinear combinationCanonicalizes multivariate polynomials and prunes zero templates
merge-coeff / factor-scalarSIR modelCombines identical normal words or factors shared scalar prefactors
external-candidateMCP sandboxUntrusted candidate rewrite submitted via weyl.rewrite.propose

Cost Functions and Extraction for SIR →\to 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 TargetPrimary Cost ObjectivePhysical / Computational Payoff
SIR →\to KIR (Perturbation)$\text{cost}(w) = (\mathrm{supp}(w)
SIR →\to TIR (Tensor Network)cost(e)=∑contractFLOPs(e)+λ⋅max⁡χrank\text{cost}(e) = \sum_{\text{contract}} \text{FLOPs}(e) + \lambda \cdot \max \chi_{\text{rank}}Jointly optimizes contraction order, intermediate rank, and bond dimension χ\chi
String-Diagram SIR →\to Lean 4Minimum non-trivial rewrite stepsShortens exported MonoidalCategory equality chains

Below is the SIR →\to KIR support-minimizing CostFunction: its lexicographic tuple minimizes operator factor count first (directly shrinking cluster length), phase nesting depth second, and breaks ties deterministically:

rust
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:

rust
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 Mbefore−Mafter≡0M_{\text{before}} - M_{\text{after}} \equiv 0; numerical oracles such as ED can never approve a rewrite:

rust
#[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 ε\varepsilon.

Below is an untrusted LLM proposal submitted via weyl-mcp (weyl.rewrite.propose) before kernel certification:

json
{
  "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:

T=(X(0,0),d Z(1,0),h)⋅(Y(0,0),d)T = \big(X_{(0,0),d} \, Z_{(1,0),h}\big) \cdot \big(Y_{(0,0),d}\big)

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 ii 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.

Weyl v0.1 · MIT License