Skip to content

tokenizer memo: keep segments of 64 bytes or more, not 1,024 - #2509

Merged
ashhart merged 7 commits into
ashhart:mainfrom
mrv777:tokenizer-memo-short-segments
Nov 9, 2026
Merged

ashhart merged 7 commits into
ashhart:mainfrom
mrv777:tokenizer-memo-short-segments

Conversation

@mrv777

@mrv777 mrv777 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

A chat request renders and encodes its whole conversation four or five times. The tokenizer's memo kept only segments (text between added tokens) of 1,024 bytes or more, so every shorter segment was tokenized again on each render: an agent conversation's short messages, tool calls and small tool results. The memo now keeps segments of 64 bytes or more. Kept ids are looked up by the segment's exact text and first flag, so the ids an encode returns are the same at any minimum; only how often short segments are re-tokenized changes.

  • Issue: n/a. This is a host-side tokenizer cache setting with the same ids, so it changes no family, backend or arithmetic.
  • Stacked on: main (857b11bb8, merged in); commits 1a64b1016 (the change) and the changelog line's PR number.
  • atc overlap --base upstream/main --json (2026-11-08): the only file shared with open pull requests is CHANGELOG.md. atc who lists no open PR or worktree on memo.zig, tokenizer.zig or tokenizer_test.zig.

Why 64

I took 83 real agent conversations from a local prompt cache and decoded them with the Qwen3.8-27B tokenizer: 3 to 60,693 tokens, median 17K, 6,723 segments. Segments under 1,024 bytes are 89% of the segments and 11.5% of the bytes. Encode cost follows bytes, so 11.5% is roughly what a warm render still tokenizes today.

minimum segments below bytes below
1024 (main) 88.7% 11.47%
256 77.2% 4.35%
128 61.0% 0.94%
64 55.0% 0.28%
32 53.4% 0.20%

Most of the remaining short segments are a few bytes, such as role names and newlines, where a lookup would cost what the encode does. Going below 64 measured no further gain (the table under Receipt).

Checks on this head

  • Head commit: 9e8e58f51, its cap test tightened, over ef3946665, the per-entry overhead asked for in review, over 90d2c0d98 (a merge of main, latest 857b11bb8, changelog conflicts only). On this head: tokenizer_test.zig 52/52, memo.zig 7/7, zig build native, zig fmt --check, git diff --check and tools/pr_check.py --pr 2509 (0 errors, 0 warnings, lean 398 vs 398, 0 new) pass.
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: 398 and 398, 0 new (tools/pr_check.py --base upstream/main; 116 and 116 on the earlier base). The 398 are inherited.
  • Tests run, with the command and pass, fail and skip counts:
    • zig test -lc zig/src/core/tokenizer/tokenizer_test.zig: 52/52 (includes memo.zig, memo_reuse_test.zig, masked_test.zig and the EOS tests).
    • zig test -lc zig/src/core/tokenizer/memo.zig: 7/7.
    • zig build test test-golden -Dcpu=apple_m1 on the same code before the changelog-only rebase (18e9def96 on 9450a3624): exit 0, 4m51s, Metal device checks included. Golden shows 0 unexpected differences; the known differences are as recorded.
    • Plain zig build -Dcpu=apple_m1: exit 0.
    • zig fmt --check build.zig zig and git diff --check: clean.
  • New and widened tests:
    • "the memo keeps a 64-byte segment and tokenizes one under min_bytes each time" checks both sides of the boundary, and that ids equal an encode without the memo.
    • "a kept segment's ids equal a fresh encode's wherever the segment sits" now also runs with a 70-byte body. That covers first-segment Metaspace handling, lstrip/rstrip neighbours, a leading space, a lossy byte and repeats within one prompt, for short segments as well as long ones.
    • "each kept segment counts its entry against the cap, so short segments cannot outgrow it" puts 20 distinct 64-byte segments, each with 16 ids, under a cap of ten segments' text and id bytes. It requires fewer than ten kept (exactly what the cap holds once entries and keys count), and held within the cap.
  • Planted controls, each failing as planted:
    • overhead back at 0 (the old accounting): the new cap test and the map-growth recency test fail.
    • min_bytes back at 1024, at 128 and at 65: the new tests fail.
    • A memo blind to first for segments under 1,024 bytes: the widened test and two existing memo tests fail.
  • CI: pending on this head.
  • Not run, and why: CUDA, HIP and Windows hosts. The tokenizer is host code shared by every backend, and nothing here depends on the GPU.

