Repository navigation
Conversation
`visitedNames`, `visitedLevels` and `visitedExprs` were `Std.HashMap α Nat`s. At 43–53 bytes per distinct object they make up most of the exporter's own memory on large exports. They become `Export.IndexSet α`: the elements stored once in insertion order, in chunks, plus an open-addressing table of 4-byte indices kept at most half full, for 16–24 bytes per object. The numbering and the `BEq`/`Hashable` instances are unchanged, so the output is unchanged byte for byte, except in one case where it was unreadable before (below). Exporting more than `2 ^ 32 - 1` distinct objects of one kind now fails with an error. Exporting a string literal first exports `Char.ofNat` and `String.ofList`. If one of them contains the same literal, which is not the case with `Init` but can be with a custom prelude, the old code gave the literal's index to the next object as well, so the file bound one index twice. `Export.parseStream` overwrites the first binding, but a reader that checks for this, such as the one in Lean core, rejects the file. The literal is now written twice under two indices. A test in `Test.lean` covers this, next to a test of `IndexSet` against `Std.HashMap`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Field report: a full-size export that stalled without this PR and finished with it. I was re-checking the claimed Riemann hypothesis formalization (Alpöge / Sutherland / Rubinstein) from source: build the project, export it with lean4export, hash the export, run a checker on it. Setup (identical for both runs)
Without the PR (tag v4.33.0):
With this PR applied to the same tag (
Other checks on the PR (separate Ubuntu 24.04 VM, Lean 4.33.1)
Caveats: one run of each at full size, not a controlled benchmark, and the cause of the stall is unconfirmed. The evidence is that the unpatched run never finished in 38 hours and the patched run finished in under 2, with output matching a published reference. Thanks for the PR. |
|
Thank you for running this end to end. A full-size export whose hash matches the published one is much stronger evidence than anything I could run locally. I can't confirm the cause of the stall either. It does fit what I saw at smaller sizes: the per-object hash maps account for most of the exporter's anonymous memory, so a large export can push the process into memory pressure before it finishes writing. The 8% slowdown on |
Export.leankeeps aStd.HashMap α Natfor every name, level and expression it has numbered, and on large exports these maps are most of the exporter's heap. This PR replaces them withExport.IndexSet, which stores each element once plus a table of 4-byte indices. On Mathlib v4.36.0 that reduces peak anonymous memory by about two thirds. Single runs ofmasterwith and without the patch, warm page cache:InitMathlib.Topology.Basic(2 runs)Mathlib.Topology.Basic --export-mdataPeak anonymous memory is the exporter's own heap. Max RSS also counts the mapped
.oleanfiles, which this does not change. CPU time is 8 % higher onInitand unchanged within noise onTopology.Basic.This copy of the exporter is the one used with toolchains that predate Lean core's
leanexport(first in v4.35.0-rc1). lean-action'snanodacheck also uses it: it buildsmasterand exports whole projects on CI runners.Change.
Export/IndexSet.lean(new, 149 lines) keeps the elements in insertion order, in chunks of2^20, with an open-addressing table of 4-byte indices kept at most half full. That is about 16–24 bytes per element, against an estimated 43–53 for aHashMapentry.getIdxchanges in five lines. Indices are assigned as before, with the sameBEq/Hashableinstances.Output. Patched and unpatched builds of
masterproduced byte-identical files forInit, and forMathlib.Topology.Basicwith no flags, with--export-mdataand with--export-unsafe. Both were built withlean-toolchainset to v4.36.0, so that they could read Mathlib v4.36.0. The one known difference needs a custom prelude: when a string literal's own dependencies (Char.ofNat,String.ofList) contain the same literal, the old code bound one index twice, and the patch writes the literal twice instead. A new test covers this case; it fails on currentmaster.Other measurements, not repeated on this branch. A backport of the same change to the
v4.33.0tag, run with Lean 4.33.1, gave byte-identical output onMathlib.NumberTheory.LSeries.RiemannZeta(41 M expressions). In Lean core's copy of the exporter, the change reduced peak anonymous memory on that module from 2,276 to 1,328 MB.Tests.
lake testpasses on the pinned v4.36.0-rc1 and on v4.36.0.Test.leangains two tests:IndexSetagainstStd.HashMap, covering collisions, wrap-around, high hash bits, chunk boundaries, resizes,Namekeys and duplicate pushes;Limits.
2^32 − 1distinct objects of one kind; past that,getIdxthrows an error.2^31expressions, becauseExpr.hashhas 32 bits.Std.HashMap, whose per-entry heap object is the cost being removed.#59. This composes with #59 (
ExprKey). Applied on top of it, the only conflict is the threeStatefield lines, which resolve toExport.IndexSet ExprKey, andlake testpasses. I can rebase in either order.The same change has been proposed for Lean core's copy in leanprover/lean4#16705.
AI assistance. The change, its tests, the measurements and this description were produced with Claude (Anthropic's AI assistant), which also ran the builds and benchmarks. The commit carries a
Co-Authored-By: Claudetrailer.Method, full results and reproduction
All runs were on one machine: Linux x86-64, a WSL2 Ubuntu 24.04 VM with 6 GB RAM and 12 cores, 23–24 Nov 2026.
What was compared
masteratdf81913("chore: bump toolchain to v4.36.0-rc1 (chore: bump toolchain to v4.36.0-rc1 #57)").Export.lean: 9 lines added, 6 removed;Export/IndexSet.lean: new, 149 lines;Test.lean: 107 lines added.v4.36.0-rc1, and again on v4.36.0.lean-toolchainset to v4.36.0, so that they read Mathlib v4.36.0(official cache). lean-action's nanoda script does the same with a project's toolchain.
output.
1. Byte identity
Init93b61a432ed4241bMathlib.Topology.Basic(two runs each)57e529fd102a82e8Mathlib.Topology.Basic --export-mdata86d4126665fca845Mathlib.Topology.Basic --export-unsafeca6f208ccbe7471dEarlier, on the same code.
v4.33.0tag. It differs only in namespace and file header. With Lean4.33.1, it gave byte-identical output on
Init,Mathlib.Topology.Basic(plain and--export-mdata), andMathlib.NumberTheory.LSeries.RiemannZeta, which is 2.43 GB with 41 Mexpressions.
2. The one output change
The test environment declares
String,f : String → String,Char.ofNat := "x"androot := f "x". Exportingrootexports the literal"x". That first exportsChar.ofNat,which contains the same literal. The tail of the export on current
master:Index 5 is bound twice.
HashMap.inserton the existing key left the map'ssize at 5, so the application got 5 as well.
Export.parseStreamkeeps the later binding, so this file happens to parse to the rightdeclarations. Lean core's reader rejects such files ("Expr index 5 bound twice").
With the patch, the literal is written again as 5, and the application is 6:
Reach.
Initcannot trigger it (checked on v4.36.0): the dependency closure ofChar.ofNatandString.ofListcontains no string literal (377 constants on v4.36.0). A custom prelude can.
The new test guards the whole raw output of this export. It fails on current
masterandpasses with the patch.
3. Tests
lake testThe only warning is the existing one on
functionWithLet.The
IndexSettest comparesExport.IndexSetwith aStd.HashMap α Natupdated bym.insert x m.size. Indices and lookups must agree. It covers:high 32 bits;
Namekeys;push, after whichfind?keeps the first index.4. Memory and CPU
Single runs, warm page cache, output piped to
sha256sum. Peak anonymous memory was sampled from/proc/<pid>/statusevery 0.25 s. It is the exporter's own heap; max RSS also counts the mapped.oleanfiles.InitTopology.Basic, run 1Topology.Basic, run 2Topology.Basic --export-mdataTopology.Basic --export-unsafeReading.
Topology.Basic.Init: +8 %. Lean core's copy measured +3–9 % onInitandStd.Topology.Basic: within run-to-run noise.Not run with this build:
RiemannZeta, and runs under tight memory caps. Measured with Leancore's copy, same algorithm and same Mathlib:
RiemannZetaheap: 2,276 → 1,328 MB.Topology.Basicwithin 1.4 GB, where the base needed about2.2 GB for a similar time.
5. Compatibility
ExprKey, structural equality). ItsExprKeyderivesInhabited, whichIndexSetneeds.Statefield lines,resolved as
visitedExprs : Export.IndexSet ExprKey := {}.lake testpass, fix: key visited expressions by structural equality #59's own test included.IndexSetuses onlyArray,ByteArray(get!,set!,push,emptyWithCapacity),UInt8/32/64arithmetic andNat.fold. It built and passed its testson v4.33.1, v4.36.0-rc1 and v4.36.0. Older toolchains were not tried.
6. Limits
2^32 − 1distinct objects of one kind:getIdxthrows an error beyond that.2^31expressions, probe sequences grow long, becauseExpr.hashhas 32 bits.At 41 M expressions, the mean probe displacement measured in Lean core's copy was 0.23, and the
maximum 22.
7. Reproducing
Save the PR's commit as a patch (append
.patchto the PR URL) aslean4export-indexset.patch. This needs elan, and several GB of disk for Mathlib's cache.The two sha256 values must be equal. They cover the whole file, because both builds use the same
toolchain. Peak anonymous memory (§ 4) is not reported by
time. ReadRssAnonfrom/proc/<pid>/statuswhile the export runs.