Skip to content

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

Open
mrv777 wants to merge 3 commits into
ashhart:mainfrom
mrv777:qwen27-metal-message-starts
Open

mrv777 wants to merge 3 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.

  • 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: 3ed03cf90 (base ed70f71aa); 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.
    • test-request-starts-turns-host, test-qwen27-resume-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 the previous head a81150e85; 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.

  • 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: 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
…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.
@mrv777
mrv777 force-pushed the qwen27-metal-message-starts branch from a81150e to 3ed03cf Compare November 25, 2026 04:14
@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

This branch has not been deployed

No deployments
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