Repository navigation
Clamp prompt-cache keys to the KV they describe #2083
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
## 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.- Loading branch information
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -119,6 +119,23 @@ def can_trim_prompt_cache(cache: List[Any]) -> bool: | |
| return all(c.is_trimmable() for c in cache) | ||
|
|
||
|
|
||
| def prompt_cache_length(prompt_cache: List[Any]) -> Optional[int]: | ||
| """ | ||
| Return the sequence length of the prompt cache's first layer, if it can | ||
| be determined, otherwise ``None``. | ||
|
|
||
| The first layer belongs to the target model, also when draft caches are | ||
| appended for speculative decoding, so this is the number of tokens whose | ||
| KV the cache actually holds. | ||
| """ | ||
| if len(prompt_cache) == 0: | ||
| return None | ||
| offset = getattr(prompt_cache[0], "offset", None) | ||
| if isinstance(offset, int): | ||
| return offset | ||
| return None | ||
|
|
||
|
|
||
| def trim_prompt_cache(cache: List[Any], num_tokens: int) -> List[Any]: | ||
| """ | ||
| Trim the model's cache by the given number of tokens. | ||
|
|
@@ -1679,6 +1696,21 @@ def insert_cache( | |
| *, | ||
| cache_type: str = "assistant", | ||
| ): | ||
| # The generation loop can finish with emitted tokens whose KV was | ||
| # never computed, e.g. the speculative decoding bonus token which is | ||
| # only processed at the start of the next draft/verify round. Never | ||
| # store a token list longer than the cache it describes: | ||
| # fetch_nearest_cache trims stored entries by ``len(key) - prefix``, | ||
| # so a key longer than the cache makes requests that fork from this | ||
| # entry drop the last shared token's KV and shift the positions of | ||
| # 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. Choose a reason for hiding this commentThe 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? |
||
| tokens = tokens[:n] | ||
| if not tokens: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
| return | ||
|
|
||
| # Make the cache entry | ||
| entry = LRUPromptCache.CacheEntry( | ||
| prompt_cache, sum(c.nbytes for c in prompt_cache), cache_type | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are existing LRU tests in test_server.py. |
||
| def _make_cache(self, length): | ||
| c = KVCache() | ||
| kv = mx.zeros((1, 1, length, 8), mx.float16) | ||
| c.update_and_fetch(kv, kv) | ||
| return c | ||
|
|
||
| def test_insert_clamps_tokens_to_cache_length(self): | ||
| # A generation can emit more tokens than the KV cache holds (e.g. | ||
| # the speculative decoding bonus token). The stored key must be | ||
| # clamped to the cache, otherwise a forking fetch over-trims. | ||
| from mlx_lm.models.cache import LRUPromptCache | ||
|
|
||
| model = object() | ||
| cache = self._make_cache(18) | ||
|
|
||
| lru = LRUPromptCache() | ||
| # 20 emitted tokens but KV for only 18. | ||
| lru.insert_cache(model, list(range(20)), [cache]) | ||
|
|
||
| # A request sharing the first 13 tokens must restart exactly at the | ||
| # shared prefix boundary. | ||
| query = list(range(13)) + [100, 101, 102] | ||
| fetched, rest = lru.fetch_nearest_cache(model, query) | ||
| self.assertEqual(fetched[0].offset, 13) | ||
| self.assertEqual(rest, [100, 101, 102]) | ||
|
|
||
| def test_exact_continuation_processes_next_token(self): | ||
| # With the key clamped to the cache, a request that extends the | ||
| # stored prompt re-processes from the true KV frontier, so the | ||
| # previously unprocessed final token gets its KV computed. | ||
| from mlx_lm.models.cache import LRUPromptCache | ||
|
|
||
| model = object() | ||
| lru = LRUPromptCache() | ||
| lru.insert_cache(model, list(range(18)), [self._make_cache(18)]) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
|
|
||
| fetched, rest = lru.fetch_nearest_cache(model, list(range(18)) + [99]) | ||
| self.assertEqual(fetched[0].offset, 18) | ||
| self.assertEqual(rest, [99]) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CacheListmodels have nooffset. The key will be stored unclamped (below) which means this PR has no effect in that case. Can you recurse into the object?