Skip to content

perf: deduplicate exported objects without a hash map entry per object - #61

Open
alonbase wants to merge 1 commit into
leanprover:masterfrom
alonbase:perf/indexset
Open

alonbase wants to merge 1 commit into
leanprover:masterfrom
alonbase:perf/indexset

Conversation

@alonbase

Copy link
Copy Markdown

Export.lean keeps a Std.HashMap α Nat for 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 with Export.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 of master with and without the patch, warm page cache:

Export Peak anonymous memory Max RSS CPU time (user + sys)
Init 532 → 195 MB 960 → 623 MB 20.7 → 22.4 s
Mathlib.Topology.Basic (2 runs) 1,089 → 386 MB 2,467 → 1,768 MB 53.8, 54.0 → 52.9, 54.1 s
Mathlib.Topology.Basic --export-mdata 1,053 → 350 MB 2,435 → 1,732 MB 45.4 → 44.6 s

Peak anonymous memory is the exporter's own heap. Max RSS also counts the mapped .olean files, which this does not change. CPU time is 8 % higher on Init and unchanged within noise on Topology.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's nanoda check also uses it: it builds master and exports whole projects on CI runners.

Change. Export/IndexSet.lean (new, 149 lines) keeps the elements in insertion order, in chunks of 2^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 a HashMap entry. getIdx changes in five lines. Indices are assigned as before, with the same BEq/Hashable instances.

Output. Patched and unpatched builds of master produced byte-identical files for Init, and for Mathlib.Topology.Basic with no flags, with --export-mdata and with --export-unsafe. Both were built with lean-toolchain set 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 current master.

Other measurements, not repeated on this branch. A backport of the same change to the v4.33.0 tag, run with Lean 4.33.1, gave byte-identical output on Mathlib.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 test passes on the pinned v4.36.0-rc1 and on v4.36.0. Test.lean gains two tests:

  • a comparison of IndexSet against Std.HashMap, covering collisions, wrap-around, high hash bits, chunk boundaries, resizes, Name keys and duplicate pushes;
  • the re-entrant case above.

Limits.

  • At most 2^32 − 1 distinct objects of one kind; past that, getIdx throws an error.
  • Probe sequences get long past about 2^31 expressions, because Expr.hash has 32 bits.
  • It is a hand-written table rather than Std.HashMap, whose per-entry heap object is the cost being removed.
  • All measurements come from one 6 GB VM.

#59. This composes with #59 (ExprKey). Applied on top of it, the only conflict is the three State field lines, which resolve to Export.IndexSet ExprKey, and lake test passes. 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: Claude trailer.

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

  • Base: master at df81913 ("chore: bump toolchain to v4.36.0-rc1 (chore: bump toolchain to v4.36.0-rc1 #57)").
  • Patched: the same commit plus the PR's commit:
    • Export.lean: 9 lines added, 6 removed;
    • Export/IndexSet.lean: new, 149 lines;
    • Test.lean: 107 lines added.
  • Tests ran on the pinned v4.36.0-rc1, and again on v4.36.0.
  • Exports.
    • Both builds were made with lean-toolchain set 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.
    • The same toolchain means the metadata line is equal too, so the comparison is on the whole
      output.
    • Every run was capped at 4,500 MB with no swap.

1. Byte identity

Export sha256 (first 16 hex digits) Bytes
Init 93b61a432ed4241b 347,772,063 identical
Mathlib.Topology.Basic (two runs each) 57e529fd102a82e8 787,047,359 identical
Mathlib.Topology.Basic --export-mdata 86d4126665fca845 789,899,964 identical
Mathlib.Topology.Basic --export-unsafe ca6f208ccbe7471d 788,856,611 identical

Earlier, on the same code.

  • A backport to the v4.33.0 tag. It differs only in namespace and file header. With Lean
    4.33.1, it gave byte-identical output on Init, Mathlib.Topology.Basic (plain and
    --export-mdata), and Mathlib.NumberTheory.LSeries.RiemannZeta, which is 2.43 GB with 41 M
    expressions.
  • The same change in Lean core's copy. Identical on 15 exports of up to 2.5 GB.

2. The one output change

The test environment declares String, f : String → String, Char.ofNat := "x" and
root := f "x". Exporting root exports the literal "x". That first exports Char.ofNat,
which contains the same literal. The tail of the export on current master:

{"ie":4,"strVal":"x"}
{"def":{"all":[6],"hints":"opaque","levelParams":[],"name":6,"safety":"safe","type":1,"value":4}}
{"ie":5,"strVal":"x"}
{"app":{"arg":5,"fn":3},"ie":5}
{"def":{"all":[4],"hints":"opaque","levelParams":[],"name":4,"safety":"safe","type":1,"value":5}}

Index 5 is bound twice.

  • The inner call numbered the literal 4.
  • The outer call printed it again, as 5. But HashMap.insert on the existing key left the map's
    size at 5, so the application got 5 as well.
  • Export.parseStream keeps the later binding, so this file happens to parse to the right
    declarations. 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:

{"ie":5,"strVal":"x"}
{"app":{"arg":5,"fn":3},"ie":6}
{"def":{"all":[4],"hints":"opaque","levelParams":[],"name":4,"safety":"safe","type":1,"value":6}}

Reach. Init cannot trigger it (checked on v4.36.0): the dependency closure of Char.ofNat and String.ofList
contains 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 master and
passes with the patch.

3. Tests

Build Toolchain lake test
patched v4.36.0-rc1 (pinned) pass
patched v4.36.0 pass
unpatched v4.36.0 pass
unpatched, plus only the re-entrancy test v4.36.0-rc1 fails, as intended
patched, on top of PR #59 v4.36.0-rc1 pass

