Skip to content

An e-graph over each arm, and three rules that reshape defs: a default constructor dropped, one call site, fusion - #2221

Closed
nicolas-abril wants to merge 19 commits into
bendlang:mainfrom
nicolas-abril:opt/eqsat
Closed

nicolas-abril wants to merge 19 commits into
bendlang:mainfrom
nicolas-abril:opt/eqsat

Conversation

@nicolas-abril

Copy link
Copy Markdown
Collaborator

comp.ts is 80,977 ttok (main 65,995: +14,982); the cap was set aside for this draft by the owner. Measured on one Mac (M4), not on the cluster: the test and perf gates have not been run. Numbers are against the integration branch (opt/integration at bae6475 on nicolas-abril/bend, which merges #2153, #2161, #2162, #2175, #2177, #2180, #2188, #2207, #2211, #2217, #2218 and others onto main 0e2f38f) with this branch merged onto a copy of it, unless a line says main. Scripts, raw results and the debug build: https://github.com/nicolas-abril/bend-eqsat (private).

What it does

A pass on the checked terms, in file_book, before emission, C lane only (like #2175's acc_def and #2180's def_fix). Two parts:

  • An e-graph over each arm. A def's case tree (its lambdas, its matches, a fork's let) stays as it is. Each arm's expression below it (calls, constructors, literals; a let's name is its value's class; a closure is a leaf whose own arms go through the pass in turn) goes into an e-graph: hash-consed nodes, union-find, congruence rebuilding. The rules below add equal terms for up to 8 rounds or 2,000 nodes, then the cheapest term comes back out by a static cost model, and a class read twice whose type is all words is bound once by a let (common subexpressions). An arm changes only if that saves at least 1 in the model, so an arm no rule improves is left exactly as it was.
  • Three rules that make new defs or change a type. Where a rule builds a def it writes it as an unannotated core term and has bend.ts' own def_check elaborate it: types, quantities and termination are checked again, and a refusal leaves the program as it was.
# isqrt (koru): the Newton iterate is computed twice, as an argument and in the flag
iter(n, y, Nat.div(Nat.add(y, Nat.div(n, y)), 2n),
     Nat.is_lt(Nat.div(Nat.add(y, Nat.div(n, y)), 2n), y))
# compiled as if written
+x = Nat.div(Nat.add(y, Nat.div(n, y)), 2n)
iter(n, y, x, Nat.is_lt(x, y))

The rules

Term rules, in the e-graph; each is an equation of pure terms:

rule holds because
fold: a U32 operation on literals is its value; Nat.add / Nat.mul too when the value is at most 2^32 - 1 evaluation (a larger Nat literal is not a word)
units: x + 0, x - 0, x * 1, x | 0, x ^ 0, x & ~0 (U32), x + 0n, x * 1n (Nat) U32 wraps; a Nat operand is already under 2^48 - 1
U32.inc(x) is x + 1 its definition
Nat.add commutes and reassociates; Nat.mul commutes no partial sum of Nats exceeds the whole, so both orders pass 2^48 - 1 together (#2175's argument); the same product. Nat.mul does not reassociate: a later 0 hides an earlier overflow
unfold: a call to a def that does not recurse is its body at its arguments; a match in it on an argument whose class holds a constructor or a Nat literal takes that arm (case of a known constructor); a def that recurses unfolds only through a match on a constructor evaluation; each unfolding of a recursion consumes a constructor, so it stops
fusion: f(g(ys)) is f~g(ys) by construction of f~g (below)

U32 and F32 reordering hold too (U32 wraps; Base proves U32.add_comm) but are left out: they never lowered a cost and made every arm's e-graph grow each round. None of Base's other laws is an equation between runtime terms this pass meets (they are about Word, Equal, Nat.max and foreign signatures).

Rules that change defs or types:

  • A default constructor dropped (type level, whole program). A datatype D{} | P{f..} with no parameters and U32 / Nat fields, whose D{} acts as P{0, ..} at every match the program runs: each match on it has an arm for both, and D's arm equals P's arm at zero fields in the e-graph under the hypothesis D{} = P{0, ..}. That makes "replace every D{} by P{0, ..}" a simulation (values related by it go to related results at every match), so D{} is built as P{0, ..}, every D arm is dropped, and the type keeps one constructor: no tag word, one arm where there were two. Checked over every def the program reaches; refused if a foreign def, main or a def's type names the type or D. This is queens' Stat0{} as Stats{0, 0} (section 30's step 1 of the optimisation log).
  • One call site. A def d whose case tree ends, in every arm, in an expression with exactly one call to the same def g (one argument, a frame or more in the model, not d, not @unsafe) becomes d(ps) = d~k(g(d~s(qs)), ps): d~s is d's case tree answering each arm's argument (over the parameters it matches or reads), d~k the same tree with the call replaced by its value. For every input d~s takes the arm d takes, so d~k answers what d did; g now runs before the rest of its arm. A version that would read an affine parameter twice is refused by the checker. This is listops' runOne.
  • Fusion (deforestation). f(g(ys)), with g a recursion that builds what f, a one-parameter recursion, takes apart, is f~g(ys): g's case tree with f applied at each leaf (f is strict, so f of a match is the match of f's), elaborated and checked to terminate by def_check. Its arms go through the e-graph like any def's: f unfolds on the constructor the leaf builds, and f(g(y)) folds back into f~g(y) (the induction step). f~g is kept only if no call to g is left in it, and only call sites the model prefers take it. With the shared-word rule, check(make(d)) (binarytrees) becomes d steps: make(p) twice in an arm builds equal trees, so check~make(p) twice is one call.

What can differ from main, as with #2175 and #2180: every rule is an equation of pure terms, so a program that runs to its end prints the same. What moves is when a value is computed: a shared value once, at the head of its arm; d~s selects before the arm's other work; a fused recursion never builds its tree. So a program that stops (the Nat limit, an @unsafe recursion) can stop at another point of the same run, or not at all where a fused recursion no longer computes a part of a tree that overflowed and was never read. No rule copies a value of a boxed type: sharing a box would turn its type into counted nodes program-wide (what #2180 measured), so only words are shared.

The cost model, and where measurement disagreed

Static, in rough instructions: a Nat.add / Nat.mul 2 (its limit test, which clang cannot share), a division 4, a heap node 6, a call to a def that recurses 20 (a frame), a call to a def that does not what its body costs (the emitter unfolds it; a match 3 and 1 an arm). U32 and F32 operations, word-sized constructors, unchecked Nat operations, operations or calls on literals, and defs with no parameters cost 0. That last line is the calibration; the first version priced word arithmetic and constants and was wrong in both directions:

program the model said measured now
koru nestedloop folding MD() into 1000000007n saves 4 an iteration +5.0% instructions, -8% cycles: clang turns a literal divisor into a multiply sequence constants cost 0: no change
nbody sharing U32/F32 subterms of sim saves about 3 +5.4% instructions: sim's C fell under SPIN_FAR, became INLINE and was inlined into its callers word arithmetic costs 0: no change
gameoflife sharing four U32 indices saves 2 0.0%: clang already shares them no change
koru listops one call site: nothing visible 0 at the kernel's 7 iterations, -21% instructions at 700 (clang inlines runOne at its one site once go is not unrolled; mechanism inferred from the iteration count alone deciding it) taken, measured
koru binarytrees fusion: one call of 20 for two of 40 2^13 nodes built and walked become 13 steps (main: 1,639M to 12M instructions) taken
koru digitsum, on main only sharing Nat.div(n, 10n) saves 4 a call +2.7% instructions on main (cycles inside the range); unchanged on the integration branch; the spins' order in the C changes too, cause not traced open
coins, forked factorial (first version) sharing word work -3.2% and -6.3% instructions lost with the calibration: traded for no regression

The default drop is not cost-driven (one word and one test fewer per value is assumed to pay): measured, below.

Results

One M4, one thread, GPU off, cc -O3. Cycles are P-core cycles over 16 placements (nops before the first segment, 2 rounds, least / median / most).

Targets, against the integration branch:

target what the pass does instructions cycles, median (range) new over the baseline?
queens solve drops Stat0{} 58.47G to 55.05G (-5.9%) 17.61G (17.55 / 17.68) to 16.54G (16.42 / 16.70): -6.1% yes (r1, the hand pair accumulator: -4.8%)
koru isqrt binds the iterate once 163.4M to 128.3M (-21.5%) 59M to 48M (-19%) yes
koru isqrt, forked port same 168.4M to 133.4M (-20.8%) 64M to 50M (-22%) yes
koru binarytrees fuses check(make(d)) and shares its two equal calls 11.96M to 11.03M (-7.5%): start-up only, #2180 already computes it once inside the range yes (#2031 is not in the baseline)
koru listops one call site for runOne 13.43M to 13.45M median (noise) inside the range no gain on the kernel as shipped; -21% / -26% at 700 iterations
koru fib nothing #2175 has it; no accumulator rule here
koru pascal nothing needs binom(n, k) = 0 for k > n and a change of variables: a lemma about the def's own values, not an equation the rules can reach
koru powmod, factorial two shares of Nat.div(b, 2n) -0.2% inside the range the doubling loop is a product mod m; replacing it needs a closed form for a recursion and modular laws Base does not state
Base String.contains (before #2196) nothing needs String.starts_with.go specialised on a constructor in the argument it matches second (constructor specialisation, not a rule here); on main since #2196

On main: queens 89.87G to 85.01G instructions and 22.13G to 18.88G cycles (-14.7%, ranges apart, section 30's figure for step 1), isqrt -21.5% / -19%, binarytrees 1,639M to 12M instructions and 279M to 5M cycles.

The suite, against the integration branch: 19 of the 63 programs (17 benches, 22 kernels, 17 forked kernels, 7 Perceus ports) change their C (kmeans, queens; binarytrees, coins, digitsum, exprtree, factorial, isqrt, listops, powmod, primes, wordfreq; seven forked ports); no Perceus port changes. No program is worse than +0.15% in instructions (listops' start-up noise), and every cycle median is inside its base's placement range except the gains above. What it found beyond the targets in the suite (all inside noise): kmeans computes b2u(U32.is_zero(n)) once, primes d + 1 once, digitsum n / 10 once, coins coin(k) once, wordfreq drops a 1n * c. Over every test and program the default drop fires twice (queens and its test), one call site twice (listops and its test), fusion 31 times in 21 programs (both binarytrees ports, the rest tests, e.g. String.length(String.append(..))), and arms are rewritten in 306 programs, mostly compile-time evaluation of calls on literal lists in test mains.

Search cost and compile time

Per target, the pass takes under 30 ms; the largest arm's e-graph has 2,006 nodes (binarytrees, at the budget), most under 50. Budgets: 8 rounds and 2,000 nodes an arm, 400,000 nodes a build, closures 32 deep; gates skip the rounds on an arm of word arithmetic alone or with nothing shared, foldable or unfoldable.

compile_book, the least of 3 runs, one process per program: +7.9% over the 17 benches and 15 demos together; app_slash_boss_3d 1,787 to 1,937 ms (+8.4%); small programs +10% to +25% of a few tens of ms (the perf gate's COMPILER cell also counts the check and clang, about 0.6 s on bfs). Perceus deriv (a 3.7 GB compile on main): times swing from 15 to 34 s on both builds under load, inconclusive; peak memory 5.17 to 5.93 GB.

Checks

Against main:

  • The 162 tests whose C changes (every other test emits byte-identical C): the C lane prints the same as main on all 162 (3 differ from their #| lines on main too: two network tests, and one whose output is longer than the harness keeps); the memory check (poisoned frees, live heap words at exit) is the same at 1 and 8 threads, 0 live words on 158, the same counts on the rest.
  • JS: the pass is C only; the 162 tests' emitted JS is byte-identical.
  • Metal: the 4 changed tests with ! calls build their GPU program and print their #| lines.
  • tsc: the same errors as main.
  • Four new tests, tests/run/eqsat_{cse,drop,sites,fuse}.bend: each rule's shapes and its refusals (a default that one match does not treat as zeros, one matched by a catch-all arm, a call-site candidate reading an affine parameter twice, a capture of a let-bound value), and programs that stop on the Nat limit on every lane, fused or not.
  • Ten wrong versions (a wrong unit, a wrong fold, Nat.sub / Nat.mul reordered, a default dropped unchecked or built at the wrong fields, a wrong call-site selector, a fusion found by its producer alone, a literal taking the other arm, a shared word bound affine, a captured variable moved): 9 caught by the new tests; the affine binding emits the same C (the emitter counts reads itself). The repo's own tests whose C changes catch 5 of them and miss the reordering, both drop versions and the selector.

Not run: the cluster gates, CUDA, Linux, x86.

Not covered

🤖 Generated with Claude Code

nicolas-abril and others added 19 commits November 22, 2026 12:30
The case tree stays; each arm's calls, constructors, literals and lets go
into an e-graph with fold, unit, commutativity, associativity and unfold
rules, and come back out by a static cost, a word read twice bound once.
isqrt binds its Newton iterate once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ing of recursions (WIP)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…literal arm and a moved capture

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ons and calls on literals cost 0

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a def that does not match

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

Moved to nicolas-abril#27, which keeps it saved off the main queue until it can be accepted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant