Skip to content

feat(prefix cache): save the history before the last user turn when prompts fork there - #1056

Open
mitar wants to merge 2 commits into
ROCm:mainfrom
mitar:cache-context
Open

mitar wants to merge 2 commits into
ROCm:mainfrom
mitar:cache-context

Conversation

@mitar

@mitar mitar commented Nov 16, 2026 •

Copy link
Copy Markdown

Related to #737: this covers requests which share their earlier messages (few-shot example pairs, a document in an earlier message) and differ in the last one. A shared part and a payload inside one user message are not covered.

Why

Prompts which share everything but their last user turn, like the same few-shot examples followed by different inputs, or the same document followed by different questions, reuse only the system prompt + tools snapshot today. The end snapshot of one prompt does not cover the next one, and the boundary snapshot ends before the first user turn, so every such prompt reads the whole shared history again. With about 6.5K tokens of few-shot examples that is 26-31 s of prefill per request on qwen3.6-moe:35b-a3b and 63 s on qwen3.8-mtp:27b.

What

  • _prefix_insert finds the last user-turn marker as well as the first. In the Qwen templates tool results are a user turn too.
  • When the prompt before this one shared everything up to that marker and went on differently (new PrefixSlotCache::forked(), against the prompt set_last_prompt() remembers), it prefills up to the marker in a pass of its own and saves a boundary slot there, as it does for the system prompt + tools.
    • As a boundary slot it is evicted after the end slots. end_kv_from prefers it, so the end slots saved after it hold only the rows past it and keep it as their head. A head with pictures in it is never shared this way: resume() matches the rows before kv_from by tokens only, so such an end slot keeps its rows from the system prompt slot on, or all of them.
    • It is saved only when it is at least min_boundary (512) tokens into the prompt, adds at least --prefix-min-gain tokens over the system prompt + tools slot and over the slot the prompt resumed from, and its slot is kept (fits(): the cache is on and the slot alone is within --prefix-cache-mb). The system prompt pass runs under the same fits() check.
  • The marker scan and these guards are in PrefixSlotCache (find_user_turns(), plan_heads(), end_kv_from() over both heads), called by _prefix_insert and by the test.
  • A chat turn only continues the prompt before it, so it is no fork and saves nothing more. forget_all() clears the remembered prompt.
  • qwen3.8-mtp and qwen3.8-dflash2 (boundary_only) save this slot too. They keep no end slots, so for them it is the only way to reuse a shared history.
  • Docs: prefix_cache.md (how it works, that a prompt is compared only with the prompt just before it, that many different histories leave fewer slots for replies, the Qwen3.8 limit) and the Qwen3.8 model card.

Why only when prompts fork

A chat never resumes from the start of its last user turn: its next turn continues from the end slot. Saving the history there would cost every chat turn a prefill pass of its own up to the marker, and a boundary slot per turn, which is evicted last and so would push out the end slots of other conversations. Waiting for the second prompt which forks at the same place costs one more full read for few-shot workloads and nothing for chats.