The only warning is the existing one on functionWithLet.

The IndexSet test compares Export.IndexSet with a Std.HashMap α Nat updated by
m.insert x m.size. Indices and lookups must agree. It covers:

  • a key type whose hash forces collisions, wraps probes around the end of the table, and sets the
    high 32 bits;
  • chunks of 4 and 8 elements, so the elements span many chunks;
  • 50,000 lookups and about 20,000 inserts across several resizes;
  • Name keys;
  • a duplicate push, after which find? 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>/status every 0.25 s. It is the exporter's own heap; max RSS also counts the mapped
.olean files.

Export Peak anonymous memory Max RSS CPU (user + sys) Wall
Init 532 → 195 MB (−63 %) 960 → 623 MB 20.7 → 22.4 s (+8 %) 22.3 → 22.0 s
Topology.Basic, run 1 1,089 → 386 MB (−65 %) 2,467 → 1,768 MB 53.8 → 52.9 s 55.4 → 52.5 s
Topology.Basic, run 2 1,089 → 385 MB 2,470 → 1,767 MB 54.0 → 54.1 s 53.8 → 53.7 s
Topology.Basic --export-mdata 1,053 → 350 MB (−67 %) 2,435 → 1,732 MB 45.4 → 44.6 s 46.3 → 43.7 s
Topology.Basic --export-unsafe 1,089 → 385 MB 2,471 → 1,767 MB 51.9 → 52.8 s 51.5 → 54.1 s

Reading.

  • Memory. The patch removes about 700 MB of the base's 1.1 GB heap on Topology.Basic.
  • CPU.
    • Init: +8 %. Lean core's copy measured +3–9 % on Init and Std.
    • Topology.Basic: within run-to-run noise.

Not run with this build: RiemannZeta, and runs under tight memory caps. Measured with Lean
core's copy, same algorithm and same Mathlib:

  • RiemannZeta heap: 2,276 → 1,328 MB.
  • Under a memory cap, the patch ran Topology.Basic within 1.4 GB, where the base needed about
    2.2 GB for a similar time.

5. Compatibility

6. Limits

  • At most 2^32 − 1 distinct objects of one kind: getIdx throws an error beyond that.
  • Beyond about 2^31 expressions, probe sequences grow long, because Expr.hash has 32 bits.
    At 41 M expressions, the mean probe displacement measured in Lean core's copy was 0.23, and the
    maximum 22.
  • All measurements come from one 6 GB VM.

7. Reproducing

Save the PR's commit as a patch (append .patch to the PR URL) as lean4export-indexset.patch. This needs elan, and several GB of disk for Mathlib's cache.

git clone https://github.com/leanprover/lean4export base
git clone https://github.com/leanprover/lean4export patched
(cd patched && git am ../lean4export-indexset.patch)
for d in base patched; do (cd $d && lake build && lake test); done      # pinned v4.36.0-rc1

# identity and memory against Mathlib v4.36.0
for d in base patched; do (cd $d && echo 'leanprover/lean4:v4.36.0' > lean-toolchain && lake build); done
git clone --depth 1 --branch v4.36.0 https://github.com/leanprover-community/mathlib4
cd mathlib4 && lake exe cache get
for d in base patched; do
  lake env /usr/bin/time -f "%e s wall, %U+%S s CPU, %M KB max RSS" ../$d/.lake/build/bin/lean4export Mathlib.Topology.Basic | sha256sum
done

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. Read RssAnon from
/proc/<pid>/status while the export runs.

`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>
@abhiapsunde

Copy link
Copy Markdown

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)

  • AMD Ryzen 9 5950X (16 cores, 32 threads), 125 GiB RAM, Ubuntu 24.04, Linux 7.0
  • Lean 4.33.1 for the project; lean4export built at the v4.33.0 tag (15f6055)
  • Same compiled project, same targets file (the 4-line export-targets.txt from the submission), same command: lake env lean4export Main -- <targets> > solution.ndjson
  • The project compiled cleanly (183,903 jobs, exit 0)

Without the PR (tag v4.33.0):

  • Output reached about 46 GB in roughly 90 minutes, then stopped growing.
  • It sat for about 21 hours at 61,570,588,672 bytes with no new writes (the finished file is 61,570,595,788, so it was 7,116 bytes short). I killed it at 38 hours.
  • During the stall the process's anonymous memory was flat at about 68 GB and disk showed reads but no writes. A gdb sample showed it inside lean_dec_ref_cold under the exporter's main loop. I did not find the root cause; the memory pressure from the per-object hash maps (see #16705) is my guess, not something I confirmed.

With this PR applied to the same tag (Export.lean and Export/IndexSet.lean; Test.lean left out of the build):

  • Exit 0 in 1 h 53 min 37 s, peak RSS 86.9 GB.
  • Output is 61,570,595,788 bytes with sha256 5ea74b912147c5c93cc2b6d70cc727cf908df2f62ac6a20480a3fa02f6be244e, which matches the hash of the export published by Sutherland for this proof.

Other checks on the PR (separate Ubuntu 24.04 VM, Lean 4.33.1)

  • lake test exits 0 on the PR branch.
  • Init export is byte-identical between the tag and the tag plus this PR (347,714,179 bytes, 6,490,422 lines).
  • Single module Mathlib.NumberTheory.LSeries.RiemannZeta: the PR was about 8% slower in wall time (2:01 vs 1:52) and used about 20% less RSS (4.2 vs 5.2 GB).

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.

@alonbase

Copy link
Copy Markdown
Author

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 RiemannZeta is within the range I measured. The CPU cost varied by toolchain and module, from slightly faster to about 20% slower.

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.

2 participants