Receipt

  • Main against branch, same machine and data (9450a3624 vs 18e9def96; the code is unchanged by the rebase).
  • Boxes it reaches: every server that loads a Hugging Face tokenizer (server/hf_text.zig creates the 64 MiB memo).
  • New switch? None.
  • Environment:
    • Software: Zig 0.17.0, Xcode 27.2 (27B52).
    • Machine: macOS 27.2 on an Apple M5 Ultra with 96 GB.
    • Checkpoint: a local Qwen3.8-27B MLX 4-bit (affine, group 64), the same files for both builds.
    • Drafter: z-lab/Qwen3.8-27B-DFlash2 at 50307d4c4cde6860d4eee73e2547cd786fe8e8a4.
  • Paths and platforms the change reaches: Tokenizer.encode and encodeMasked (the chat route takes the masked path; the Qwen tokenizer has no normalized added tokens, so request gaps use the memo too). Ran: macOS. Not run: Linux and Windows, which share the same host code.
  • Exactness:
    • The ids are equal to an encode without the memo for all 83 conversations at every minimum from 16 to 1,024, with 4 encodes each and 0 mismatches.
    • Served, the same reply at both builds and in every run.
    • Output tokens can't change while the ids are equal.
  • Encode cost, an in-process bench over the 83 conversations, longest last, with the real tokenizer (ReleaseFast). The bench replays each request as one encode plus three repeats sharing a 64 MiB memo.
minimum repeat encode, mean warm encode, 8 largest cold one-off, empty memo (all 83) memo entries / heap
1024 (main) 452-457 µs 680-691 µs 400 ms (no memo 401-404) 88 / 1.3 MB
128 86-88 µs 163-172 µs 401-427 ms (no memo 405-425) 271 / 1.5 MB
64 65-66 µs 146-151 µs 400-406 ms (no memo 402-404) 320 / 1.5 MB
32 62-63 µs 138-139 µs 401-402 ms 330 / 1.5 MB
16 62 µs 142-144 µs 397-401 ms 333 / 1.5 MB

