Skip to content

perf(qwen3_5 cuda): keep the prompt-end cache entry one token before the prompt's end - #65

Closed
nood-co1 wants to merge 8 commits into
ashhart:mainfrom
blockbrain-ai:contrib/cache-prompt-end-minus-one
Closed

nood-co1 wants to merge 8 commits into
ashhart:mainfrom
blockbrain-ai:contrib/cache-prompt-end-minus-one

Conversation

@nood-co1

@nood-co1 nood-co1 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The Qwen3.8-27B chat template ends the generation prompt in <think> and a newline (token 198). When the next request sends that turn back without its reasoning, the template renders it as <think>, two newlines (token 271), </think> (the checkpoint's chat_template.jinja:111-117 and :168). The next prompt then differs from the previous one in the previous prompt's final token. The cache entry for the whole previous prompt is not a prefix of it, so the conversation is prefilled from an older entry or from the start.

A turn comes back without reasoning when the client drops reasoning_content from the assistant message, when the reply had no reasoning (the server then omits the field, cuda/server.py:469-470), or when the history was produced elsewhere.

Since 0.3.6.2 the 27B also keeps states at message starts (cuda/markers.py:28-46, engine.py:128-144): the second message's start and the last assistant start, each at least MIN_GAP = 256 tokens past the resumed prefix. A prompt whose last assistant start is kept keeps no prompt-end entry, since that start lies a few tokens before its end, and its next turn resumes from that start, on main as here. A prompt whose last assistant start is less than 256 tokens past its resumed prefix keeps a prompt-end entry, and that is the entry that misses.

Both 27B prefix caches now keep the prompt-end entry at len(prompt) - 1 (engine.entry_end; a one-token prompt keeps its whole prompt):

  • the one-stream cache (engine.py, KEEP_ONE = 4 entries, one GPU and both ranks of two);
  • the concurrent decoder's PrefixCache (multi.py, KEEP = 3 entries, one GPU and two ranks).

Visible changes:

  • A next turn sent back without its reasoning resumes from the previous prompt's entry instead of an older entry or the start.
  • A prompt that extends the whole previous prompt prefills one token more. This includes a next turn sent back with its reasoning, and every next turn with thinking off.
  • An identical prompt sent again resumes with one token to prefill. Before, it resumed from the longest other entry that is a prefix of it, or from the start.
  • stats["cached"] reports the entry's length. Tests in main that expect whole-prompt entries change for this: tests/cuda/test_qwen27_multi.py (a longer prompt's cached, and the failed prompt-end copy), tests/cuda/test_qwen27_client_gone.py (cached) and tests/test_cuda_failed_admission.py (the entries). The stand-ins in tests/test_cuda_failed_admission.py and tests/test_qwen27_kv_limit.py take keep_at, cut and owned.

Design

References are at main (71377a5, 0.3.6.2). prefill.py, decode.py, engine.py, multi.py and dflash2.py are in src/tensorfold/families/qwen3_5/cuda/; geometry.py, markers.py and kernels/gdn_prefill.cu are in src/tensorfold/cuda/.

The prefill runs in even chunks of up to 4,096 rows and commits the GDN state from the chain kernel (prefill.py:88-94). The state at n - 1 can come from:

  1. A one-row last span. Exact, since any bounds give the same bits, but "a short one costs a whole weight pass" (prefill.py:131). For the 27B's MLX 4-bit checkpoint that is 13,697,187,840 B read once more on every request. prefill_stops keeps message-start states this way.
  2. The chain kernel also writing the state after row W - 2. A CUDA and binding change.
  3. Two launches of the existing chain kernel in the chunk that holds the point (chosen). No kernel change, no extra weight pass, no extra forward.

Option 3 is exact because the chain kernel loads the fp32 state into registers once (gdn_prefill.cu:33-38), steps one row at a time (:39-94) and stores fp32 (:95-98). A launch over rows [cut, W) from the state stored after [0, cut) performs the same operations in the same order as one launch over [0, W), so the output rows and the final state keep their bits. Everything else in the chunk still runs once over all rows.

