Skip to content

Clamp prompt-cache keys to the KV they describe - #2083

Open
turingH wants to merge 2 commits into
ml-explore:mainfrom
turingH:fix/spec-prompt-cache-key-kv-misalignment
Open

turingH wants to merge 2 commits into
ml-explore:mainfrom
turingH:fix/spec-prompt-cache-key-kv-misalignment

Conversation

@turingH

@turingH turingH commented Nov 20, 2026

Copy link
Copy Markdown

Summary

With --draft-model, speculative decoding can stop after yielding one token
that never went through the target model's forward pass. The server still
appends that token to the prompt-cache key, so the stored key is one token
longer than the KV. On reuse, fetch_nearest_cache sizes the trim from the
key and drops an already-processed token from the victim's context. The
victim then attends to the wrong sequence; greedy output changes.

How the key ends up longer than the KV

Each round the target reads 1 + k tokens (carry-over plus k drafts) and
emits k + 1 candidates: the k verify slots plus one extra sample past
the drafts. That extra token only enters the target at the next round's
start. When generation stops on it, there is no next round:

prompt                 [7, 3, 4, 1]
drafts this round      [8, 9]
fed into the target    [1, 8, 9]        KV for all 3
emitted                [8, 9, 2]        "2" never got KV
target KV              7 3 4 1 8 9

If every draft is accepted, one round emits num_draft_tokens + 1 tokens,
so this hits whenever:

max_tokens % (num_draft_tokens + 1) == 0

Default server flags do that: --max-tokens 512, --num-draft-tokens 3,
512 % 4 == 0. Per-request max_tokens / max_completion_tokens and
num_draft_tokens work too. Earlier rounds' extras are consumed next round,
so a single generation can leave at most a gap of 1.

In speculative_generate_step (mlx_lm/generate.py), the verify loop yields
accepted drafts; the extra token is yielded after it (generate.py:655). _step
only runs model(y, cache=cache) on the fed y, so the last sample is not
in KV. When ntoks == max_tokens the function breaks before the line that
would carry that token into the next round.

Trim trusts the key, not KV length

At generation end the server appends every emitted token — including the
unread one — to the key and stores the pair (server.py:1142, 1155):

stored key = [7, 3, 4, 1, 8, 9, 2]   len 7
stored KV  =  7  3  4  1  8  9        len 6

On fork, the longer branch of fetch_nearest_cache computes trim from key
length, without checking KV offset (cache.py:1663-1666):

next request            [7, 3, 4, 1, 8, 9, 5]
prefix                  = 6
num_to_trim             = 7 - 6 = 1
effective KV            = 6 - 1 = 5
returned KV             7 3 4 1 8
tokens to process       [5]

Token 9 is gone: not in effective KV and not in tokens to process.

user input              7  3  4  1  8  9  5
what the model reads    7  3  4  1  8     5

trim lowers the copy's offset from 6 to 5; slot 5 still holds 9's
vectors until token 5 overwrites them. Positions follow offset, so 5
lands at position 5 instead of 6 and everything after shifts left.

The corrupted run inserts a new pair (the forked entry is a deepcopy and
stays as-is): the new key has the user's ids at position 5 (9), but slot 5
already holds 5's KV. Later forks see key/KV disagree from that slot. The
stored gap goes 1 → 2 for this request then stays at 2 until eviction.

Draft proposals are irrelevant here: everything yielded after verify is
target output. Without a draft model the plain loop writes KV before yield,
so key and KV stay aligned.

Repro (Llama-3.2-3B-4bit + 1B draft, mlx-lm 0.32.2, temp 0)

Request A needs no knowledge of the victim:
"My favorite color is blue. I also enjoy long walks." with max_tokens=5
(5 % 4 == 0). Victim prompt is always "The capital of France is".
Completions prepend BOS, so the two share exactly one token.

Probe (insert_cache / fetch_nearest_cache logs):

A          INSERT key_len=18  main KV offset=17        gap 1
victim     FETCH  req_len=6 cp=1 longer=18 main=[0]    BOS KV trimmed away
           INSERT key_len=46  main KV offset=45        gap persists
