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
Prev Previous commit
Align speculative KV caches on generator exit
- 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.
  • Loading branch information
turingH committed Nov 24, 2026
commit a4b972f312184988fbd19b57ed10a8b41dad8630
23 changes: 22 additions & 1 deletion mlx_lm/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,7 @@ def speculative_generate_step(
logits. Default: ``None``.
prompt_cache (List[Any], optional): A pre-computed prompt cache. Note, if
provided, the cache will be updated in place. The cache must be trimmable.
When the generator stops, the cache holds every yielded token.
prefill_step_size (int): Step size for processing the prompt.
kv_bits (int, optional): Number of bits to use for KV cache quantization.
None implies no cache quantization. Default: ``None``.
Expand Down Expand Up @@ -605,6 +606,12 @@ def _prefill(model, cache, y):
mx.clear_cache()
return y

def _feed(model, cache, y):
"""Read y into the cache and discard the logits."""
model(y[None], cache=cache)
quantize_cache_fn(cache)
mx.eval([c.state for c in cache])

def _rewind_cache(num_draft, num_accept):
trim_prompt_cache(model_cache, num_draft - num_accept)
trim_prompt_cache(draft_cache, max(num_draft - num_accept - 1, 0))
Expand All @@ -627,6 +634,8 @@ def _draft_generate(y, num_draft):
# Set these so the finally block doesn't raise
num_draft = 0
n = 0
# Bonus token that was yielded but not read by the models yet
bonus = None
try:
while True:
num_draft = min(max_tokens - ntoks, num_draft_tokens)
Expand All @@ -637,6 +646,7 @@ def _draft_generate(y, num_draft):
]
y = mx.concatenate([y, draft_tokens])
tokens, logprobs = _step(model, model_cache, y, num_draft + 1)
bonus = None
mx.eval(tokens, draft_tokens)
draft_tokens = draft_tokens.tolist()
tokens = tokens.tolist()
Expand All @@ -652,7 +662,8 @@ def _draft_generate(y, num_draft):
break
if ntoks < max_tokens:
ntoks += 1
yield tokens[n], logprobs[n], False
bonus = tokens[n]
yield bonus, logprobs[n], False

if ntoks == max_tokens:
break
Expand All @@ -673,6 +684,16 @@ def _draft_generate(y, num_draft):
_rewind_cache(num_draft, n)
finally:
_rewind_cache(num_draft, n)
# Read the tokens that were yielded but not processed yet, so the
# cache holds every yielded token as generate_step does
# If all drafts were accepted, the draft model has not read the
# last one
unread = draft_tokens[-1:] if num_draft > 0 and n == num_draft else []
if bonus is not None:
_feed(model, model_cache, mx.array([bonus], mx.uint32))
unread.append(bonus)
if unread:
_feed(draft_model, draft_cache, mx.array(unread, mx.uint32))