Testing

  • test_prefix_slot_cache (as cpu-tests.yml runs it): new test_shared_history (the history slot is saved from the second prompt on, the later prompts resume there, and it outlives the evicted end slots), test_chat_saves_no_history (a chat turn saves nothing before its last user turn, a fork from the same history does), test_find_user_turns, test_forked, test_plan_heads, test_head_not_kept_not_split and test_history_with_pictures (the same tokens with another picture never resume on the first picture's rows). The prefill helper calls the same PrefixSlotCache methods as _prefix_insert. All pass, also merged with current main.
  • Linux build of v1.0.14 with this change as a .deb on Ubuntu 26.04 (GCC 15), no warnings from the changed files.
  • NPU: Ryzen AI 9 HX 370, Ubuntu 26.04, kernel 7.0, amdxdna 0.7, NPU firmware 1.1.2.64.
  • Pictures, qwen3.5:9b on the NPU: a red picture's history slot, then the same text with a blue picture of the same size, an unrelated request, and the question which colour the picture is. Before the fix the blue picture's end slot was saved on the red picture's history slot and the answer was "Red."; with it the end slot is self-contained and the answer is "Blue.", as from a cold run.

qwen3.6-moe:35b-a3b, v1.0.13 against this branch, flm serve --ctx-len 16384. A 266-character system prompt (below 512 tokens, so no system prompt slot in either build) and 9 few-shot example pairs, followed by one input as the last user message, greedy, 32 tokens per answer. Prefill time:

Request v1.0.13 This PR
1. examples + input A (6956 tokens) 31.3 s 26.8 s
2. examples + input B (6622 tokens) 27.0 s 28.1 s, saves the history (6555 tokens)
3. examples + input C (6601 tokens) 26.2 s 2.5 s, 6555 cached
4. examples + input D (7023 tokens) 26.7 s 4.8 s, 6555 cached, end slot from row 6555
5. request 4 + its answer + a new user message (chat turn, 7427 tokens) 5.1 s, 7023 cached 4.8 s, 7023 cached, no history slot saved
6. examples + input E (6660 tokens) 28.3 s 3.2 s, 6555 cached

Request 1 differs by 4.5 s between the builds with the same prompt (other work loaded the CPU during the runs), so the cost of the extra pass in request 2 is within the noise of this run.

The same examples with a 676-token system prompt save both heads, the second request resuming at the system prompt and saving the history, the third resuming at the history:

[FLM]  Prefix cache: saved slot 1 (boundary, 676 tokens, from row 0, 74 MiB)
[FLM]  Prefix cache: saved slot 2 (end, 7572 tokens, from row 676, 196 MiB)
[FLM]  Prefix cache: resuming at 676 of 7238 tokens, from slot 1 (boundary, 2 saved)
[FLM]  Prefix cache: saved slot 3 (boundary, 7171 tokens, from row 0, 201 MiB)
[FLM]  Prefix cache: not saved, only 67 tokens past slot 3 (needs 128, --prefix-min-gain)
[FLM]  Prefix cache: resuming at 7171 of 7217 tokens, from slot 3 (boundary, 3 saved)
[FLM]  Request done: prompt 7217 tokens (7171 cached) (prefill 2.581 s, 17.82 tok/s), generated 32 tokens (decode 2.134 s, 15.00 tok/s), kv 7252/16384, finish length

qwen3.8-mtp:27b, v1.0.13 with this change applied (the same code), --ctx-len 16377, a sustained run of 19 requests with the same examples (about 6.6K tokens), each with a json_schema response format: the first two requests read everything in 63.4 and 63.3 s, the second one saving the history (6591 tokens). The other 17 resumed there and read the rest in 4.0-6.0 s:

[FLM]  Prefix cache: saved slot 1 (boundary, 6591 tokens, from row 0, 692 MiB)
[FLM]  Prefix cache: resuming at 6591 of 6637 tokens, from slot 1 (boundary, 1 saved)
[FLM]  Request done: prompt 6641 tokens (6591 cached) (prefill 4.035 s, 12.39 tok/s), generated 100 tokens (decode 17.293 s, 5.78 tok/s), kv 6740/16377, finish stop

Notes

  • The first two prompts which share a history read all of it. The third one is the first to resume.
  • Only the prompt just before is compared, so a side call between two few-shot prompts, or two alternating sets of examples, saves no history slot.
  • On the Qwen3.8 models a conversation which continues through the single checkpoint does not pass through _prefix_insert, so it does not update the remembered prompt. At worst one more prompt reads everything.
  • I tested on the NPU with qwen3.6-moe:35b-a3b and qwen3.8-mtp:27b only. The change applies to every model which uses _prefix_insert, each with its own user-turn marker. Models with a sliding window or a convolution state resume a slot only when the prompt starts with all of it, which is the case for the history slot.

…rompts fork there

Prompts which share everything but their last user turn, like the same few-shot examples followed by different
inputs or the same document followed by different questions, reused only the system prompt + tools snapshot: the
end snapshot of one prompt does not cover the next one, and the boundary snapshot ends before the first user turn.
Every such prompt read the whole shared history again.

_prefix_insert now finds the last user-turn marker as well as the first. When the prompt before this one shared
everything up to it and went on differently (PrefixSlotCache::forked, against the prompt set_last_prompt
remembered), it prefills up to the marker in a pass of its own and saves a boundary slot there, as it does for the
system prompt + tools. As a boundary slot it is evicted after the end slots, and end_kv_from prefers it, so the end
slots saved after it hold only the rows past it and keep it as their head. It is saved only when it is at least
min_boundary tokens into the prompt and adds at least --prefix-min-gain tokens over the system prompt + tools slot
and over what the prompt resumed from. forget_all clears the remembered prompt.

A chat turn only continues the prompt before it, so it is no fork and saves nothing more: the extra prefill pass
has a cost of its own whatever its length, and saving the history on every request made chat turns 2-4 on
qwen3.6-moe about 3 s slower each. The first two prompts which share a history therefore read all of it, the later
ones resume there.

qwen3.8-mtp and qwen3.8-dflash2 save only boundary slots, so they save this one too.

Test: test_shared_history and test_chat_saves_no_history in the prefix_slot_cache test; its prefill helper follows
the new _prefix_insert.

Docs: prefix_cache.md (how it works, the Qwen3.8 limit) and the Qwen3.8 model card.
@tawei-amd
tawei-amd requested a review from zaneni6 November 23, 2026 22:59
@tawei-amd

Copy link
Copy Markdown
Collaborator

Nice change: the numbers show a real win for few-shot / shared-document workloads, and gating the save on a detected fork so chat turns pay nothing is the right call. I read the diff statically (no build or run on my side); a few points before merge:

Worth checking

  1. VL models / image hashes. end_kv_from(full_tokens, history) matches the history slot by token prefix and size. In VL models (qwen3vl, qwen3.5, minicpm) earlier turns often hold images, and two different images give identical placeholder tokens. Can a same-length slot with a different image's rows be picked as kv_from? If so, a resumed end slot would mix K/V rows from two images. Only qwen3.6-moe and qwen3.8-mtp were run, so this path is untested. Comparing image_hashes (or skipping kv_from when the slot has images) would close it.
  2. Wasted pass when the slot isn't kept. The extra history prefill runs before we know save() will keep the slot. With a small --prefix-cache-mb or --prefix-slots 1/2 on qwen3.8 (~60 s pass), every forking request could pay it and store nothing, and the "too big" warning prints once. Could we check that the slot fits before prefilling?

Smaller points
3. History slots are boundary slots with no cap, so many distinct histories (branching agents, regenerate/edit) can evict the system+tools slot and other conversations' end slots. A cap or a note in the docs would help.
4. last_prompt_ is not reset by clear_live() / cold start after a cancel or failure, and image prompts also overwrite it. Probably worth resetting in those paths.
5. The history slot is saved with kv_from=0, so rows 0..boundary are stored twice when a boundary slot exists. kv_from=boundary would save memory.
6. test_prefix_slot_cache's prefill helper re-implements _prefix_insert, so the real marker scan and guards aren't covered. Even a small forked() unit test (equal prompt, prefix of last, shorter than last) would help.
7. Docs: please state that the fork is only detected against the immediately preceding prompt (as in the PR Notes), and that min_boundary (512) is configurable rather than a fixed number.

… head pass for a slot not kept

An end slot keeps the rows of a head with pictures in it itself. resume() puts the rows before kv_from back from the
engine's live context or from a self-contained slot with the same tokens, and matches both by tokens only, so the same
tokens with another picture of the same size would put that picture's rows under the end slot. A history slot holds
pictures when they were inside the part a prompt resumed from, like a chat with a picture whose later message is
edited.

A head is prefilled in a pass of its own only when its slot is kept (fits()). save() makes room for a self-contained
slot by evicting any other one, so it refuses such a slot only when the cache is off or the slot alone is bigger than
--prefix-cache-mb, which fits() checks and warns about once.

The marker scan and the guards are in PrefixSlotCache (find_user_turns, plan_heads, end_kv_from over both heads), and
_prefix_insert and the test's prefill helper both call them. forked() notes that it never selects rows, and that an
earlier turn sent again is a fork.

Test: test_find_user_turns, test_forked, test_plan_heads, test_head_not_kept_not_split and test_history_with_pictures
in the prefix_slot_cache test.

Docs: a prompt is compared only with the prompt just before it; a history is kept over every reply, so many different
histories leave fewer slots for replies.
@mitar

mitar commented Nov 25, 2026

Copy link
Copy Markdown
Author

Thanks for the careful read. The new commit addresses 1, 2, 6 and 7, and 3 with a note in the docs; for 4 and 5 I explain below why I would keep them as they are.

  1. Yes, this can happen. Fixed.

  2. The history pass reads nothing twice: _prefix_insert splits the same prefill at the history, so the extra cost is one more pass, not a second read of 60 s. In the PR's table request 2, which saves the history, is within the noise of v1.0.13 (28.1 s vs 27.0 s), and on qwen3.8-mtp the first two requests read in 63.4 and 63.3 s, the second one saving the history. The commit message gives about 3 s per pass on qwen3.6-moe, so it is not free either. save() makes room for a self-contained slot by evicting any other one (a slot with kv_from > 0 is never a parent, so there is always a slot without dependents to evict), so it refuses such a slot only when the cache is off or the slot alone is bigger than --prefix-cache-mb. The new fits() checks exactly that, and a head is prefilled in a pass of its own only when fits() says its slot is kept. fits() prints the same one-time warning as save(). The system prompt pass had the same property and uses the same check now. On the NPU with --prefix-cache-mb 150 (below every snapshot of these prompts on qwen3.6-moe), nothing is saved, the warning is printed once, and the forking request reads in 27.0 s like the others. With --prefix-slots 1, the second request resumes at the system prompt slot and replaces it with the history slot, and the third resumes at the history (2.5 s).

  3. I kept the history slot a boundary slot, so one eviction rule holds for every model: end slots go first, then the shared heads (system prompt and history slots) that nothing depends on, each least recently used first. The docs now say that a history is kept over every reply, so a workload with many different histories (edited messages, agents which branch) leaves fewer slots for replies, and to raise --prefix-slots (and --prefix-cache-mb) for it.

  4. last_prompt_ only decides whether a head is worth a prefill pass of its own; it never selects which rows a prompt reuses (the history slot always holds the current prompt's own rows). A stale value therefore costs at most one pass or one save which does not happen. It is set only after a prompt was prefilled completely, so after a cancel or a failure it still holds the last complete prompt, and a retry of a cancelled fork still saves the history. Resetting it there would lose that. An image prompt is the prompt before the next one like any other: the next prompt is compared with it, and an image prompt with pictures still to read is not split anyway. forked() now has a note that it never selects rows.

  5. Saving the history from kv_from = boundary would make it depend on the system prompt slot, and the end slots after it on the history slot. Every parent lookup (end_kv_from, the ancestor search in resume(), the dependents rule in eviction) requires a self-contained parent, so this needs chained restores: two state_write_kv calls in order, and eviction which follows two levels. The saving is the system prompt's rows only. On qwen3.6-moe a saved row costs 20 KiB (from the server log), so in the PR's example with a 676-token system prompt that is 13 MiB of the 201 MiB history slot (about 7%). I would keep it self-contained; a self-contained history slot also stays usable when the system prompt slot is evicted.

  6. The marker scan and every guard are now in PrefixSlotCache.

  7. The docs now say that a prompt is compared only with the prompt just before it, with the cases where no history is saved (a request in between, two sets of examples used in turn). min_boundary has no option: configure() accepts only --prefix-cache-mb, --prefix-slots and --prefix-min-gain, and only a test changes the member, so for users it is 512, as the docs say.

test_prefix_slot_cache passes on the branch and on the branch merged with current main, and v1.0.14 with this change builds as a Linux .deb on Ubuntu 26.04 (GCC 15) with no warnings from the changed files, its test_prefix_slot_cache passing. On the NPU (Ryzen AI 9 HX 370) v1.0.14 with this change behaves as the PR's table says: on qwen3.6-moe:35b-a3b the same slots are saved and resumed for every request as with the first commit, with prefill 27.9 / 27.4 / 2.4 / 4.7 / 4.8 / 3.1 s, both heads are saved with the 676-token system prompt, and on qwen3.8-mtp:27b the second request saves the history (6591 tokens) and the third, fourth and sixth resume there (3.7-5.5 s instead of 62 s). The picture case above ran on qwen3.5:9b; the build before the fix was v1.0.13 with the first commit.

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