cold run   INSERT key_len=46  main KV offset=46        aligned

Same victim request:

cold (empty cache):
  Paris. The capital of France is Paris. The capital of France is Paris.

after A:
  Paris. The capital of Germany is Berlin. The capital of Italy is Rome.
  The capital of Spain is Madrid. The capital of Portugal is Lisbon. ...

Same input and sampling; only difference is an unrelated request ran first.
Here the shared token is BOS, so it loses KV (attention sink) and the prompt
is read at positions 0.. instead of 1... Smaller shared prefixes need a
tighter victim or top-2 margin to flip; --kv-bits widens the gap to 4–10.

Impact

  • Any request forking a cached entry can get the wrong context: retry, regen,
    or another chat/user sharing BOS, system prompt, or template header.
  • Same prompt can return different text on the second call.
  • A bad insert leaves a mismatched entry in the LRU (gap 1 → 2) until eviction.
  • Greedy only; trigger is earlier request's max_tokens divisibility — looks
    flaky but is deterministic for a given pair.

Fix

In insert_cache, clamp the stored token list to the first-layer (target)
cache sequence length; skip empty keys. Draft caches sit after that layer.

Fork trims match the real shared prefix; exact continuations re-run the last
token from the true KV frontier so the previously unread token finally gets
KV; realigned inserts stop the mismatch from spreading.

## The one-token gap

In speculative_generate_step the target reads 1 + k tokens per round (the
token left over from the previous round plus k drafted tokens) and emits
k + 1 candidates: k verify slots plus one extra token sampled past the
drafts. That extra token is only fed into the target at the start of the
next round. When generation stops on it, there is no next round: the
emitted token list is one token longer than the target's KV.

With every draft accepted this happens deterministically whenever
max_tokens is divisible by (num_draft_tokens + 1). The server defaults
hit it out of the box: max_tokens 512 / num_draft_tokens 3, and
512 % 4 == 0. A --draft-model (server flag or per-request draft_model)
is all that is needed to take this path.

Minimal example (prompt [7, 3, 4, 1], max_tokens 3, k 2): the draft
proposes [8, 9], the target emits [8, 9, 2].

    read by the target:   7 3 4 1 8 9
    emitted:              7 3 4 1 8 9 2   <- 2 has no key/value

max_tokens 2 instead stops on the already-read 9 and the KV is aligned.

## What the gap does to the shared prompt cache

The server records the emitted list as the cache key, so the entry's
ledger claims one token more than its KV holds. When a later request
forks from that entry, fetch_nearest_cache trims by
len(key) - prefix, so the trim over-cuts by the gap: one already-read
shared token loses its KV and every following token runs at shifted
positions, silently changing that request's greedy output. The
corrupted run is then re-inserted under its own misaligned key; measured
on mlx_lm.server the stored gap grows 1 -> 2 and persists in the LRU
until eviction, so repeats and later forks diverge as well.

## Fix

Clamp the stored token list to the cache's actual sequence length in
insert_cache (first layer = target model; draft caches are appended
after it) and skip empty keys. Fork trims then land exactly on the
shared-prefix boundary, exact continuations re-process the final token
from the true KV frontier, and the misalignment no longer propagates.

## Verification

- New unit tests (TestLRUPromptCacheKeyAlignment) fail on the old code
  (AssertionError: 11 != 13, the over-trim) and pass with the clamp.
- End-to-end differential repro (Qwen2.5-0.5B 4bit, draft on,
  temperature 0): request B returned a corrupted completion after any
  forking request A; with the fix all arms return byte-identical output
  to the cold run.

@ipazarbasi ipazarbasi left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for tracking this down! The clamp fixes the plain KVCache case, but I think the root cause is in speculative_generate_step: it yields the bonus token and stops without feeding it, while generate_step always feeds a token before yielding it. Clamping in insert_cache relies on layer 0 having an int offset but it isn't true for CacheList or the batch caches. In that case, it silently does nothing. Also, if layer 0 has offset 0, the entry is now silently dropped. Would it make more sense to fix this where the tokens are generated instead?