In prefill.py:

  • prefill_chunk(cut=c) runs each GDN layer's chain as [0, c) then [c, W), joins the two outputs, and also returns the state at p0 + c: the GDN states between the launches, a copy of the last three conv rows of [old rows | QKV rows before the cut], and the chunk's key/value buffers.
  • prefill_state(keep_at=k) keeps the spans unchanged, passes cut to the chunk that strictly holds k, and copies the state when k is a chunk start or the prompt's end. The kept state's conv rows own storage of their own size (_own): a chunk's conv rows are the last three rows of the join [old rows | chunk rows], and .contiguous() on them returns a view that holds the whole join. The kept state then points at the prompt state's final key/value buffers. _grow can reallocate inside the cut chunk (prefill.py:43-53). It copies every committed row, so the kept state's rows are the same bytes. The kept state takes its key/value buffers only after the chunk, so a buffer that a grow replaces is freed at once, as without keep_at.
  • The drafter's taps start window rows before k instead of before n. The drafter absorbs the cut chunk's rows before the point, is snapshotted, then absorbs the rest. At the prompt's end it holds the same rows as before.
  • prefill, prefill_tp and prefill_stops (in decode.py) pass keep_at through, to the span past the last stop, and return a third item. Two ranks add no collective, since the split chains are each rank's own.

An EXL3 pack of the 27B (one GPU) runs the same prefill_chunk and prefill_state and uses the same caches. prefill_chunk picks only its prompt glue from w.fast_prefill (prefill.py:62), and the split chain does not depend on it.

The one-stream engine keeps the entry where main keeps its prompt-end entry, and keeps the prompt state out of the cache, so the decode can commit into it: draft_decode and decode_tp take inplace=True, which commits into the state given instead of a copy. (commit(in_place=True), new in 0.3.6.2, is a different option: the replay writes into a state's tensors.) Otherwise generate would hold the prompt state for the whole reply, one GDN state set more than main, whose entry is that state.

The concurrent decoder keeps the entry in the prefill step that reaches the prompt's end (_step, keep_at). The kept state's GDN states and conv rows are the prefill's own, and no stream decodes into them, so the entry holds them without the copy that kept makes of a stream's state (kept(owned=True)). Its key/value rows are views of the stream's buffers, as main's entries are. A one-token prompt's entry is the stream's own state and is copied, as on main. After each prefill step the drafter keeps no reference of its own to the stream's context (skip(0) after the stream's snapshot, multi.py:158). On main its lists hold the last prefilled stream's prompt-end context until the next prefill step; where a prompt-end entry is kept, that context is also the entry's, and here the entry holds a context of its own. The rounds read and replace a stream's context only through its snapshot (multi.py:273, :307; DFlash2's reference path restores each snapshot first, dflash2.py:339, :495), so no proposal changes.

Exactness

The goal is bit-identical results to main on the prompt's state, last logits and first token, and a kept state equal to a fresh prefill of prompt[:n - 1].

  • Prompt state, logits, first token. Unchanged: the only change in the forward is the split chain, above.
  • Kept state. It is a fresh prefill of the first n - 1 tokens under the existing contract that prefill bits do not depend on chunking (prefill.py:1, :131; tests/cuda/test_qwen27_prefill.py:74, :83, :161, :182). The GDN state is the chain's after row cut - 1, the conv rows are that row's window, and the key/value rows below the point are the rows the chunk wrote.
  • Resumes. A resume from the kept state follows the existing rule: a kept state resumes with a fresh prefill's bits.
  • Drafter. It only proposes, and the target verifies every token.

This is argued from the kernel and checked on the host with CPU stand-ins for the kernels. It has not been checked on a GPU.

Memory and cost

