Repository navigation
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
Closed
nicolas-abril wants to merge 19 commits into
nicolas-abril wants to merge 19 commits into
Conversation
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]>
… as zeros (WIP) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ing of recursions (WIP) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…only reordering (WIP) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…literal arm and a moved capture Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… closure; a depth cap Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a def that does not match Co-Authored-By: Claude Opus 5.5 <[email protected]>
… main Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng merge shows Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 22, 2026
Collaborator
Author
|
Moved to nicolas-abril#27, which keeps it saved off the main queue until it can be accepted. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
comp.tsis 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: thetestandperfgates have not been run. Numbers are against the integration branch (opt/integrationat 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'sacc_defand #2180'sdef_fix). Two parts:let) stays as it is. Each arm's expression below it (calls, constructors, literals; alet'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 alet(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.def_checkelaborate it: types, quantities and termination are checked again, and a refusal leaves the program as it was.The rules
Term rules, in the e-graph; each is an equation of pure terms:
Nat.add/Nat.multoo when the value is at most 2^32 - 1x + 0,x - 0,x * 1,x | 0,x ^ 0,x & ~0(U32),x + 0n,x * 1n(Nat)U32.inc(x)isx + 1Nat.addcommutes and reassociates;Nat.mulcommutesNat.muldoes not reassociate: a later 0 hides an earlier overflowf(g(ys))isf~g(ys)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 aboutWord,Equal,Nat.maxand foreign signatures).Rules that change defs or types:
D{} | P{f..}with no parameters andU32/Natfields, whoseD{}acts asP{0, ..}at every match the program runs: each match on it has an arm for both, andD's arm equalsP's arm at zero fields in the e-graph under the hypothesisD{} = P{0, ..}. That makes "replace everyD{}byP{0, ..}" a simulation (values related by it go to related results at every match), soD{}is built asP{0, ..}, everyDarm 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,mainor a def's type names the type orD. This isqueens'Stat0{}asStats{0, 0}(section 30's step 1 of the optimisation log).dwhose case tree ends, in every arm, in an expression with exactly one call to the same defg(one argument, a frame or more in the model, notd, not@unsafe) becomesd(ps) = d~k(g(d~s(qs)), ps):d~sisd's case tree answering each arm's argument (over the parameters it matches or reads),d~kthe same tree with the call replaced by its value. For every inputd~stakes the armdtakes, sod~kanswers whatddid;gnow runs before the rest of its arm. A version that would read an affine parameter twice is refused by the checker. This islistops'runOne.f(g(ys)), withga recursion that builds whatf, a one-parameter recursion, takes apart, isf~g(ys):g's case tree withfapplied at each leaf (fis strict, sofof a match is the match off's), elaborated and checked to terminate bydef_check. Its arms go through the e-graph like any def's:funfolds on the constructor the leaf builds, andf(g(y))folds back intof~g(y)(the induction step).f~gis kept only if no call togis left in it, and only call sites the model prefers take it. With the shared-word rule,check(make(d))(binarytrees) becomesdsteps:make(p)twice in an arm builds equal trees, socheck~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~sselects before the arm's other work; a fused recursion never builds its tree. So a program that stops (the Nat limit, an@unsaferecursion) 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.mul2 (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:MD()into1000000007nsaves 4 an iterationsimsaves about 3sim's C fell underSPIN_FAR, becameINLINEand was inlined into its callersrunOneat its one site oncegois not unrolled; mechanism inferred from the iteration count alone deciding it)Nat.div(n, 10n)saves 4 a callThe 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:
queenssolveStat0{}r1, the hand pair accumulator: -4.8%)isqrtisqrt, forked portbinarytreescheck(make(d))and shares its two equal callslistopsrunOnefibpascalbinom(n, k) = 0fork > nand a change of variables: a lemma about the def's own values, not an equation the rules can reachpowmod,factorialNat.div(b, 2n)m; replacing it needs a closed form for a recursion and modular laws Base does not stateString.contains(before #2196)String.starts_with.gospecialised on a constructor in the argument it matches second (constructor specialisation, not a rule here); on main since #2196On main:
queens89.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%,binarytrees1,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):kmeanscomputesb2u(U32.is_zero(n))once,primesd + 1once,digitsumn / 10once,coinscoin(k)once,wordfreqdrops a1n * c. Over every test and program the default drop fires twice (queensand its test), one call site twice (listopsand its test), fusion 31 times in 21 programs (bothbinarytreesports, 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 testmains.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_3d1,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). Perceusderiv(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:
#|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.!calls build their GPU program and print their#|lines.tsc: the same errors as main.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.Nat.sub/Nat.mulreordered, 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
Unit × A ≅ A(section 31 found the wrappers already erased and no closures in the benches). Let floating is subsumed: lets are read through and re-bound by extraction.queens'Statsin the suites (as section 30 counted).🤖 Generated with Claude Code