Skip to content

Fix server prompt cache reuse with speculative decoding - #2104

Closed
cassieliang6709 wants to merge 1 commit into
ml-explore:mainfrom
cassieliang6709:fix-spec-decode-prompt-cache
Closed

cassieliang6709 wants to merge 1 commit into
ml-explore:mainfrom
cassieliang6709:fix-spec-decode-prompt-cache

Conversation

@cassieliang6709

Copy link
Copy Markdown
  1. Symptom

    • With --draft-model, sending the same request twice gives a correct answer the first time. The second time, the model echoes the input back, starting with user\n.
    • Repro models: Qwen3-4B-Instruct-2507-4bit as the main model, Qwen3-0.6B-4bit as the draft model.
  2. Cause

    • When LRUPromptCache.fetch_nearest_cache reuses a cache, it trims len(key) - prefix tokens. This assumes the cache has one entry per token in the key.
    • After speculative decoding, the last generated token is never added to the cache. In my test the cache had 336 entries and the key had 337 tokens, so reuse trims one token too many.
    • The token that gets cut is the one before assistant, so the model thinks a new user turn has started.
  3. Fix

    • In server.py, before saving the cache, trim every layer to the length of the shortest layer, and cut the key to the same length.
    • Only the draft-model path is affected.
  4. Tests

    • Added TestAlignCacheToTokens (2 tests).
    • All 70 tests in tests/test_server.py and tests/test_prompt_cache.py pass.
    • On an M1 Pro, 8 prompts give the same output with and without the draft model, and the repeated request above is now correct.

LRUPromptCache trims a reused cache by len(key) - prefix, so it assumes
the cache holds one entry per token in its key. After speculative
decoding the last yielded token is never fed back, and the draft cache
can lag the main cache, so the cache is shorter than the key.

The next request that shares a prefix then gets a cache trimmed one
token too far, and the model sees a prompt with a token missing. With
Qwen3 this drops the token before "assistant", so the model answers as
if a new user turn started and echoes the input.

Before inserting the cache, trim every layer to the shortest cache and
cut the key to the same length. Only the draft-model path changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cassieliang6709

Copy link
Copy Markdown
Author

Closing as a duplicate of #2083, which fixes the same bug and was opened earlier. It aligns the caches inside speculative_generate_step, so it also covers EOS and early-disconnect exits and callers outside the server.

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