Skip to content

qwen27 metal pages: a stream promises its pages as its rows come and gives them back when it leaves - #3377

Merged
ashhart merged 4 commits into
ashhart:mainfrom
CodingEmil:qwen27-demand-pages
Nov 21, 2026
Merged

ashhart merged 4 commits into
ashhart:mainfrom
CodingEmil:qwen27-demand-pages

Conversation

@CodingEmil

Copy link
Copy Markdown
Contributor

What this changes

Before, TF_QWEN27_METAL_KV_PAGES=1 promised every slot the pages of its whole window when the model loaded (kv_pages.caches), and the promise stayed for the server's life; pages were already taken as rows came. With this change, a stream that opens a slot is promised the pages of its prompt and one widest pass. A pass past that promises the rest before it takes a page, and a promise the pool cannot meet fails with LaneMemory before any page is taken or any table entry written. A stream that leaves, a prompt pass that fails or goes back to the queue, a reset and a move to slot 0 give back the slot's pages and its promise; a standing slot 0 keeps the pages of its committed rows for its resume. Without the flag, nothing changes.

Checks on this head

  • Head commit: 864e6f1d5 on 7238ed8e9.
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: 341 on the base, 341 on the head, 0 new (tools/zig/lean_new.py). The 341 are inherited. No touched file is over 600 lines: decode_round.zig is at 594, because the page lifecycle is in the new families/qwen27/slot_pages.zig and the runner keeps one-line aliases to it.
  • Tests run, with the command and pass, fail and skip counts:
    • zig build test-qwen27: base 149 passed, 2 skipped; head 183 passed, 2 skipped. The 8 new tests in slot_pages_test.zig run in it (alone, through a test filter: 11/11). The rest of the increase is core tests the new test file brings into the module's test binary.
    • zig build test-qwen27 test-qwen27-reply-cache-host test-qwen27-startup-host test-lane-api-host test-lane-strand-host test-lane-halt-host test-lane-lone-host test-lane-interrupted-host test-kv-pool test-prefill-service-host test-flashnext-batch-host: 84/84 steps, 1083 passed, 2 skipped.
    • zig build native tf-qwen27-attention-pages tf-qwen27-pages-resume -Dcpu=apple_m1: builds.
    • zig build test test-golden -Dcpu=apple_m1 --summary all, with the GPU free: 870/870 steps succeeded, 13807 passed, 116 skipped, 0 failed. Five test steps came from the build cache, and the summary does not count their tests.
    • zig fmt --check build.zig zig and git diff --check: clean.
    • python3 tools/pr_check.py: 0 errors, 1 warning (it asks for --pr NUMBER to check the Unreleased line).
    • Failing before: the new functions do not exist on the base. To show the change rather than the compile error, I swapped slot_pages for the base's policy: the whole window promised at the first open, a growth taking pages only, leaving and a reset touching nothing. All 8 new tests fail with it.
  • New tests, one or more per point of @jschmied's list in Metal: KV pages from the core pool #1293:
    • a promise or a growth the pool cannot meet fails with LaneMemory, with no page taken, no table entry written and the pool's counts unchanged;
    • no leaks: a stream that leaves mid-prompt (cancelled or failed) gives back every page and its promise;
    • a reset mid-prompt gives back the slot's pages before the new prompt takes its own, and a kept holder's page stays held;
    • a move to slot 0 (promote) leaves the old slot empty and unpromised;
    • a reply that finds no page mid-run fails its growth, and once the round's streams leave, no page or promise is left;
    • a standing slot 0 keeps the pages of its committed rows, nothing past them and no promise;
    • two streams promised their prompts open on a pool smaller than two windows and each grows as its rows come;
    • two streams grow in turn to their whole windows, and leaving gives every page back.
  • CI: not run yet (nothing pushed).
  • Not run, and why:
    • zig build dev-tools: the runner's cover, promise, release and reset keep their call shape (aliases), and the two page tools build.
    • the failed-pass release in qwen27_slots.prefillStep has no host test, because it needs the Metal backend. On the device, the cell that cuts a stream mid-prompt ends with every page free; I have not checked that the cut takes this path rather than unbind.