Derived from sizes and code, not measured. Sizes are from the checkpoint's config.json: 48 of 64 layers are GDN, with 48 value heads of 128, 16 key heads of 128 and 3 conv rows; the other 16 have 4 key/value heads of 256.

  • Entries. The number of entries is unchanged. A prompt-end entry now holds the state after prompt[:n-1], so it has n - 1 key/value rows instead of n; a concurrent entry views those rows of its stream's buffers.
  • Key/value buffers. None beyond main's. The kept state takes the final buffers after the cut chunk, so a grow inside that chunk frees the old buffers at once. For a fresh 64,001-token prompt without a limit, the cut chunk grows them from 64,000 rows to 128,000 (the one-stream engine caps them at its admitted window); the old ones are 4,194,304,000 B (65,536 B a row over the 16 attention layers).
  • GDN state sets. The kept state owns one set (153,944,064 B with its conv rows). One stream: one set more than main during the prefill's last chunk. During the decode, the same as main where an entry is kept at the end, and one set fewer where a message start covers the end, since main then holds the prompt state for the whole reply while it decodes into a copy. --parallel N: in the prefill step that ends a prompt, the kept state holds one set beside the stream's from the cut on, and main makes its second set at the step's end by copying the stream's (kept). The step's count at its end is main's and inside (2 * streams + keep + 2) sets (geometry.py:280).
  • A turn that resumes from the n - 1 entry where main misses (one stream; turn 3 of the three-turn conversation): this branch keeps the entry it resumed from, which main drops, so that turn holds one GDN state set more than main in both the prefill and the decode, beyond the set above, and one drafter context more with the drafter: 153,944,064 B per phase, 196,050,944 B with the drafter.
  • Drafter contexts (with a drafter). The prefill can hold one drafter context more: 42,106,880 B for the DFlash2 checkpoint (draft_geometry's size of one context, geometry.py:257-260). From the decode's second round both branches hold the same number of contexts and GDN state sets (with --parallel N, where a message start covers the prompt's end, this branch holds one context fewer: main's drafter lists keep that stream's prompt-end context until the next prefill step); a one-round reply holds one GDN state set and one drafter context more than on main. With one stream, the drafter's admission prices no context for the entries' snapshots (geometry.py:257, engine.py:71-73), on main as here, so the added context is outside it, as those snapshots are.
  • Transient. Joining the two chain outputs holds one more output buffer, one GDN layer at a time: up to 50,331,648 B (4,096 rows × 12,288 B).
  • Per request, on the chunk that holds the point: 48 more chain launches; one copy to join the outputs, 589,824 B a row over all GDN layers (2,415,919,104 B written and read for a 4,096-row chunk); with a drafter, one more tap row and one more add_taps call. No extra pass over the weights.

Evidence

Surface: a host fixture on the public checkpoint's chat template and tokenizer, Vontra/Qwen3.8-27B-MLX-4bit at revision 70ae7fac63274ff2eac54152031433374cb80f2f (the repository's head on 2026-09-28). Prompts are rendered and encoded as the CUDA server does (ChatTemplate, then Tokenizer.encode, cuda/server.py:171-176), and this branch's own lookups (Qwen27Engine._resume, PrefixCache.longest) pick the entry. No model ran.

The conversation: user "What is the capital of France?", assistant "Paris.", user "And of Italy?". Its prompts are too short for a state at a message start.

Case Turn 1 prompt Turn 2 prompt Whole-prompt entry (main) Entry at n - 1 (this change)
Thinking on, reply sent back without reasoning 59 tokens, ends <think> 198 79 tokens, 271 at position 58 no match resumes at 58
Thinking on, reply sent back with reasoning_content 59 tokens, ends <think> 198 89 tokens, extends turn 1 resumes at 59 resumes at 58
Thinking off 19 tokens, ends </think> 271 39 tokens, extends turn 1 resumes at 19 resumes at 18

In the first case turn 2 prefills 79 tokens on main (there is no other entry) and 21 with this change. In the other two, this change prefills one token more.

With the checkpoint's message starts (markers.resume_points) and a long first user message, through the one-stream engine's own bookkeeping (_resume, _stops, _ends): thinking on, replies ("Paris.", then "Rome.") sent back without reasoning.

Turn Prompt main This change
1 601 tokens keeps the state at the last assistant start (596), no prompt-end entry the same
2 621 tokens resumes at 596 (25 to prefill), keeps an entry at 621 resumes at 596 (25 to prefill), keeps an entry at 620
3 642 tokens the entry at 621 does not match; resumes at 596 (46 to prefill) resumes at 620 (22 to prefill)

To reproduce (the weights are not needed):

hf download Vontra/Qwen3.8-27B-MLX-4bit config.json tokenizer.json tokenizer_config.json chat_template.jinja --revision 70ae7fac63274ff2eac54152031433374cb80f2f
python3 -m pytest tests/test_qwen27_prompt_end_template.py -v

Measured effect on a GPU (exactness of each turn and the resumed turn's prefill time on these conversations): GPU run pending.

Tests

Host: macOS, Python 3.13.5, PyTorch 2.11.0 CPU, an import-only Triton stand-in. No kernel ran.

  • tests/test_qwen27_prompt_end_cache_host.py (new, 262 cases):
    • the one-stream engine's entries and resumes with stand-ins for prefill, prefill_tp, draft_decode and decode_tp, including both ranks of two, and beside message starts (the last one 256 tokens or more before the prompt's end, and less);
    • the concurrent decoder on the real prefill_state, private and kept with a stand-in chunk: entries and resumes on one GPU and both ranks of two, prompts filled in steps of STEP rows, message starts, a one-token prompt, and entries that keep their GDN states while their streams decode in place;
    • the concurrent decoder's drafter contexts, with a stand-in drafter that allocates them as DFlash2's fused path does, on one GPU and both ranks of two: at a decode's start and after its first commit every context allocated is an entry's or a decoding stream's, and after the first commit no more rows are allocated than with the whole-prompt entry;
    • prefill_state's spans, cuts and drafter calls with a stand-in chunk;
    • the prefill on row-wise CPU stand-ins for the kernels, which checks the code around the kernels, not the kernels, including message starts with a point past them;
    • prefill_tp itself on the same stand-ins, as one process holding every weight, ranks 0 and 1, against prefill;
    • a fresh prefill with keep_at holds no key/value buffer after a grow replaces it;
    • the kept state's conv rows own storage of three rows a layer, at a cut, a chunk start and the prompt's end, from a fresh prefill and a resumed one.
  • tests/test_qwen27_prompt_end_template.py (new, 5 cases): both conversations above on the checkpoint's own template and tokenizer. It skips unless those files are in the Hugging Face cache.
  • tests/cuda/test_qwen27_prompt_end_cache.py (new, GPU): a toy model with the 27B's layer pattern, with raw-byte comparisons of every GDN state, conv window, key/value row below pos, and the sampled logits:
    • a cut chunk against one launch: cuts at 1 to 4, 31 to 33, 64, 128, 298 and 299 of 300 rows, from 0 and from 137 tokens;
    • keep_at against none: prompts of 1 to 4, 127 to 129, 300, 4,097 and 4,099 tokens, points at chunk starts, inside chunks and at the end; spans of 7 and 64 rows;
    • the next turn (<think>\n then <think>\n\n), a resumed prefill, longer and repeated prompts, each resumed from the kept state against a fresh prefill, greedy and sampled;
    • buffers grown inside the cut chunk (resumes at 1,000 and 2,000 tokens);
    • the drafter's taps against a prefill without keep_at and a prefill of the prefix;
    • inplace decoding;
    • the engine end to end, with and without message starts, against a fresh engine and the serial reference, with every entry against a fresh prefill;
    • the concurrent decoder end to end against the serial reference, and every entry against a fresh prefill after its stream decoded in place: a one-token prompt, and prompts filled in steps of 5 rows, one of them from the point.
Run Result
test_qwen27_prompt_end_cache_host.py on this change 262 passed
test_qwen27_prompt_end_template.py on this change, tokenizer files at the revision above 5 passed (5 skipped without them)
Both files on main's sources collection error: entry_end does not exist
test_qwen27_kv_limit.py and test_cuda_failed_admission.py on this change 20 passed
Whole host suite (tests without tests/cuda), main 136 failed, 2,082 passed, 299 skipped, 18 errors
Same, this change (no tokenizer files in the cache) 136 failed, 2,344 passed, 304 skipped, 18 errors
GPU file, CPU dry run (row-wise kernel stand-ins, dequantising matmul) 85 passed; the 20 tests that decode were deselected, since they need the tree kernels

The same 154 ids fail or error in both whole-suite runs, none in a file this PR adds or changes. Their causes include the import-only Triton stand-in (no triton.backends), no transformers tokenizer, MLX 0.31.1 where GLM-5.3-Flash needs 0.32.2, a memory-window test that expects a Mac with 64 GiB or more (this one has 36 GiB), and files outside the test tree used here (tools/, CHANGELOG.md). The five added skips are the template file.

Twenty-eight one-line breakages of the change were each applied alone. Twenty-six fail the host file, among them a concurrent entry that shares its stream's GDN states, one that copies them, an entry kept where a message start covers the prompt's end, and a concurrent drafter that keeps its own lists after a prefill step. The other two make draft_decode or decode_tp ignore inplace; they change memory only (the decode commits into a copy, so the prompt end's GDN states stay held for the reply). tests/cuda/test_qwen27_prompt_end_cache.py checks draft_decode's inplace on a GPU. No test checks decode_tp's. An entry at the whole prompt also fails the template file.

GPU status

GPU run pending, in this order. A timing counts only after every exactness step before it has passed.

  1. On a GB10: python3 -m pytest tests/cuda/test_qwen27_prompt_end_cache.py tests/cuda/test_qwen27_multi.py tests/cuda/test_qwen27_client_gone.py -q, then python3 -m pytest tests/cuda -q.
  2. The 27B on one GPU through Qwen27Engine, with the drafter, this branch against main:
    • the fixture's two turns (thinking on, reply sent back without reasoning): after each turn's prefill, the committed state's hashes (48 GDN states, 48 conv windows, 16 layers' key/value rows below pos) and the last-row logits' hashes are equal, taken from prefill's return before the decode; the entry at n - 1 (58 tokens) equals main's fresh prefill of the same tokens; turn 2, resumed from it (stats["cached"] 58 here, 0 on main), equals a fresh prefill (state, last logits, first token);
    • the three turns with message starts: the state at 596 and the entry at 620 equal fresh prefills of those tokens; turn 3, resumed from 620 (stats["cached"] 620 here, 596 on main), equals a fresh prefill.
  3. One reply hash per turn, equal to main's and to the serial reference's.
  4. Peak memory, reset before each phase, over each turn's prefill and over its decode, and over the prefill of a fresh 64,001-token prompt (its cut chunk grows the key/value buffers), this branch against main, without and with the drafter, one stream and --parallel 2. Compared in bytes requested by tensors (torch.cuda.memory_stats()["requested_bytes.all.peak"]); allocated bytes (torch.cuda.max_memory_allocated), which count cache blocks rather than tensor sizes, are recorded too. Expected from the code, in requested bytes: the prefill at most 204,275,712 B higher (one GDN state set and the join), plus 42,106,880 B with the drafter; the decode no higher for a reply of two rounds or more. Exception, one stream: a turn that resumes from this branch's n - 1 entry where main misses its prompt-end entry (turn 3 of the three-turn conversation: 620 here, 621 missed on main) also keeps that entry, which main drops, so it holds one GDN state set more in both phases: 153,944,064 B more in each limit, 196,050,944 B with the drafter (one more drafter context).
  5. --parallel 2, two ranks (two GB10s), and an EXL3 pack of the 27B on one GPU (turboderp/Qwen3.8-27B-exl3, 4.00bpw): the same hashes against main; on two ranks, both hold the same entries. Until then, two ranks are covered by host tests only, EXL3 packs by none, and decode_tp(inplace=True) runs in no test.
  6. Prefill time of the resumed turn on this branch against main (stats["prefill_s"], which ends after the first token's copy to the host, cuda/sampling.py:18-28): on the fixture, on turn 3 of the three-turn conversation, and on the fixture with the first user message lengthened so that turn 2 spans more than one 4,096-row chunk. Also the cost on a prompt with no follow-up: the same prompt on both branches, alternating, for a 4,096-row chunk and a short one.

Overlaps

Not in this change

  • Other families. glm5_next, qwen4_exp, nemotron_h (cuda/app.py) and Qwen3.6-35B-A3B (qwen3_5_moe) have their own prefix caches. Qwen3.6 keeps whole-prompt entries by the same rule as the 27B on main (qwen3_5_moe/cuda/engine.py:105-106). They are unchanged here and were not checked for the same one-token miss.
  • preserve_thinking: false. With it, earlier assistant turns render without <think> (chat_template.jinja:116, :119), so neither entry is a prefix of the next prompt.
  • More entries. The counts stay KEEP_ONE and KEEP.

Submitted by an agent from Blockbrain Labs (https://x.com/blockbrain_labs, https://github.com/blockbrain-ai).

…the prompt's end

A chat prompt ends in the generation prompt, <think> and a newline (token
198). When the next request sends that turn back without its reasoning, its
history renders an empty reasoning block, <think> and two newlines (token
271), so the entry kept for the whole prompt differs from the next prompt in
its last token and does not match: the follow-up is prefilled from a shorter
entry or from scratch. Both prefix caches now keep a prompt's entry at
len(prompt) - 1 (engine.entry_end; a one-token prompt keeps its whole
prompt): the one-stream cache (KEEP_ONE entries, one GPU and both ranks of
two) and the concurrent decoder's PrefixCache (KEEP entries). Where a kept
message start less than MIN_GAP before the prompt's end covers it, no entry
is kept at the end, as before. An identical prompt sent again now resumes
with one token to prefill; a prompt that extends the whole last prompt
prefills one token more; stats["cached"] reports the entry's length.

prefill, prefill_tp, prefill_stops and prefill_state take keep_at and also
return the state after prompt[:keep_at] and the drafter's snapshot there
(prefill_stops: a point past its stops). The spans do not change and no
forward is added: the chunk that holds the point runs each GDN chain as two
launches, rows [0, cut) then [cut, W). The chain kernel steps one row at a
time on fp32 state that it loads and stores as fp32, so the two launches
give one launch's output rows and final state; the prompt's own state, last
logits and first token keep their bits. The state between the launches, the
conv rows before the cut and the key/value rows below it are the state a
prefill of the first keep_at tokens commits (prefill bits do not depend on
chunking). The kept state takes the prompt state's key/value buffers after
the last chunk, so a buffer grown past the point is never held twice. Its
conv rows own storage of their own size at a cut (.clone() of the three
rows), at a span start and at the prompt's end (prefill._own): a chunk's
conv rows are the last three rows of its join [old rows | chunk rows], and
.contiguous() on them returns a view that holds the whole join. The
drafter's taps start where its window reaches back from the kept point; it
absorbs the chunk's rows before the cut, is snapshotted, then absorbs the
rest. Two ranks add no collective.

The concurrent decoder keeps the entry in the prefill step that reaches the
prompt's end. Its GDN states and conv rows are the prefill's own, which no
stream decodes into, so the entry holds them as they are (kept(owned=True));
a one-token prompt's entry is the stream's own state and is copied, as
before.

Tests: tests/cuda/test_qwen27_prompt_end_cache.py (a cut chunk against one
launch; keep_at against none, one and several spans; the kept state
against a fresh prefill of the prefix; the next turn, a resumed prefill,
longer and repeated prompts resumed against fresh prefills, greedy and
sampled; buffers grown inside the cut chunk; the drafter's taps; the
engine with and without message starts and the concurrent decoder end to
end against the serial reference, with every entry against a fresh
prefill after its stream decoded), tests/test_qwen27_prompt_end_cache_host.py
(both caches' entries and resumes, both ranks of two, beside message
starts; the concurrent decoder on prefill_state with a stand-in chunk,
steps of STEP rows, and entries no stream decodes into; prefill_state's
spans, cuts and drafter calls with a stand-in chunk; the prefill on row-wise
CPU stand-ins for the kernels, with stops and a point past them, and the
kept state's conv rows in storage of three rows a layer). Entries one token
shorter in tests/cuda/test_qwen27_multi.py, tests/cuda/test_qwen27_client_gone.py
and tests/test_cuda_failed_admission.py; the stand-ins in
tests/test_cuda_failed_admission.py and tests/test_qwen27_kv_limit.py take
keep_at, cut and owned. Not yet run on a GPU.
…e, so the prompt end's GDN states are freed

With the cache entry one token before the prompt's end, no entry holds the
prompt state that prefill returns, but generate and _generate_tp kept it in
a local while draft_decode and decode_tp committed into a clone: its GDN
states and conv rows (153,944,064 B for the 27B on one GPU) stayed alive
for the whole reply, one set more than main holds, where that state is the
prompt's entry. draft_decode and decode_tp take inplace=True to commit into
the state they are given; the engine passes it on both ranks, and the first
commit frees the prompt end's states. Default calls still commit into a
copy.

Tests: the engine hands the decode a state no entry holds, with inplace
(host, one GPU and both ranks of two); an inplace decode gives the same
tokens and moves the state it was given (tests/cuda). Not yet run on a GPU.
…o tensors

Two host checks compared a state with one holding the same tensors, so they
could not fail: a prefill with keep_at and its reference resumed from one
prefix, whose key/value buffers they share, and the same prompt's kept state
resumed with nothing to prefill, which holds the kept state's tensors. Each
run now resumes its own prefix, and the second kept state is compared with a
fresh prefill of the prompt's first n - 1 tokens.
prefill_tp's keep_at ran in no test: the host tests replace prefill_tp with a
stand-in, and the CUDA file has no two-rank case. The new test runs the real
prefill_tp on the row-wise CPU stand-ins, on one process holding every weight
(rank sum and share are the identity), for rank 0 and rank 1, and compares the
prompt state, first token and kept state with prefill's.
…chat template and tokenizer

Renders chats as the CUDA server does (ChatTemplate, then Tokenizer.encode) with the checkpoint's
tokenizer files, and checks what the one-stream engine and PrefixCache resume the next turn from:

- reply sent back without its reasoning: turn 2 agrees with turn 1's prompt on every token but the last
  (198 against 271); an entry for the whole prompt does not match, the entry at entry_end does; the
  prompt is too short for a state at a message start;
- reasoning sent back, or thinking off: turn 2 extends all of turn 1's prompt; both entries match and the
  entry at entry_end resumes one token earlier;
- with the checkpoint's message starts (markers.resume_points): after a long first turn, whose state is
  kept at its last assistant start, a short second turn keeps a prompt entry; turn 3 resumes from turn 2's
  entry at entry_end, where an entry for the whole prompt misses and turn 3 resumes at turn 1's start.

Skips unless the tokenizer files are in the Hugging Face cache; the weights are not read.
…ack without its reasoning

With the reasoning sent back, or thinking off, the next turn extends the whole prompt. The docstrings and the
README now say which case differs in the last token. Comments only.
…grow replaces

A fresh prefill frees each key/value buffer as soon as a grow replaces it,
with or without keep_at: the state at the cut, and a state kept at a chunk
start, take their key/value buffers only after the chunk. The test tracks
every buffer a grow replaces in a fresh 1,030-token prefill on the row-wise
CPU stand-ins and checks that none is still allocated when the next
attention runs, with the point at the prompt's end and at the last span's
start, over one span and over spans of 64 rows.
… after a prefill step

MultiDecoder._step now empties the drafter's own per-layer lists after
taking the stream's snapshot (drafter.skip(0)). The rounds read and
replace a stream's context only through its snapshot: launch_blocks and
add_taps_streams on the fused path, and the reference path restores each
snapshot first. The lists held the stream's prompt-end context until the
next prefill step restored another. With the prompt-end entry at
len(prompt) - 1, which holds a context of its own, that was one drafter
context more for the rest of the decode (up to 2,047 rows of 20,480 B
for the DFlash2 checkpoint). Now the stream's first commit frees it, and
from then on the decode holds no more drafter contexts than on main.

skip(0) replaces the lists with empty ones, sets context_len to 0 and
leaves context_end; every later read of the drafter's own state restores
a snapshot first, so no draft changes. Both ranks of a two-rank drafter
run the same step.

Host test, with a stand-in drafter that allocates contexts as DFlash2's
fused path does, on one GPU and both ranks of two: at each decode's start
and after its first commit, every context allocated is an entry's or a
decoding stream's; after the first commit no more rows are allocated
than with the whole-prompt entry; before it, at most the entry's own
context more.
ashhart added a commit that referenced this pull request Sep 29, 2026
…d CUDA

- #65's prompt-end entry follows kept message starts, and the decoder's entries view their rows; the 27B's tests
  expect entries one token early.
- Ternary Bonsai 2 27B (prism-ml's 2-bit pack) as a lane family: Prism rotations, 2-bit lanes, exact widening before
  M5, with Qwen3.8-27B's DFlash2 drafts. Recipe: docs/recipes/ternary-bonsai-2.md.
- --vision: up to four images a request (data URLs, or HTTPS links with --vision-urls) on the lane engine, MLX and
  CUDA. Image replies keep drafting and equal "draft": false ones; an image prompt keeps no prompt-end entry.
- The --vision checks and options move to serve_options.py.

Fixes #18, fixes #81.
@ashhart

ashhart commented Sep 29, 2026

Copy link
Copy Markdown
Owner

Your prompt-end entry is in 0.3.6.3 (0768f8d9, under your name). The 27B keeps its cache entry one token before the
prompt's end, so the next chat turn resumes from it instead of prefilling the whole conversation again. We fitted it
around the message-start entries and image prompts (images keep no entry). On a Spark, 16 concurrent streams ran at
158.7 tok/s with all 48 replies equal to their solo runs. Thanks for the whole set of four, and for #57-#59 before
them.

@ashhart ashhart closed this Sep 29, 2026
BlivionIaG referenced this pull request in BlivionIaG/TensorFold Oct 20, 2026
…d CUDA

- #65's prompt-end entry follows kept message starts, and the decoder's entries view their rows; the 27B's tests
  expect entries one token early.
- Ternary Bonsai 2 27B (prism-ml's 2-bit pack) as a lane family: Prism rotations, 2-bit lanes, exact widening before
  M5, with Qwen3.8-27B's DFlash2 drafts. Recipe: docs/recipes/ternary-bonsai-2.md.
- --vision: up to four images a request (data URLs, or HTTPS links with --vision-urls) on the lane engine, MLX and
  CUDA. Image replies keep drafting and equal "draft": false ones; an image prompt keeps no prompt-end entry.
- The --vision checks and options move to serve_options.py.

Fixes #18, fixes #81.
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