Skip to content

Rewind a diverging session to the longest common prefix - #296

Open
stratika wants to merge 2 commits into
mainfrom
fix/session-rewind-common-prefix
Open

stratika wants to merge 2 commits into
mainfrom
fix/session-rewind-common-prefix

Conversation

@stratika

@stratika stratika commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

A chat session with a reasoning model (Qwen3, Gemma 4) re-encodes the whole conversation on every turn, so each turn's prefill grows with the length of the chat.

DelegatingSession reuses its key/value cache only when everything it holds is an exact prefix of the new request; any difference resets the cache and encodes everything again. A reasoning model's cache holds the <think> block it generated, but the chat template drops reasoning from the history a client sends back. So the second request always differs from the cache at the previous answer, and every turn after the first starts from zero.

Working out where to rewind also showed that the existing continuation was wrong in two cases:

  • The two loop families disagree on what a continuation feeds. Llama, Mistral, Phi-3, Granite and every GPU prefill/decode loop feed the seed token at the start position and the prompt after it. The Qwen 3-style loops (Qwen2/3, Gemma 4, DeepSeek2, LFM2, gpt-oss) never feed the seed after position 0. On the seed-first loops, a session continued with whatever seed the loop left behind:

    • after a stop token, that token was fed twice;
    • after the token budget ran out, the last slot was never written.

    Either way, the next turn's first logits moved by up to 1.1. The prompt-only loops had the same unwritten slot after a budget cut.

  • dropReasoningFromHistory rewound the position but kept that stale seed, so a seed-first loop wrote the last reasoning token ahead of the answer.

Also, the host batched prefill fed the last prompt token twice when firstIndex() == 1; the GPU path had already been fixed for this. On Llama-3.2-1B Q8_0 at batch 4, the first logits moved by 9.2 and the greedy token changed.

To reproduce: run a multi-turn chat on one session, sending each answer back without its reasoning as a chat client does, and compare the prompt tokens each turn feeds (GenerationResult.promptTokens()) with a fresh session's. On main, Qwen3-0.6B Q8_0 at greedy:

turn 1: fed 14 of 14 prompt tokens
turn 2: fed 33 of 33 prompt tokens
turn 3: fed 57 of 57 prompt tokens
turn 4: fed 77 of 77 prompt tokens
total: fed 181 of 181 prompt tokens

Fix

  • ContinuationFeed (new): each generation loop records on the State which convention it follows, SEED_THEN_PROMPT or PROMPT_ONLY.

  • DelegatingSession: for a family whose state is purely positional and has a recorded convention, the session keeps the longest common encoded prefix common of the cache and the request. It always rewinds to R = common - 1 and writes full[R] into slot R again:

    • on a seed-first loop, full[R] is fed as the seed;
    • on a prompt-only loop, it is the prompt's first token.

    Rewriting R recomputes the identical entry when that slot was already written, and supplies the missing write when it wasn't, which fixes the stop-token and budget-cut cases above. Recurrent families, and states without a recorded convention, keep the exact-prefix-or-reset behaviour.

  • dropReasoningFromHistory reseeds with the right token.

  • TokenGenerationLoop:

    • the host batched prefill feeds the last prompt token once;
    • the loops record their ContinuationFeed.
  • EncodedPrefix.commonPrefixLength(full): the length of the prefix the cache and the request share. A turn's promptTokens() is what it actually fed, which the measurements below use.

  • Formatting of the touched files, with the project's Spotless settings.

Testing

Unit tests: ./mvnw -Pjdk22plus test gives 980 tests and 0 failures.

New accel tests (-Pjdk22plus,accel-tests, Apple M4 Pro, all 10 pass). They compare exact CPU logits and tokens.

  • ContinuationPlacementAccelTest:
    • llamaFeedsTheSeedFirstAndTheRewoundShapeIsExact and qwen3FeedsThePromptOnlyAndTheRewoundShapeIsExact: a rewound continuation produces the same logits as encoding the whole prompt, for each convention.
    • theHostBatchedPrefillFeedsTheLastPromptTokenOnce.
  • ConversationAccelTest:
    • a reused prefix answers as a fresh session does;
    • divergence answers the conversation that was sent;
    • an edited last turn rewinds to the common prefix;
    • a reasoning answer replayed without its thinking rewinds and answers like a fresh session;
    • reset and event-count checks.

End to end with the reproduction above, using main's and this branch's jars, at greedy with a fixed seed:

Model, device main: prompt tokens fed over 4 turns This PR Answers equal a fresh session's
Qwen3-0.6B Q8_0, CPU 181 of 181 (14 / 33 / 57 / 77) 77 of 181 (14 / 19 / 24 / 20) yes, every turn, both builds
Qwen3-0.6B Q8_0, GPU (Metal) 181 of 181 77 of 181 yes
Llama-3.2-1B Q8_0, GPU (Metal) 69 of 183 (already reused: no reasoning) 69 of 183 yes

Not covered

  • I ran it on Metal and the CPU only, not on CUDA.
  • Gemma 4, DeepSeek2, LFM2 and gpt-oss follow the prompt-only convention, but only Qwen3 was run end to end.

DelegatingSession reused the key/value cache only when everything it
retained was an exact prefix of the new request; any divergence reset and
re-encoded the whole conversation. A reasoning model (Qwen3, Gemma 4)
always diverges, because its cache holds the <think> block that the chat
template drops from history, so every turn after the first re-encoded
everything.

A family whose state is purely positional now keeps the longest common
encoded prefix. Doing that correctly needed the seed placement worked out,
and measuring it on exact CPU logits found that the existing continuation
was wrong on its own:

- The loops disagree on what a continuation (startPosition > 0) feeds.
  Llama, Mistral, Phi3, Granite and every GPU prefill/decode loop feed
  the seed at S and the prompt from S+1. The Qwen 3 loops (Qwen2/3,
  Gemma 4, DeepSeek2, LFM2, gpt-oss) never feed the seed after position 0.
  Each loop now records its convention on the State (ContinuationFeed).
- On the seed-first loops the session continued at its position with the
  seed the loop left behind, which is the last sampled token. After a
  stop that token was fed twice; after a budget cut, slot P-1 was never
  written. The first answer logits of the next turn moved by up to 1.1.
  The prompt-only loops had the same unwritten slot after a budget cut.
- dropReasoningFromHistory rewound position but kept that stale seed, so
  a seed-first loop wrote the last reasoning token ahead of the answer.

The session now always rewinds to R = common - 1 and writes full[R] into
slot R again. On a seed-first loop full[R] is the reseeded token; on a
prompt-only loop it is the prompt's first token. Rewriting R recomputes
an identical entry when the slot was already written, and supplies the
missing write when it was not. Recurrent families, and states with no
recorded convention, keep the exact-prefix-or-reset behaviour.

Also fixes the host batched prefill, which with firstIndex()==1 fed the
last prompt token twice. That is the same defect generateWithPrefill
already fixed on the GPU. On Llama-3.2-1B Q8_0 at batch 4 the first
logits moved by 9.2 and the greedy token changed.

Qwen3-0.6B Q8_0 on CPU, a 6-turn chat at greedy with answers replayed
without reasoning, gave identical answers before and after:
  prompt tokens fed per turn  before 15/44/98/156/218/332 (863)
                              after  15/29/54/58/62/114   (332)
  turn-6 prefill              7.04 s -> 2.71 s

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.

1 participant