Repository navigation
Conversation
## 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
left a comment
There was a problem hiding this comment.
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?
| """ | ||
| if len(prompt_cache) == 0: | ||
| return None | ||
| offset = getattr(prompt_cache[0], "offset", None) |
There was a problem hiding this comment.
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?
| n = prompt_cache_length(prompt_cache) | ||
| if n is not None and len(tokens) > n: | ||
| tokens = tokens[:n] | ||
| if not tokens: |
There was a problem hiding this comment.
Does this line pass all the tests? This stops entries with an empty key from being stored. Please run the tests.
| # 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: |
There was a problem hiding this comment.
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?
|
|
||
| model = object() | ||
| lru = LRUPromptCache() | ||
| lru.insert_cache(model, list(range(18)), [self._make_cache(18)]) |
There was a problem hiding this comment.
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].
| @@ -836,5 +836,47 @@ def test_window_mask_with_full_kv_cache(self): | |||
| self.assertTrue(mx.array_equal(mask, expected)) | |||
|
|
|||
|
|
|||
| class TestLRUPromptCacheKeyAlignment(unittest.TestCase): | |||
There was a problem hiding this comment.
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.
|
|
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: One small thing: the extra forward pass in the |
Summary
With
--draft-model, speculative decoding can stop after yielding one tokenthat 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_cachesizes the trim from thekey 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 + ktokens (carry-over pluskdrafts) andemits
k + 1candidates: thekverify slots plus one extra sample pastthe drafts. That extra token only enters the target at the next round's
start. When generation stops on it, there is no next round:
If every draft is accepted, one round emits
num_draft_tokens + 1tokens,so this hits whenever:
Default server flags do that:
--max-tokens 512,--num-draft-tokens 3,512 % 4 == 0. Per-requestmax_tokens/max_completion_tokensandnum_draft_tokenswork 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 yieldsaccepted drafts; the extra token is yielded after it (generate.py:655).
_steponly runs
model(y, cache=cache)on the fedy, so the last sample is notin KV. When
ntoks == max_tokensthe function breaks before the line thatwould 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):
On fork, the
longerbranch offetch_nearest_cachecomputes trim from keylength, without checking KV
offset(cache.py:1663-1666):Token
9is gone: not in effective KV and not in tokens to process.trimlowers the copy'soffsetfrom 6 to 5; slot 5 still holds9'svectors until token
5overwrites them. Positions followoffset, so5lands 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 5already holds
5's KV. Later forks see key/KV disagree from that slot. Thestored 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."withmax_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_cachelogs):Same victim request:
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-bitswidens the gap to 4–10.Impact
or another chat/user sharing BOS, system prompt, or template header.
max_tokensdivisibility — looksflaky 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.