Skip to content

perf: memoize get_merges (TRADE_MEMORY_FOR_SPEED, default True) - #30

Merged
AmitMY merged 1 commit into
mainfrom
perf/optional-get-merges-memo
Jun 26, 2026
Merged

AmitMY merged 1 commit into
mainfrom
perf/optional-get-merges-memo

Conversation

@AmitMY

@AmitMY AmitMY commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

get_merges is a pure function of an immutable node, and merge returns self for unchanged subtrees (PR #28), so the same node objects recur across merges — a full re-walk every step can instead be a cache hit.

NodesSequence now memoizes its candidate list, gated by a new GraphSettings.TRADE_MEMORY_FOR_SPEED flag:

# speed up by 2x~ at the cost of 2x more memory use
TRADE_MEMORY_FOR_SPEED = True

Default True — favors speed. Set it to False to keep the previous lower-memory behavior. Output is identical either way (a new test trains with the flag off and on and asserts the merge sequences match). All 137 tests pass.

Measured (50 texts / 200 merges):

False (was main) True (default)
BPE 5.62s / 3.16MB 3.45s / 4.41MB
BNE n=4 7.87s / 2.84MB 5.21s / 6.28MB
Boundless 6.58s / 3.04MB 4.03s / 5.29MB
SuperBPE 7.19s / 2.71MB 4.62s / 4.41MB

~35–40% faster (grows toward ~1.65× at larger scale) for roughly 2× peak memory. Notably this also speeds up the connected tokenizers (Boundless/SuperBPE).

🤖 Generated with Claude Code

get_merges is a pure function of an immutable node, and merge returns
self for unchanged subtrees, so the same node objects recur across merges
and a full re-walk becomes a cache hit. NodesSequence now memoizes its
candidate list when GraphSettings.TRADE_MEMORY_FOR_SPEED is set.

Default True: ~35-40% faster across all tokenizers at roughly 2x peak
memory. Set False to keep the lower-memory behavior. Output is identical
either way; a new test asserts the memoized path matches the unmemoized one.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@AmitMY
AmitMY merged commit 9e2d8a3 into main Jun 26, 2026
3 checks passed
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