Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions mlx_lm/models/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

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?

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.
Expand Down Expand Up @@ -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:

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?

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.

return

# Make the cache entry
entry = LRUPromptCache.CacheEntry(
prompt_cache, sum(c.nbytes for c in prompt_cache), cache_type
Expand Down
42 changes: 42 additions & 0 deletions tests/test_prompt_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

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)])

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].


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()