A one-off prompt pays nothing measurable for the extra saves.

  • Served, the time to a one-token reply for a real 20,655-token agent conversation sent repeatedly, with --prompt-cache-gib 8. 20,650 tokens are cached, so the time is mostly host work.
    • Serve flags: serve MODEL --drafter z-lab/Qwen3.8-27B-DFlash2 --parallel 2 --context 65536 --prompt-cache-gib 8.
    • Median of 12 or 24 repeats, three alternated runs: main 42.21 / 42.54 / 42.72 ms, branch 41.71 / 42.04 / 42.12 ms, about 0.5 ms (1.2%) faster.
    • That request inlines tool calls in 14 messages. A client that sends tool calls and results as separate messages renders more short segments, so it saves more; the in-process table bounds it at about 0.4-0.5 ms per encode on the largest conversations, four or five encodes a request.
  • Memory: entries under 1,024 bytes carry relatively more bookkeeping. In review this became part of the change (ef3946665): a kept segment now counts a fixed overhead of @sizeOf(Entry) + @sizeOf(u64) against the cap, added in put and subtracted in remove through one bytes helper, so the 64 MiB cap bounds the entries and their keys too. Before it, filled to its cap with distinct entries, the live heap was 1.08x held at 1,024-byte entries, 1.63x at 128 and 2.27x at 64 (about 145 MiB at the server's 64 MiB cap). The memo tests' caps are now written in that unit (bytes(1, 1) a one-byte entry, 60 + overhead). On the 83 real conversations the memo held 1.5 MB, far under the cap either way.
  • Decode speed before and after: n/a, the change doesn't reach decode.
  • Prompt speed before and after: n/a for cold prefill, which is GPU work this change doesn't touch. The host part of the first token is above.
  • Licence of any new weights or drafter: n/a.

Checklist

  • The title and description match the head commit, including the receipt and the stack.

  • New tests fail before the change, pass after it, and skip cleanly without their dependency. (They fail at the old 1,024 minimum and need no device.)

  • Comments and docstrings are one line. No measurements or history in the source.

  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.

  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.

  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo. (The prompt ids are unchanged, so nothing after tokenization can differ; the full suite and golden corpus pass.)

  • No precision traded for speed. If the bits change, the description says which sums change and why. (No arithmetic changes.)

  • Decode and prompt processing are no slower than main at one stream and the widest admitted; with --drafter, no slower than without it, greedy and sampled. (Decode is untouched; the host part of a cached prompt is faster and a one-off prompt is not slower.)

mrv777 added a commit to mrv777/TensorFold that referenced this pull request Nov 8, 2026
@ashhart

ashhart commented Nov 8, 2026

Copy link
Copy Markdown
Owner

Thanks @mrv777. The segment table makes the case for 64 well, and the exactness argument holds when we read it: Memo.append returns ids only after matching the full text and first, so the threshold only changes how often a segment is re-tokenized, never what it becomes. The boundary test and the 70-byte run of the any-position test cover it.

One thing: at 64-byte segments the cap stops being a bound. held counts only text and id bytes (zig/src/core/tokenizer/memo.zig:50, :71, :102), and the Entry, its key and the map slot can be larger than a short segment. Could you count a fixed per-entry overhead (for example @sizeOf(Entry) + @sizeOf(u64)) in size, and subtract the same in remove, so 64 MiB stays the limit? The memo test's 60-byte cap will need its numbers adjusted.

We'll settle the CHANGELOG conflict at landing.

@mrv777

mrv777 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Done in ef3946665. A kept segment now counts @sizeOf(Entry) + @sizeOf(u64) against the cap through one bytes helper, added in put and subtracted in remove, so 64 MiB stays the limit with its bookkeeping. The memo tests' caps are now written in that unit. A new test keeps 20 distinct 64-byte segments under a ten-entry cap and requires exactly ten kept. With overhead set back to 0 it fails, and so does the map-growth recency test. tokenizer_test.zig 52/52, memo.zig 7/7, the native build and pr_check pass; the description is updated.

@mrv777

mrv777 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my last comment: the cap test in ef3946665 wrote its cap through bytes(), so it still passed with overhead at 0. Only the map-growth test caught that. In 9e8e58f51 its cap is fixed in text and id bytes, and it requires fewer than ten segments kept. With overhead at 0, both it and the map-growth test fail. memo.zig 7/7, tokenizer_test.zig 52/52.

@ashhart

ashhart commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@mrv777 thanks, and for the correction. With the cap fixed in text and id bytes, twenty 64-byte segments under a ten-segment budget keep exactly ten if the overhead isn't counted, so the test now fails without it, as you say. The overhead in put and remove through one helper keeps 64 MiB the real limit. It's ready and on the landing queue now; the CHANGELOG line keeps yours, with the thanks.

@ashhart

ashhart commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@mrv777, the branch's merges of main stopped our landing rebase, so I've rebuilt it linearly on today's main (3c6a4757bb). It holds your four commits with every code line unchanged, plus one commit leaving a single CHANGELOG line. It's back on the landing queue.

ashhart pushed a commit to mrv777/TensorFold that referenced this pull request Nov 9, 2026
ashhart and others added 7 commits November 9, 2026 19:49
A chat request renders and encodes its conversation four or five times, and
the memo skipped every segment under 1,024 bytes, so an agent conversation's
short messages, tool calls and tool results were tokenized on every render.
On 83 real agent conversations (Qwen3.8-27B tokenizer, 3 to 60K tokens) those
segments are 89% of all segments and 11.5% of the bytes; at 64 bytes they are
0.3%, and going lower gains nothing.

Kept ids are looked up by the segment's exact text and first flag, so ids are
unchanged at any minimum. The tests keep a 64-byte segment, refuse one under
the minimum, and read a 70-byte body back in every position the long-body test
covers; with the old minimum (or 128, or 65) they fail.
…e cap

At 64-byte segments the map's entry and key cost about as much as a short
segment, and held counted only text and ids. A segment now counts a fixed
overhead of @sizeof(Entry) + @sizeof(u64) when it is kept and when it goes,
so the cap bounds the memo's bookkeeping too.
@ashhart
ashhart force-pushed the tokenizer-memo-short-segments branch from 3c6a475 to 5cdecc2 Compare November 9, 2026 19:49
@ashhart
ashhart merged commit 26e1b07 into ashhart:main Nov 9, 2026
2 of 10 checks passed
ashhart pushed a commit that referenced this pull request Nov 9, 2026
@ashhart

ashhart commented Nov 9, 2026

Copy link
Copy Markdown
Owner

Thank you @mrv777. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

ashhart added a commit that referenced this pull request Nov 10, 2026
Figures corrected to the PRs' measured ones (#2699 head runs, #2509,
#2633, #2436, #2644, #2593, #2430, #2568), scope fixed (#2253, #2287,
#2511, #2569, #2337, #2627, #2351, #2626), unsourced figures dropped
(#2181, #2606, #2257's pricing clauses), the shipped #2176, #2565,
#2548 and gfx12 silu entries and the first #2625 copy removed, and
the #2568 and #2352 entries unwrapped to one line each.
@ashhart

ashhart commented Nov 10, 2026

Copy link
Copy Markdown
Owner

Thanks @mrv777! This is in TensorFold 1.2.6, out now: https://github.com/ashhart/TensorFold/releases/tag/v1.2.6

  • Synthena (Ash's Agent)

@mrv777
mrv777 deleted the tokenizer-memo-short-segments branch November 26, 2026 22:24
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