Skip to content

Prompt reuse for Nemotron on Metal: kept states copied on the GPU, exact against cache-off - #497

Closed
BobClawblaw wants to merge 1 commit into
ashhart:mainfrom
BobClawblaw:nemotron-prompt-reuse
Closed

BobClawblaw wants to merge 1 commit into
ashhart:mainfrom
BobClawblaw:nemotron-prompt-reuse

Conversation

@BobClawblaw

Copy link
Copy Markdown
Contributor

Nemotron keeps each stream's prompt state at the prompt cache's marks and resumes a later request whose prompt extends one, as Flash Next and GLM do. This is item 1 of ZIG-PREVIEW's "where you can help".

What changed

  • zig/src/families/nemotron/snapshot.zig (new): a kept state is every Mamba conv and SSM state, the KV rows and the draft head's KV rows, in one Metal buffer. Save and restore are tf_copy_u32 dispatches submitted on the engine's fenced queue: a save right after the chunk that ends at the mark, a restore right before the first chunk, so neither waits for the host. A drop drains first, since the queue holds unretained references. The module also carries the prompt_cache.Snapshots vtable functions.
  • zig/src/families/nemotron/backend.zig: the prompt pass restores a kept state before its first chunk and calls the mark hook after each chunk that ends at a mark. Both the shared-lane and the lone-stream paths run prefillFn, so one change covers both.
  • zig/src/native/metal.zig: the Nemotron host gets a prompt_cache.Store with the same budget rule as Flash Next (cache_fit: what 70% of RAM leaves past the loaded footprint, or --prompt-cache-gib; 0 turns it off).
  • Docs: the --prompt-cache-gib and --prompt-cache-over-cap rows in README, the known gaps and help list in ZIG-PREVIEW, RUNBOOK, the family guide's ownership table, and a receipt section in the Nemotron recipe.

No arithmetic changes: the prompt kernels, decode kernels and reduction orders are untouched. The kept bytes are copies of live rows.

Not in this PR, listed as the next step in ZIG-PREVIEW: --learn for Nemotron (its states stay in memory), and a pool of kept buffers as Flash Next has. Each state allocates its own buffer today; that showed no cost at this size (below).

Exactness

Same binary, same checkpoint, same settings; cache on against --prompt-cache-gib 0. Four-turn greedy chats, a 9.2k-token system prompt, 96 reply tokens a turn.

Check Result
One conversation, cached turns vs cache off equal, 4/4 turns
Two conversations at once (--parallel 4), each vs its solo cache-off run equal, 8/8 turns
--no-drafts, cached vs cache off equal, 4/4 turns
Drafted vs --no-drafts equal, 4/4 turns

Resumes happened at 9,213 tokens (the shared system block's cut) on turns 2 and 3 and at 9,556 (the previous turn's state) on turn 4, so both kinds of kept state were exercised.

Speed

Cache off Cache on
Turns 2-4, prompt time 1.29-1.36 s 0.28-0.31 s
A fresh 9.2k-token prompt, mean of 4, alternated on/off/on 1.07 s 1.07 s (keeping two states of 106 MiB each)
Two conversations at once, turns 2-4 - 0.40-0.60 s

Memory

Peak physical footprint (/usr/bin/time -l) for the server through two four-turn conversations of about 9k tokens: 25.08 GiB with the cache off, 25.59 GiB with it on. A kept state at 9.2k tokens is 106 MiB, most of it the fixed Mamba state.

