Skip to content

prompt cache: Qwen3.8-27B on Metal keeps states at message starts behind TF_QWEN27_MESSAGE_STARTS (#3617) - #4932

Merged
ashhart merged 6 commits into
ashhart:mainfrom
mrv777:qwen27-metal-message-starts
Nov 25, 2026
Merged

ashhart merged 6 commits into
ashhart:mainfrom
mrv777:qwen27-metal-message-starts

Conversation

@mrv777

@mrv777 mrv777 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Qwen3.8-27B on Metal can keep prompt states at a chat request's message starts, behind TF_QWEN27_MESSAGE_STARTS=1 (off by default). It builds on the starts #3679 already records: the store plans states at up to four of the request's latest message starts, and the rewind state moves back to the last user message's start, role header included. A later request that edits a tool result or replaces a message in that history then resumes from that message's start, where main re-reads the whole prompt. Unset or 0 leaves every plan exactly as on main.

  • What is kept. A new planner step, core/prompt_message_starts.zig, runs after the ladder in lookupUserAt. Candidates are Request.message_starts strictly between the resume point and the history end, at least min_gap (256) from the resume point, the history end, the other marks and each other. The latest are taken first, at most Rules.message_starts (4 for the 27B). The lane host scopes the request's starts onto the store around its lookup, as it does for salt. No family code reads the starts, and the Metal pass already cuts at any planned mark.

  • The rewind mark. With the switch on, an unplanned family's rewind sits at the last message start within min_gap before rewind_len, which is the last user message's own start with its role header. A next turn that replaces that whole message, rather than editing its text, now resumes there. This is the point Synthena raised above.

  • Scope. The Qwen27 Metal host also serves SenseNova-Loop. A looped checkpoint keeps main's plan with the switch set (qwen27_resume.messageStarts(looped)), so the opt-in reaches Qwen3.8-27B only.

  • Memory. The planner admits a start only into room that free space or redundant (superseded) states hold. The guarded reservation then gives non-endpoint marks only free room plus the resumed state's credit, so start states never displace another kept state. Under pressure they are trimmed before the pass (counted in trimmed), and nothing else changes. A growing conversation plans none, because its resume point already sits at the previous reply's end.

  • Issue: Refs Prompt cache: keep a state at every message start, in every family, by default (exact) #3617 (the Qwen3.8-27B Metal slice of step 3; default-on is step 4)

  • Stacked on: main

  • atc overlap --json: run after rebasing on ed70f71aa. Three open PRs conflict on neighbouring lines: glm(metal): gate in-memory 4-bit/64 MTP draft head on GLM_DRAFT_HEAD_Q4 #4253 and CPU: Qwen3.5-2B served on the host's cores (zig build native-cpu), every operation in the kernel contract, judged against a float64 reference #2551 (registry and parser-test rows in environment.zig, its test and docs/environment.md) and Implement GLP control vectors with a fused Metal kernel for Qwen3.8-27B #1835 (CHANGELOG.md and qwen27_served.zig). Whichever lands second takes both. Seven are clean, and the rest unknown (ATC hit its PR limit).

Checks on this head

  • Head commit: de46458cf (base ed70f71aa; it merges cleanly with main at 9961ca492); tools/pr_check.py --pr 4932 --base upstream/main: 0 errors, 0 warnings
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: base 165, head 165, 0 new (tools/zig/lean_new.py)
  • Tests run, with the command and pass, fail and skip counts:
    • zig build test-prompt-cache-host -Dcpu=apple_m1: 785 passed (8 new in prompt_cache_message_starts_test.zig)
    • zig build test-message-starts-resume-host -Dcpu=apple_m1 (new step): 34 passed, 2 of them the new tool edit starts: tests. Real chat histories go through openai.chatInput and chat.prepare, through ChatML and through Qwen3.8's own qwen38.jinja. An edit to the last of four tool results resumes at that tool message's recorded start, and the resumed hash equals a fresh pass. Unset resumes from 0.
    • zig build test-qwen27-resume-host -Dcpu=apple_m1: 25 passed, 1 new: the switch's starts reach a plain checkpoint and never a looped one.
    • test-request-starts-turns-host, test-qwen27-reply-cache-host, test-qwen27-startup-host, test-qwen27-keep-host, test-cache-store-host, test-conversation-cache-host, test-cache-progress-host, test-cache-spares-host, test-cache-replay-host, test-cache-agent-host, test-cache-decay-host: all pass.
    • test-environment-host, test-environment-report-host, test-capability-env-host, test-env-defaults-host, test-profile: all pass.
    • zig build test test-kernel-contract test-golden fuzz-cortheon -Dcpu=apple_m1 (on the previous base; CI ran it green on a81150e85): the same three failures as on main at the base, and nothing new. These are six std.mem compile errors ("Only nullable and allowzero pointers can be set to zero"), mtp_pick.zig's missing bf16_topk module, and the test info prices a Qwen3.8-27B start from serve's charge. Golden: 0 unexpected differences.
    • zig build: passes
    • zig fmt --check build.zig zig, git diff --check: clean
    • New tests fail without the change. Neutering add fails the edit, budget, superseded-room and raw-prompt tests. Letting non-redundant states count as free fails the no-displacement test. Neutering rewind fails both rewind tests.
  • CI: all green on a81150e85 and 3ed03cf90; pending on this push
  • Not run, and why: chips other than the M5 Ultra (I have no other Mac).

Receipt

  • Main against branch: the cells below, measured with main at a0f809ea0 against this change on that base, on the same machine, checkpoint and settings. The branch has since been rebased onto ed70f71aa. The rebases touched neighbouring registry rows and the changelog, and moved one test call into main's new qwen27_served_test.zig; the host checks above were re-run on the rebased head.

  • Boxes it reaches: Qwen3.8-27B on Metal with TF_QWEN27_MESSAGE_STARTS=1. With the switch unset no plan changes on any family: Rules.message_starts defaults to 0, and only the 27B Metal host sets it, never for a looped (SenseNova-Loop) checkpoint.

  • New switch? TF_QWEN27_MESSAGE_STARTS, exactly 0 or 1, default 0. It is registered in platform/environment.zig with parser tests and documented in docs/environment.md, the recipe and the ledger. It has no profile row, like the other TF_QWEN27_* cache and slot switches (TF_QWEN27_SLOT_RESUME, TF_QWEN27_METAL_KV_PAGES): it changes which states are kept, not any arithmetic, and the replies below are token-identical.

  • Environment: TensorFold a0f809ea0 (main) and this change on it, Zig 0.17.0 ReleaseFast. Mac Studio M5 Ultra, 64-core GPU, 96 GB, macOS 27.2. Qwen3.8-27B MLX 4-bit (local conversion), DFlash2 z-lab/Qwen3.8-27B-DFlash2 at 50307d4c. --parallel 1 --context 40960 --prompt-cache-gib 12 (0 for the cold controls), TF_PROMPT_ROWS=512, thinking off, one server start per cell.

  • Paths and platforms the change reaches, which I ran and which I could not: the Qwen27 Metal lane host, with and without DFlash2, greedy and seeded, on an M5 Ultra. Not run: M1 to M4. The planner is shared core code, but no other family sets message_starts.

  • Exactness on the final tree, for the review: this change (with the SenseNova scope) rebased onto main 9961ca492, the same M5 Ultra, checkpoint and settings, 256-token long answers, two server starts per cell, 32 runs in all.

    • State: a measurement-only probe logs Session.fingerprint() for the slot once its prompt pass ends, before the first decode round. That hashes every layer's committed DeltaNet state, the visible K/V rows and the last row's logits. The probe isn't in this branch.
    • Paths: resumed at the edited tool message's start (edit, 20,995 tokens reused) and resumed after only the preceding turn (prior, 20,961 reused), each against the fresh cache-off pass. Greedy and seeded (seed=7, t=0.7), with and without DFlash2. Without a drafter, the bank captures marks inside a chunk. With DFlash2, and in a second build that refuses the bank (the NoBuffer fallback, forced), the pass splits its chunks at each mark instead.
    • Result: every resumed run's fingerprint equals the fresh pass's (c13624874828…, the same in every cell, drafter on and off), and every reply's token IDs are equal (greedy f5bd5681a3…, seeded 52fa3ce563…).
    • SenseNova-Loop: no device run; I have no looped checkpoint. With the scope above it keeps main's plan, which the new host test pins.
  • Exactness on a0f809ea0, as first posted: the fixture is the one from my earlier comment, rebuilt: four read_file results of public repo docs, rendered to exactly 32,768 tokens, with the last result's BUILD_MARKER=17 edited to 19.

    • Every edited request's reply token IDs equal the fresh cache-off replay's: resumed at the tool message's start, resumed after only the preceding turn, and main with the cache on. That holds greedy and seeded (seed=7, t=0.7), with and without DFlash2. Greedy IDs are also equal across drafter on and off.
    • Short answer, two runs each: 3 tokens with EOS, 19.
    • Long answer, one run each (summarize the edited file, 256 tokens): greedy 9183534beb…, seeded 350f58413e….
    • One observation on unmodified main, outside this change: the very first long-answer run of main with --prompt-cache-gib 0 and DFlash2, greedy, diverged at token 8. Runs 2 and 3 of that same cell matched everything above. I haven't chased it; I can open an issue if useful.
    • tools/bench_concurrent.py --levels 1,4 --alone --serial with the switch on: every request equal alone and serial at 1 and 4 streams. Its token_sha values equal main's.
  • Main against this branch, same machine and checkpoint: (seconds to first visible output, client-side)

    Request, 32,768 tokens main branch, unset branch, =1
    Edit the last tool result, then the question (DFlash2) 0 cached, 24.62 / 25.40 s 0 cached, 24.70 / 24.52 s 21,054 cached, 9.61 / 9.56 s
    Same, no drafter 0 cached, 24.44 / 24.37 s 0 cached, 24.44 / 24.44 s 21,054 cached, 9.64 / 9.67 s
    Served the turn before the last tool turn, then the edit (DFlash2) (main resumes 0) n/a 21,007 cached, 9.73 s (14,108 and 14.8 s before the rewind fix)
    Append the question to the unchanged history n/a n/a 32,739 cached, 0.13 s
    Cold first request with the cache on (the edit cells' first request) 24.44–25.55 s 24.42–24.77 s 24.48–25.10 s
    Cold, cache off (--prompt-cache-gib 0) 24.31–24.56 s n/a n/a

    In the edit fixture the marker sits about 7,000 tokens into the last tool result, so a resume from that message's start still reads those 7,000 rows and the 4,700 after them. Where the edit is near a message's start, as in my earlier comment's fixture (68 tokens), the saving is close to the whole prefix.

  • Decode speed before and after, from tools/bench_openai.py (ABBA, --parallel 4, DFlash2, greedy): code 215.8 / 216.9 tok/s on main against 217.1 / 216.9 on the branch; chat 152.8 / 153.4 against 153.5 / 153.1. bench_concurrent at 4 streams: code 385.4 / 384.7 against 383.2 / 382.8; chat 301.8 / 335.7 against 300.3 / 300.5, where main's second run is the outlier (its round-gap p95 was 33.8 ms, against 45–46 ms on every other run). These short prompts carry no planned starts, so the switch changes no plan in these cells.

  • Prompt speed before and after: with --prompt-cache-gib 0 nothing is planned, so cold prompts are main's. With the cache on and free room, a cold 32K chat request keeps 6 states (about 10 GB) instead of main's 2 (5 GB). With DFlash2 each start that is not already a chunk end costs one more prompt pass, so expect about four passes (~0.1 s) plus four ~1 GB blits, roughly 0.5% of a 25 s pass. I couldn't resolve that on this Mac, which had other GPU work running: ABBA across fresh servers (4 and 6 pairs) and an in-process ABAB (8 pairs, cache flushed before each request, starts toggled per request in a measurement-only build) gave paired differences from -2.1 to +2.0 s, medians +0.1 to +0.5 s, with whole rounds at 39–40 s for every variant. Under pressure the reservation trims the starts and the pass is main's. If you'd rather have no extra passes, the starts could snap down to the pass's existing chunk ends, at the price of up to TF_PROMPT_ROWS rows on each resume. I didn't do that here.

  • Licence of any new weights or drafter: n/a

Host replay: why four starts, and why only promised room

I replayed synthetic agent traces through the real store with the 27B's state sizes. The traces had 1, 3 and 6 interleaved sessions, 8, 12 and 16 GiB budgets and 12 seeds. Edit mixes were none, trimming an old tool result, swapping a note in the last user message, editing the last tool result, and a cold history followed by an edit.

  • An admission that may evict other conversations' states, as the ladder's does, was the worst variant at every budget: +98 to +760 modelled seconds of prefill, with 2x the evictions.
  • The rule here kept every mix within ±1 s of unset under pressure. The guarded reservation trims most planned starts there, and no other state is displaced.
  • With room to spare (an unlimited budget), one start saved 8% of recompute on the edit mixes and sixteen saved 16%. Four is the compromise: the extra plans cost nothing when they're trimmed.
  • Freeing redundant states for starts in the guarded reserve, and tiering start states like ladder rungs, measured another 1% on edit-heavy traces. Both are changes to shared eviction code, so I've left them out of this switch.

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.
  • 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.
  • No precision traded for speed. If the bits change, the description says which sums change and why.
  • 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

mrv777 added a commit to mrv777/TensorFold that referenced this pull request Nov 24, 2026
@mrv777
mrv777 force-pushed the qwen27-metal-message-starts branch from dfb88e9 to 02badbb Compare November 24, 2026 18:21
mrv777 added a commit to mrv777/TensorFold that referenced this pull request Nov 24, 2026
mrv777 added a commit to mrv777/TensorFold that referenced this pull request Nov 24, 2026
@mrv777
mrv777 force-pushed the qwen27-metal-message-starts branch from a81150e to 3ed03cf Compare November 25, 2026 04:14
mrv777 added a commit to mrv777/TensorFold that referenced this pull request Nov 25, 2026
@AIFlowML

Copy link
Copy Markdown
Contributor

I test-merged 3ed03cf90514c3af064a759b9618c366ff81c968 onto main 4c79cfe346d3c239ff7dfd7aa694df799755bafa, with no conflict. On Apple silicon with Zig 0.17.0:

zig build test-prompt-cache-host test-message-starts-resume-host \
  test-request-starts-turns-host -Dcpu=apple_m1 --summary all

All 854 tests passed: 785 prompt-cache, 34 resume and 35 request-start tests. That covers edits to a tool result with ChatML and the Qwen3.8 template, the switch-off control, and the existing request-start fixtures in the same trial tree. These are host and scripted-route checks. I did not rerun the 27B checkpoint's Metal timing or token comparison.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thank you, @mrv777. The off path preserves the existing plan, and the new starts retain endpoint priority and reservation protection. The host checks cover tool-result edits through both templates.

This is ready for controlled comparisons. Exact fresh/resumed tokens and state on the final tree remain, including the fallback when interior capture is unavailable. The shared host also serves SenseNova, so scope the switch or qualify that path before using it there.

  • Synthena

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

@mrv777, our device check on an M3 Ultra, with Qwen3.8-27B and the switch off: prompt-fill tokens equal main's in all 8 rows, and speed is level with main at 1 and 4 streams. So the default path is unchanged.

The opt-in path still needs the checks from the review:

  • resumed equals fresh, in tokens and state, on the final tree, including the fallback when interior capture is unavailable;

  • the switch scoped away from SenseNova-Loop, which the same host serves, or that path qualified too.

  • Synthena

@mrv777

mrv777 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @ashhart, and thanks for the M3 Ultra off-path check.

SenseNova-Loop. de46458cf scopes the switch away from it: a looped checkpoint keeps main's plan with TF_QWEN27_MESSAGE_STARTS=1, so the opt-in reaches Qwen3.8-27B only. A new test-qwen27-resume-host test pins that. I don't have a looped checkpoint, so I haven't qualified that path on a device.

Resumed equals fresh, in tokens and state, on the final tree. I ran this change, with the scope, rebased onto main 9961ca492 on the M5 Ultra. A measurement-only probe, not in the branch, logs Session.fingerprint() when the slot's prompt pass ends. That covers every layer's DeltaNet state, the visible K/V and the last logits. 32 runs, 256-token answers, two server starts per cell:

Path Reused Greedy Seeded
Fresh, cache off (reference) 0 state c13624874828…, tokens f5bd5681a3… state c13624874828…, tokens 52fa3ce563…
Edit resumed at the tool message's start, mark bank (no drafter) 20,995 equal equal
Same, bank refused: chunks split at marks (forced fallback build) 20,995 equal equal
Same, DFlash2 (always splits) 20,995 equal equal
Only the preceding turn served, then the edit: bank, forced split, DFlash2 20,961 equal equal

Every resumed fingerprint and every reply's token IDs equal the fresh pass's, with and without DFlash2. The branch itself stays on ed70f71aa plus the new commit, since you rebase at landing; it merges cleanly with current main. The description has the details.

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thank you, @mrv777. The switch now excludes SenseNova-Loop through the parsed checkpoint config. The reported 32 M5 runs cover fresh/resumed tokens and state, including bank refusal, split fallback and DFlash2. That closes the earlier asks; the M3 default-off result remains accepted.

The current head merges cleanly and is ready to land after the usual final checks.

  • Synthena

ashhart and others added 6 commits November 25, 2026 18:24
…ind TF_QWEN27_MESSAGE_STARTS (ashhart#3617)

With TF_QWEN27_MESSAGE_STARTS=1 a chat request plans prompt states at up to four of its latest message
starts (the exact token offsets ashhart#3679 records), and the rewind state moves back to the last user message's
start, role header included. A later request that edits a tool result or replaces a message in that history
resumes from that message's start instead of re-reading the whole prompt.

The starts only take room the cache can already promise beside the request's own endpoint: they never
displace another kept state, and under pressure the reservation trims them before the pass. Unset or 0
leaves every plan as on main. Raw prompts carry no starts and are unchanged.
…nts on main's plan (ashhart#3617)

The Qwen27 Metal host also serves SenseNova-Loop. Its looped checkpoints now keep main's prompt-cache plan with the
switch set, so the opt-in reaches Qwen3.8-27B only.
@ashhart
ashhart force-pushed the qwen27-metal-message-starts branch from de46458 to 4043a6a Compare November 25, 2026 18:25
@ashhart
ashhart merged commit f36accc into ashhart:main Nov 25, 2026
2 of 12 checks passed
ashhart pushed a commit that referenced this pull request Nov 25, 2026
@ashhart

ashhart commented Nov 25, 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.

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