Receipt

  • Main against branch: measured in one sitting on the M5 Ultra, base 7238ed8e9 (A) against 864e6f1d5 (B), a fresh server per cell, --context 65536 --parallel 2 --prompt-cache-gib 0. Every reply hash is equal, speed is level, and every stop with the flag reads KV pages idle, 514 of 514 free with no LaneMemory. The cells are in the lines below.
  • What a user of this pull request alone gets: nothing measurable. It is groundwork for kept states holding pool pages (Metal: KV pages from the core pool #1293 step 4, on prompt radix: pages carry their reuse identity, and a request's chunk starts decide its resumes (#2444 P2, C6) #2888). @jschmied, in Metal: KV pages from the core pool #1293 you expected this part to be where most of the memory goes today; on the device it is not, for the reasons below, and the footprint cell confirms it.
    • The arena is still sized for every slot's whole window and allocated when the model loads (kv_pages.caches: slots × pages(capacity)).
    • On qwen27 metal: M5 takes TF_QWEN27_METAL_KV_PAGES; a paged prompt chunk finds its two pages once #3180 pages were already taken as rows came (Pages.cover from the promise), so the pages written, the arena and the footprint are the same.
    • No more slots and no longer context become possible: a prompt is still limited to its slot's window (qwen27_slots.opening, PromptTooLong).
    • What changes is the pool's promised count. No other holder of pages exists on main to use the room it frees: the pool belongs to qwen27's runner alone. For the same reason, a growth cannot run short of pages on main: each slot holds at most its window, and the pool has every window.
    • Measured, flag on, with the drafter: phys_footprint every 0.5 s, at idle and through two parallel 30k conversations of two turns each. A: 36 GiB idle, 37 GiB peak. B: 36 GiB idle, 37 GiB peak (footprint prints whole GiB). The eight replies have the same hashes on A and B, and the times to the first token agree within 0.02 s.
  • Boxes it reaches: Qwen3.8-27B on Metal with TF_QWEN27_METAL_KV_PAGES=1.
  • New switch? Default, accepted values, profile row: none, it changes only what the existing flag does.
  • Environment, with the TensorFold commit, Zig and backend toolchain, machine and GPU, checkpoint and revision: 864e6f1d5 on 7238ed8e9, Zig 0.17.0, Xcode 27.2 (27B52), Metal Toolchain 27B47, Apple M5 Ultra, 96 GB, macOS 27.2. Device cells: TensorFold/Qwen3.8-27B-MLX-4bit, with the z-lab/Qwen3.8-27B-DFlash2 drafter where a line says so.
  • Paths and platforms the change reaches, which I ran and which I could not:
    • Reached, with the flag: a stream opening a slot (bind, and the lone driver's slot 0); every pass's pages (Runner.cover from verify, a kept state's restore and a move); a stream leaving (unbind); a prompt pass that fails or is requeued (prefillStep); a reset (ready, opening, refill, costs); promote.
    • A rewind keeps its pages (snapshot.rewindSlot clears the DeltaNet state only).
    • Not reached: the flag off. Runner.kv is null, every slot_pages entry returns at once, and the failed-pass release returns at once too.
    • Ran: host tests and the device cells on macOS / M5 Ultra. Not run: M1 to M4. The change has no device code; jschmied's M3 Pro covered qwen27 metal: M5 takes TF_QWEN27_METAL_KV_PAGES; a paged prompt chunk finds its two pages once #3180's _sg kernel, and this pull request adds none.
  • Exactness, from tools/bench_concurrent.py --alone --serial or token_sha against "draft": false: --tokens 256 --reps 3 --temperatures 0 --levels 1,2 --alone --serial, with the drafter, on four servers: A and B without the flag, A and B with it. Each: alone 3/3 and 6/6 equal, serial equal, 0 failed, on code and chat. All 54 token_sha256 of a server are equal to the same 54 on each of the other three.
    • Resumed equals fresh (B, flag on, drafter, --prompt-cache-gib 8): a 19,711-token second turn resumed from its slot (cached 19,686), resumed after two other prompts took both slots (cached 19,688), and cold on a fresh server (cached 0) gives one token_sha256.
    • A stream cut by the client 6 s into a cold 32k prompt, then an 8k prompt, twice (B, flag on): both 8k prompts answer in 5.31 s, the cold 8k time, and the stop reads 514 of 514 free.
    • tf-qwen27-attention-pages (plain and --shared-prefix) and tf-qwen27-pages-resume on B: PASS.
  • Main against this branch, same machine and checkpoint, posted before asking for a run on our machines (or why you can't): the lines above and below.
  • Decode speed before and after, from tools/bench_openai.py --tokens 256 --reps 3 --temperatures 0, flag on, no drafter, A B B A, median tokens/s: fibonacci-raw 48.33, 48.29, 48.20, 48.24; gpu-chat-no-think 48.25, 48.29, 48.25, 48.26. Same token_sha on all four.
  • Prompt speed before and after: cold 8k and 32k from tools/bench_cache.py --require-cold, flag on, no drafter, A B B A, time to the first token: 8k 5.292, 5.292, 5.292, 5.291 s; 32k 23.369, 23.365, 23.361, 23.362 s. Same token_sha256 on all four, cached_tokens 0.
  • Licence of any new weights or drafter, or "n/a": n/a, none.

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 (host pool, 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: resumed and concurrent are measured above. Drafted against "draft": false is not run on this head; the change touches no drafting code.

  • No precision traded for speed. No arithmetic changes.

  • Decode and prompt processing are no slower than main at one stream and the widest admitted (cells above; two streams through bench_concurrent --levels 1,2).

@ashhart

ashhart commented Nov 15, 2026

Copy link
Copy Markdown
Owner

DEVICE. @CodingEmil, the eight page-promise host cases pass, along with native builds, all 16 Qwen runtime libraries and zero new lean findings. The source waits for readers before ordinary release and preserves retained cache pages through reset and promotion.

We will run the device check on our side: cancel and resume, promotion, rewind and an outstanding keep during another fill, with pages on and off. Replies and cached counts must stay exact, and promises and released leases must return to the expected census. Green zig, zig-windows, pytest and fmt CI at this head is also needed before landing.

  • Synthena (Ash's Agent)

@CodingEmil

Copy link
Copy Markdown
Contributor Author

@ashhart rebased the stack on main 5c82ef28a: #3180 eee28f177, #3377 c41666237, #3378 e05a7720f. Only the changelog hunks moved (git range-diff); the Zig files are the same bytes as before.

On the M5 Ultra at these heads: zig fmt --check, zig build test test-golden and zig build dev-tools pass on all three, and test-qwen27-outgrown-host passes on #3378. zig build kernel-contract stops at UnrecordedRotaryCompiler here, on main as well, because this Mac has no rotary sweep on file; tf-kernel-contract --only qwen27 passes on all three and on main (40 of 40 kernels, 6 of 6 controls red).

The CI runs on this PR are waiting for approval (action_required). Could you approve them so zig, zig-windows, pytest and fmt run at this head?

@ashhart

ashhart commented Nov 15, 2026

Copy link
Copy Markdown
Owner

@CodingEmil DEVICE. On M5, all 182 full replies match main across page-on/off, greedy/seeded, plain/DFlash and four streams. An interrupted fill retained 2,048 rows and resumed them exactly; interleaved cache restores stay exact and the idle page counts balance.

Page-on 32K prefill takes 0.47-0.49% longer than main. Page-off also takes 0.12-0.22% longer in the 2K start-0 and 8K cells, beyond their observed base ranges. At ready, page-on physical footprint is 39.55-39.73 GB versus main's 30.99 GB because the whole arena is reserved. This needs a performance answer and green CI before landing.

  • Synthena (Ash's Agent)

@CodingEmil

Copy link
Copy Markdown
Contributor Author

@ashhart thanks for the device run. I measured the three points on the M5 Ultra as a three-way: main 5c82ef28a without pages (main refuses the flag on tensor-unit Macs, so there is no page-on main here), #3180 eee28f177 with pages, and this PR c41666237 with pages. --context 131072 --parallel 2 --no-drafts --prompt-cache-gib 0, a fresh server per run, greedy, time = prefill_seconds. All token_sha256 are equal per cell.

Footprint (GB, /v1/memory, 6 runs a side, all equal)

at ready one slot used both slots used
main, pages off 43.65 43.76 52.36
#3180, pages on 52.27 52.38 52.38
#3377, pages on 52.27 52.38 52.38

The 8.6 GB at ready is the second slot's window: the arena for every slot is one buffer made at load and joined to the residency set, which #3180 already does. Main without pages makes slot 0 at load and each further slot at its first use, and is level once both are used. This PR does not change the arena. It moves the promises from load to the rows, so it does not lower the footprint by itself (the description's "what a user of this pull request alone gets" says the same). What it gives is that a slot which cannot get a page fails cleanly before a write, which is what a smaller arena needs. I'd propose that as a follow-up after #3378.

32K cold prefill (s, order M A B B A M, 3 rounds, median of 6)

median vs main
main, pages off 23.220
#3180, pages on 23.363 +0.62 %
#3377, pages on 23.370 +0.65 %

So the page-on cost is the paged prompt kernels against the contiguous ones, as in #3180's cells; this PR adds 0.03 % on top, inside the spread of the runs.

Pages off, 2K and 8K cold (s, order M A B M′ M′ B A M, 3 rounds, median of 6; M′ is a second, separate build of main)

2K 8K
main 1.305 5.256
main, second build 1.305 5.257
#3180 1.305 5.257
#3377 1.305 5.257

I can't reproduce a page-off difference here: both heads are within 0.02 % of main, as close as main's second build. With the flag unset this PR runs a few extra calls per stream that return at once (r.kv orelse return), none per chunk or per token. If your cells differ from these (context, slots, start offset), tell me which and I'll run them.

The stack needs one more rebase for the changelog; I'll do it when the CI runs are approved so it doesn't go stale again.

@ashhart

ashhart commented Nov 15, 2026

Copy link
Copy Markdown
Owner

DEVICE. @CodingEmil, thanks for the three-way check. The arena allocation is already in #3180; #3377 changes the promises, so its ready footprint is not a new allocation introduced here. All 182 complete replies and the cancel/resume and page-count checks stay exact.

The differing cold cells used context 40960, parallel 4, prompt rows 2048, cache 0, raw 2048/8192-token prompts at starts 0 and 5000, temperature 0, seed 1234, draft false and 64 output tokens. A drafter was attached for separate chat checks. After discarding a warm-up, the order was main/on/off/off/on/main, two measured processes per arm. Page-off start-0 2K was 1.097337 -> 1.099804 s; 8K starts 0/5000 were 4.393875 -> 4.401946 s and 4.392679 -> 4.397897 s. Please repeat those settings alongside your separate-build main control.

CI is still awaiting approval at this head, so this remains DEVICE.

  • Synthena (Ash's Agent)

@CodingEmil

Copy link
Copy Markdown
Contributor Author

@ashhart repeated with your settings on the M5 Ultra, page-off on every arm: TF_PROMPT_ROWS=2048 … --context 40960 --parallel 4 --no-drafts --prompt-cache-gib 0, /v1/completions with raw token ids, temperature 0, seed 1234, 64 output tokens, cached_tokens 0 everywhere. M = main 5c82ef28a, M′ = a second, separate build of main, A = #3180, B = this PR. One discarded warm-up process per arm, then M A B M′ M′ B A M M A B M′, three measured processes per arm, a fresh server per process. Median prefill_seconds, difference to M:

cell M (s) M′ A B
2K start 0 1.307125 +0.011 % +0.028 % +0.007 %
2K start 5000 1.294578 +0.051 % +0.021 % +0.005 %
8K start 0 5.267426 +0.022 % −0.001 % +0.013 %
8K start 5000 5.258832 −0.043 % −0.015 % −0.077 %

Both heads are as close to main as main's second build (−0.08 to +0.03 % against −0.04 to +0.05 %), so the page-off difference does not show here. token_sha256 is equal per cell across all arms.

Two things I could not match: your prompt text (mine is a fixed synthetic token sequence, cut at offsets 0 and 5000), and the attached drafter. If you can share the prompt source or the script, I'll run exactly that. One more thought: two builds of the same main already differ in their bytes here, so a separate-build control on your side would show how much of 0.1–0.2 % is layout.

CI at c41666237: all jobs green except zig, where one test of 18,884 fails: cluster/bringup_test "two ranks settle on the real clock and agree on one plan and view" (expectEqual(x.view, y.view)). This PR does not touch zig/src/cluster, and the test runs on the real clock, so I read it as timing on the runner.

Rebased the stack onto main cf4555373 for the changelog conflict: #3180 afdb113c1, #3377 f0e5bf81c, #3378 930d220f3. Only the changelog hunks moved; main changed none of the files these touch since 5c82ef28a. That gives zig a second run once the workflows are approved at the new head.

@ashhart

ashhart commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@CodingEmil, thank you for repeating it with our settings and a second build of main. Both heads sit as close to main as main's own second build does, and token_sha256 is equal in every cell, so the page-off difference is no longer a question. Your synthetic prompt is fine; the cells only need fixed tokens.

We approved the workflows at the rebased head (f0e5bf81c); the cluster/bringup_test failure at the old head is a real-clock test this PR does not touch, so a green rerun is what we need. What remains is the parent: #3180's changed paged prompt kernels still need kernel-contract entries with controls that fail, and this lands after it.

  • Synthena (Ash's Agent)

@AIFlowML

Copy link
Copy Markdown
Contributor

I retested f0e5bf81 on M5 Max with Zig 0.17.0. The five focused host targets passed 309 tests with two skips. Applying #3180 (975703f09) to 124052c97 first left only the changelog when I layered this PR over it. After resolving that in the scratch tree, the same host targets passed 342 tests with three skips, and the native binary and tf-qwen27-pages-resume built. The resume tool matched restored, moved and fresh digests. Its 190 allocator diagnostics were identical in count on the parent-only trial merge.

On that combined tree I ran the pinned Qwen3.8-27B MLX 4-bit (22d8d538) and DFlash2 (50307d4c) with --context 8192 --parallel 2 --prompt-cache-gib 0, starting a fresh local server for each value of TF_QWEN27_METAL_KV_PAGES (0 and 1).

python3 tools/bench_concurrent.py http://127.0.0.1:PORT local-model \
  --levels 1,2 --tokens 320 --reps 1 --temperatures 0,1 --seed 1234 --alone --serial

All 12 paired full token hashes matched across page modes, with zero failed requests. The two-stream runs overlapped, and all concurrent-versus-alone and drafted-versus-plain comparisons matched. The paged server shut down with all 66 pages free. This covers the combined M5 path at the tested window; I left the parent-first landing order as noted above.

Igor Lessio - AIFLOW LABS

@AIFlowML

Copy link
Copy Markdown
Contributor

I reran the focused checks on the exact #4277 train tip c443f66dd on M5 Max with Zig 0.17.0.

zig build test-qwen27 test-qwen27-reply-cache-host test-qwen27-startup-host test-kv-pool test-prefill-service-host tf-qwen27-pages-resume -Dcpu=apple_m1 -Dversion=0.0.0 -j3 --summary all
./zig-out/bin/tf-qwen27-pages-resume

342 tests passed with three skips. The resume tool exited 0 and matched the restored, moved and fresh slot digests. It printed 190 allocator diagnostics, the same count recorded on the earlier parent-only run. This verifies the exact train's host and resume paths. The earlier served-token comparison was on the earlier trial tree.

Igor Lessio - AIFLOW LABS

CodingEmil and others added 4 commits November 21, 2026 01:29
…nit Macs take TF_QWEN27_METAL_KV_PAGES

A 512-key prompt chunk spans exactly two KV pages, so the paged prompt kernels take both page bases
before their 32-key steps instead of reading the page table at every step. The M5 refusal of the flag
goes, now that the paged kernels have run on an M5 Ultra (part of ashhart#1293).
…gives them back when it leaves

With TF_QWEN27_METAL_KV_PAGES=1 a slot no longer holds a promise of its whole window from startup.
A stream opening a slot is promised its prompt and one widest pass; a pass past that promises the rest
before it takes a page, and a promise the pool cannot meet fails with LaneMemory before any page is
taken or table entry written. Leaving, failing or being put back, a reset and a move to slot 0 give
the pages and the promise back; a standing slot 0 keeps the pages of its committed rows. The page
lifecycle is in families/qwen27/slot_pages.zig, its host tests in slot_pages_test.zig (part of ashhart#1293).
@ashhart
ashhart force-pushed the qwen27-demand-pages branch from f0e5bf8 to a82be91 Compare November 21, 2026 01:29
@ashhart
ashhart merged commit 37fa51d into ashhart:main Nov 21, 2026
3 of 11 checks passed
@ashhart

ashhart commented Nov 21, 2026

Copy link
Copy Markdown
Owner

Thank you @CodingEmil. 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.

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.

3 participants