def stream_generate(
Expand Down
32 changes: 0 additions & 32 deletions mlx_lm/models/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,23 +119,6 @@ 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.
Expand Down Expand Up @@ -1696,21 +1679,6 @@ 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:
tokens = tokens[:n]
if not tokens:
return

# Make the cache entry
entry = LRUPromptCache.CacheEntry(
prompt_cache, sum(c.nbytes for c in prompt_cache), cache_type
Expand Down
66 changes: 66 additions & 0 deletions tests/test_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,72 @@ def __call__(self, inputs, cache=None):
)
self.assertEqual([t for t, _, _ in gen], expected)

def test_speculative_cache_holds_all_yielded_tokens(self):
# The server stores the yielded tokens next to the prompt cache and
# sizes later trims from the token count. Every yielded token must be
# in the target and the draft cache, also when the bonus token is
# last or the caller stops the generator early.
model = self.model
prompt = mx.array(self.tokenizer.encode("Write a story about Einstein"))
n_layers = len(model.layers)

# Always proposes token 0, so the target rejects the drafts.
class RejectedDraft:
layers = model.layers

def __call__(self, inputs, cache=None):
return model(inputs, cache=cache).at[..., 0].add(1e4)

# (draft, num_draft_tokens, max_tokens): the generation stops on the
# bonus token (2, 3), on the last accepted draft (2, 2) and (3, 4),
# and on a bonus token after a rejected draft.
cases = [(model, 2, 3), (model, 2, 2), (model, 3, 4), (RejectedDraft(), 2, 2)]
for draft, num_draft_tokens, max_tokens in cases:
for stop_after in [None, *range(1, max_tokens + 1)]:
with self.subTest(
draft=type(draft).__name__,
num_draft_tokens=num_draft_tokens,
max_tokens=max_tokens,
stop_after=stop_after,
):
# The target layers come first, the draft layers after
cache = [KVCache() for _ in range(2 * n_layers)]
gen = speculative_generate_step(
prompt,
model,
draft,
prompt_cache=cache,
num_draft_tokens=num_draft_tokens,
max_tokens=max_tokens,
)
tokens = []
for i, (token, _, _) in enumerate(gen):
tokens.append(token)
if i + 1 == stop_after:
break
gen.close()

for c in cache:
self.assertEqual(c.offset, len(prompt) + len(tokens))

# With max_tokens 0 the cache holds the KV of the input
reference = [KVCache() for _ in range(n_layers)]
list(
generate_step(
mx.array(prompt.tolist() + tokens),
model,
max_tokens=0,
prompt_cache=reference,
)
)
# Chunked and single-token passes differ by about 1e-5,
# the KV of two tokens by about 10.
for i, c in enumerate(cache):
keys, values = c.keys_and_values()
ref_keys, ref_values = reference[i % n_layers].keys_and_values()
self.assertLess(mx.abs(keys - ref_keys).max().item(), 0.1)
self.assertLess(mx.abs(values - ref_values).max().item(), 0.1)

def test_stream_generate_input_embeddings(self):
sampler = make_sampler(temp=0.0) # determinate sampler

Expand Down
42 changes: 0 additions & 42 deletions tests/test_prompt_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -836,47 +836,5 @@ def test_window_mask_with_full_kv_cache(self):
self.assertTrue(mx.array_equal(mask, expected))


class TestLRUPromptCacheKeyAlignment(unittest.TestCase):
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)])

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()
44 changes: 44 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ def __init__(self, with_draft=False, kv_bits=None, quantized_kv_start=0):
self.draft_model, _ = load(HF_MODEL_PATH)
self.draft_model_key = HF_MODEL_PATH
self.cli_args.draft_model = HF_MODEL_PATH
# A model with a draft model is served sequentially
self.is_batchable = False

def load(self, model, adapter=None, draft_model=None):
assert model in ["default_model", "chat_model"]
Expand Down Expand Up @@ -646,6 +648,48 @@ def test_prompt_cache_with_draft_model(self):
self.assertIsNotNone(first_response_body["choices"][0]["message"]["content"])
self.assertIsNotNone(second_response_body["choices"][0]["message"]["content"])

def test_prompt_cache_holds_all_tokens_with_draft_model(self):
# fetch_nearest_cache trims a stored entry by its token count, so the
# target and the draft cache must hold every token of the key.
url = f"http://localhost:{self.port}/v1/completions"
text = "A B C D E F G"
tokenizer = self.response_generator.model_provider.tokenizer
prompt = tokenizer.encode(text)
# The generation stops on the bonus token (4), on the last accepted
# draft (3) and on a fork of the two entries before (5).
max_tokens_list = [4, 3, 5]
inserted = []
stored = threading.Semaphore(0)
insert_cache = self.response_generator.prompt_cache.insert_cache

def record(model, tokens, cache, **kwargs):
insert_cache(model, tokens, cache, **kwargs)
if tokens[: len(prompt)] == prompt:
inserted.append((tokens, cache))
stored.release()

self.response_generator.prompt_cache.insert_cache = record
try:
for max_tokens in max_tokens_list:
post_data = {
"model": "default_model",
"prompt": text,
"max_tokens": max_tokens,
"temperature": 0.0,
"top_p": 1.0,
}
response = requests.post(url, json=post_data)
self.assertEqual(response.status_code, 200)
# The generation thread stores the cache after the response.
self.assertTrue(stored.acquire(timeout=10))
finally:
del self.response_generator.prompt_cache.insert_cache

self.assertEqual(len(inserted), len(max_tokens_list))
for tokens, cache in inserted:
for c in cache:
self.assertEqual(c.offset, len(tokens))


class TestServerKVCacheQuantization(unittest.TestCase):
@classmethod
Expand Down