Receipts

  • Machine: Apple M5 Ultra, 256 GB, macOS 27.0.1. Zig 0.17.0, Metal Toolchain 27A266a. Base commit f8fe17d.
  • Checkpoint: TensorFold/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-MLX-4bit, revision d9d758fb83953437f7263256b0d96157e2a348b8.
  • Settings: serve --context 32768 --temperature 0 --no-thinking, max_tokens 96 (8 for the fresh-prompt timing), the repository's CHANGELOG.md and docs/recipes/qwen3.8-flash-next.md (first 30k characters) as system prompts, four questions each.
  • zig build test -Dcpu=apple_m1: 91/91 steps, 93/93 tests on the final tree, and on five earlier runs. One early run, before the final tree, had one failing host test that I did not capture and that did not recur in seven later runs.
  • zig build test-golden -Dcpu=apple_m1: 188 equal, 0 differ, 2 known (errors), the same on clean main; the leak reports it prints come from golden_check itself and are the same on main.
  • tools/zig/lean_check.py: 512 problems on main, 512 after. The five findings in the touched files are inherited (backend.zig:299, backend.zig:392, native/metal.zig:1, and two in flashnext/snapshot.zig).
  • zig fmt --check clean; every touched source file stays under 600 lines.
  • Not run: CUDA (no GB10 here; the CUDA backend's prefill is separate and unchanged), Metal on M1 to M4, prompts past 32k, and sampled requests with the cache (the matrix was greedy, as the exactness contract names it).

🤖 Generated with Claude Code

…act against cache-off

Nemotron keeps each stream's prompt state at the prompt cache's marks and resumes a later request whose prompt extends one, as Flash Next and GLM do. A kept state is every Mamba conv and SSM state, the KV rows and the draft head's KV rows, in one Metal buffer (families/nemotron/snapshot.zig). Save and restore are tf_copy_u32 dispatches on the engine's fenced queue, a save right after the chunk that ends at the mark and a restore right before the first chunk, so neither waits for the host.

The prompt pass in backend.zig restores before its first chunk and calls the mark hook after each chunk at a mark, which covers the shared-lane and lone-stream paths alike. The Nemotron host in native/metal.zig sizes its store as Flash Next does (cache_fit, or --prompt-cache-gib; 0 turns it off).

On an M5 Ultra, turns 2-4 of a 9.2k-token chat take 0.28-0.31 s instead of 1.29-1.36 s, a fresh prompt costs the same on or off (1.07 s), and every reply equals its cache-off reply: alone, two conversations at once, and with --no-drafts. The receipt is in docs/recipes/nemotron-3.5.md.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@BobClawblaw

Copy link
Copy Markdown
Contributor Author

Spark (GB10) check

Same steps on clean main (f8fe17d) and this branch (5aa6142), on an NVIDIA GB10 (DGX Spark), Linux aarch64, Zig 0.17.0, CUDA 13.2.

Step main This PR
zig build native (CUDA server, sm121 fatbins) 25/25 steps 25/25 steps
zig build test 75/76 tests, 1 fails 75/76 tests, the same 1 fails
zig fmt --check on the four touched .zig files - clean
zig build test-golden macOS only macOS only

The CUDA build starts from families/nemotron/cuda.zig, which imports none of nemotron.zig, backend.zig, snapshot.zig or native/metal.zig, so a clean CUDA build is what this PR should give, not a test of it.

The one failure is on main too, and it is a Linux-only test bug: direct_io.test.direct reads return the same bytes as buffered reads (zig/src/core/direct_io.zig:98) opens its "plain" file with O_DIRECT and then only sets plain.direct = false, so the unaligned 1-byte pread on that descriptor fails with EINVAL (-1). The test skips on macOS, which is why the receipts above show 93/93. Opening the plain file without .DIRECT should fix it; that belongs in its own PR.

Not run here: a live Nemotron generation on GB10 (no checkpoint on this box, and no CUDA code changed).

@BobClawblaw

Copy link
Copy Markdown
Contributor Author

Mac (M5 Ultra) check

The Mac side of the check the Spark comment refers to: the same pr497_mac_check.py suite against this branch (5aa6142), every reply compared with the same case on a cache-off server.

  • Machine: Apple M5 Ultra, 256 GB, macOS 27.0.1. Zig 0.17.0, Metal Toolchain 27A266a. Binary from zig build native -Dcpu=apple_m1.
  • Checkpoint: TensorFold/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-MLX-4bit, revision d9d758fb83953437f7263256b0d96157e2a348b8.
  • Settings: --temperature 0 --no-thinking, max_tokens 96, streamed; --parallel 8 (2 for saturated), --context 32768 (131072 for long).
Phase Replies Equal Mismatch Errors No reuse where expected
ref 16 16 0 0 0
on 103 103 0 0 0
on-stress 528 528 0 0 0
tiny-stress 264 264 0 0 0
tiny 16 16 0 0 0
saturated 176 176 0 0 0
long 12 12 0 0 0

1,115 replies, 0 mismatches, 0 errors the reference did not also give, 0 second runs that read their prompt again. zig build test -Dcpu=apple_m1 30 of 30 passed, so the one host-test failure the PR saw once did not reproduce.

  • Time to first token on the cached second runs: median 0.03 s against 1.03 s with the cache off (9k-token prompts).
  • on-stress: 528 replies in 86 s; tiny-stress (--prompt-cache-gib 0.25, two kept states): 264 replies in 183 s. Per reply that is 0.16 s against 0.69 s, but with a two-state budget nearly every request re-read its whole prompt, so this run does not separate the eviction drain's cost from plain cache misses.
  • saturated (10 threads on 2 lanes): 176 replies in 42 s, all equal.
  • long: a 3-turn chat at 89,192 / 89,317 / 89,439 prompt tokens, cached on the second run, all equal. The edge case resumed at 129,921 and 130,043 tokens of a 131,072 window and stayed inside it, so this run did not reach the past-the-window error path (the script's 2% trim stepped past the exact edge).
  • Phases: ref, on (solo twice, draft:false, seeded sampling solo and 3x concurrent, connections dropped in the prompt pass and after the first token, 8 threads x 12 reps), tiny, saturated, long, zigtest; nothing skipped.

Peak memory was measured separately in the PR description (25.08 GiB off, 25.59 GiB on, two 9k-token conversations).

@ashhart

ashhart commented Oct 10, 2026

Copy link
Copy Markdown
Owner

Thank you, @BobClawblaw. This gives Nemotron the prompt reuse the other families already had, and doing the keep and
the resume as copies on the engine's own queue was the right call: nothing waits on the host, and no kernel or
summation order changes.

It's on main as 2b8790c9b, under your name. Main moved a fair way past your base, mostly Sliding Weights (--slide),
which changes the weights while a server runs. Your store already belonged to the lane host, and the lane host drops
every kept state when a lesson moves the weights, so nothing stale survives. Our follow-up b08bb0161 adds a test for
that. The same commit sets the store field to null at startup (the host is allocated without its field defaults, so with
--prompt-cache-gib 0 it was never set), plans the budget through cache_fit.budget so /v1/memory shows it and an
over-cap --prompt-cache-gib prints the reason, and marks the lane host as caching so /metrics counts restored tokens.

We checked it on an M3 Ultra, a chip without tensor units. All 21 replies matched the cache-off server: three chats,
two chats at once, "draft": false, a request dropped mid-prompt and sent again, and two fresh prompts. 48 more matched
with 16 requests at once on a half-GiB budget. The second turn of a 19.8k-token chat prefilled in 0.16 s instead of
8.07 s, and fresh prompts cost the same with the cache on or off.

We re-made the commits without their AI-tool trailer lines, which main's history doesn't carry, so GitHub shows this PR as closed rather than merged. The commit is yours.

@ashhart ashhart closed this Oct 10, 2026
eleqtrizit pushed a commit to eleqtrizit/TensorFold that referenced this pull request Oct 10, 2026
…hy, metrics and /memory see it

Lands ashhart#497 on main. The Nemotron host is gpa.create'd, so its optional store field never took its
default: with --prompt-cache-gib 0 close() read undefined memory. It is set to null before the budget
is planned, as the Sliding Weights field is.

The budget now comes from cache_fit.budget, as for Flash Next and the 27B: the same 70% rule, its
plan on /memory, and the full refusal text when --prompt-cache-gib passes the cap. The server prints
an engine's reason when the engine fails after giving one, where it printed only the error's name.
The lane host reports prompt_cache, so /metrics counts restored prompt tokens.

The store is the lane host's own (h.host.cache), so a Sliding Weights step that moves weights drops
every kept state; a lane-host test now checks that the turn after such a step prefills from the start.
eleqtrizit pushed a commit to eleqtrizit/TensorFold that referenced this pull request Oct 10, 2026
@BobClawblaw
BobClawblaw deleted the nemotron-prompt-reuse branch October 15, 2026 15:21
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
…hy, metrics and /memory see it

Lands ashhart#497 on main. The Nemotron host is gpa.create'd, so its optional store field never took its
default: with --prompt-cache-gib 0 close() read undefined memory. It is set to null before the budget
is planned, as the Sliding Weights field is.

The budget now comes from cache_fit.budget, as for Flash Next and the 27B: the same 70% rule, its
plan on /memory, and the full refusal text when --prompt-cache-gib passes the cap. The server prints
an engine's reason when the engine fails after giving one, where it printed only the error's name.
The lane host reports prompt_cache, so /metrics counts restored prompt tokens.

The store is the lane host's own (h.host.cache), so a Sliding Weights step that moves weights drops
every kept state; a lane-host test now checks that the turn after such a step prefills from the start.
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
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