Comment thread mlx_lm/models/cache.py Outdated
"""
if len(prompt_cache) == 0:
return None
offset = getattr(prompt_cache[0], "offset", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CacheList models have no offset. The key will be stored unclamped (below) which means this PR has no effect in that case. Can you recurse into the object?

Comment thread mlx_lm/models/cache.py Outdated
n = prompt_cache_length(prompt_cache)
if n is not None and len(tokens) > n:
tokens = tokens[:n]
if not tokens:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this line pass all the tests? This stops entries with an empty key from being stored. Please run the tests.

Comment thread mlx_lm/models/cache.py Outdated
# every following token (https://github.com/ml-explore/mlx-lm/issues/1494
# reports the same key/KV mismatch class for windowed caches).
n = prompt_cache_length(prompt_cache)
if n is not None and len(tokens) > n:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only checks the target cache. If every draft token is accepted in the last round, the draft cache ends one token behind the target so the stored draft cache is one token short of the key, and requests that reuse this entry keep it that way. Output is still correct since the target verifies, but acceptance should drop. Is this expected?

Comment thread tests/test_prompt_cache.py Outdated

model = object()
lru = LRUPromptCache()
lru.insert_cache(model, list(range(18)), [self._make_cache(18)])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this test is proving the PR. This key is already aligned with the cache (18 tokens, 18 KV), so the clamp never runs and the test passes without the fix too. With list(range(19)) here, rest should be [18, 99]; the old code returns [99].

Comment thread tests/test_prompt_cache.py Outdated
@@ -836,5 +836,47 @@ def test_window_mask_with_full_kv_cache(self):
self.assertTrue(mx.array_equal(mask, expected))


class TestLRUPromptCacheKeyAlignment(unittest.TestCase):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are existing LRU tests in test_server.py.

- Move the fix into speculative_generate_step so the target and draft
  KV caches match the yielded tokens when the generator finishes or is
  closed early. Add regression tests and set DummyModelProvider.is_batchable
  to False when a draft model is loaded so the existing server tests
  exercise speculative decoding.
- Remove the prompt-cache clamp and its tests.
@turingH

turingH commented Nov 24, 2026

Copy link
Copy Markdown
Author
  1. I agree with your reasoning. I removed the clamp and moved the fix into the finally block of speculative_generate_step. When the generator exits, including when the caller closes it early, both the target and draft KV caches match the prompt followed by every yielded token, in length and content.

  2. I originally thought the output bug only occurred when max_tokens % (num_draft_tokens + 1) == 0. The output can change if the target KV cache is missing a yielded token when the generator exits and that cache is later reused. For example, this can happen when a bonus token reaches the max_tokens limit, when the bonus token is EOS, or when the client disconnects immediately after the generator yields a bonus token. The draft cache can also lag by one or two tokens. On its own, that can lower the draft acceptance rate on reuse, but the target still verifies every draft token. The fix aligns both caches.

  3. The fix no longer depends on offset, which also avoids the CacheList issue.

  4. I replaced the old tests with regression tests in test_generate.py and test_server.py. I also set DummyModelProvider.is_batchable to False when a draft model is loaded so the existing draft-model server tests exercise speculative decoding.

  5. test_insert_empty_tokens_does_not_self_destruct failed with the clamp in place and now passes with it removed.

@cassieliang6709

Copy link
Copy Markdown

I ran into the same bug independently with Qwen3 and opened #2104 before I found this PR, so I closed mine as a duplicate.

Repro on 1bf8da0: mlx_lm.server with Qwen3-4B-Instruct-2507-4bit as the main model and Qwen3-0.6B-4bit as the draft, temperature 0, same chat request sent twice. The second response starts with user\n and echoes the input back. The cache had 336 tokens and the key had 337. With this branch (a4b972f) both requests return the same output on my M1 Pro.

One small thing: the extra forward pass in the finally block runs before the server ends the response, so clients wait for it. On my machine the median time from the last token to the end of the stream was 30 ms. Closing the generator after rqueue.put(None) brings it to about 3 ms, and the caches are still filled before insert_cache. I opened a PR against your branch with that change: turingH#1. Feel free to fold it in or ignore it.

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.

3 participants