Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: quantize the KV cache of sliding-window MLX models such as Gemma 4 (#11082)

Long Yixingc4f0b0b38993
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 179ed360f50..627002c20f7 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -4,6 +4,7 @@ interface, using mlx-lm/mlx-vlm instead of torch/transformers for model loading
import copy
import difflib
+import functools
import hashlib
import importlib
import os
@@ -1591,9 +1592,6 @@ MLX_KV_QUANT_NO_REUSE = (
"The installed mlx-lm cannot measure a quantized cache entry, so prompt-cache "
"reuse across turns is disabled while this is on."
)
-MLX_KV_QUANT_VLM_CACHE_NOTE = (
- "On vision models, quantization starts once the cache reaches {start} tokens."
-)
def _kv_entry_nbytes(entry):
@@ -1694,54 +1692,90 @@ def _restore_mlx_rng_key(words):
mx.random.seed((pair[0] << 32) | pair[1])
+def _kv_entry_windowed(entry):
+ return any(getattr(entry, name, None) is not None for name in ("max_size", "window_size"))
+
+
+def _allocate_empty_quantized_exactly(cls):
+ """First block at mx.quantize's ``dim * bits // 32``; upstream's ``dim // (32 // bits)`` is a word too wide at 3/5/6 bits."""
+ original = cls.update_and_fetch
+ if getattr(original, "_unsloth_exact_empty_alloc", False):
+ return
+
+ @functools.wraps(original)
+ def update_and_fetch(self, keys, values):
+ if self.keys is None:
+ import mlx.core as mx
+
+ batch, heads, steps, _ = keys.shape
+ shape = (batch, heads, (self.step + steps - 1) // self.step * self.step)
+
+ def block(dim):
+ return (
+ mx.zeros((*shape, dim * self.bits // 32), dtype = mx.uint32),
+ mx.zeros((*shape, dim // self.group_size), dtype = keys.dtype),
+ mx.zeros((*shape, dim // self.group_size), dtype = keys.dtype),
+ )
+
+ self.keys, self.values = block(keys.shape[-1]), block(values.shape[-1])
+ return original(self, keys, values)
+
+ update_and_fetch._unsloth_exact_empty_alloc = True
+ cls.update_and_fetch = update_and_fetch
+
+
+def _quantize_kv_entries(entries, bits):
+ for index, entry in enumerate(entries):
+ convert = getattr(entry, "to_quantized", None)
+ if convert is not None and not _kv_entry_windowed(entry):
+ entries[index] = convert(group_size = MLX_KV_GROUP_SIZE, bits = bits)
+ if getattr(entry, "keys", True) is None:
+ _allocate_empty_quantized_exactly(type(entries[index]))
+ return entries
+
+
def _kv_quant_probe(language_model, entries, bits):
- """Attempt the conversion the runtime will perform, on a real cache. Static proxies proved wrong
- in both directions: a model can declare a head_dim it does not use for the cache, and a
- window can be spelled differently from entry to entry. So populate one token and try the
- conversion that generation would do. Returns ``(converted, skipped, failure, retainable)``,
- where ``retainable`` is False when a converted entry's size cannot be read, because the
- prompt cache budgets by size and upstream recomputes it internally."""
+ """``(converted, skipped, failure, retainable)``; runs a real second token over the converted cache,
+ since static proxies (declared head_dim, window spelling) proved wrong both ways."""
import mlx.core as mx
- convertible = [entry for entry in entries if getattr(entry, "to_quantized", None) is not None]
- if not convertible:
+ targets = [
+ index
+ for index, entry in enumerate(entries)
+ if getattr(entry, "to_quantized", None) is not None and not _kv_entry_windowed(entry)
+ ]
+ skipped = len(entries) - len(targets)
+ if not targets:
# Verdict already known, so skip the cost of a full model call.
- return 0, len(entries), None, True
- if any(
- getattr(entry, name, None) is not None
- for entry in convertible
- for name in ("max_size", "window_size")
- ):
- # A bounded ring cannot be probed unwrapped, and wrapped its conversion keeps an absolute offset past its
- # storage. Refuse before the forward pass.
- return 0, 0, "it uses a bounded sliding window", True
+ return 0, skipped, None, True
- # The forward pass below draws random numbers, so keep sampled output stable.
+ # The forward passes below draw random numbers, so keep sampled output stable.
rng_key = _mlx_rng_key_words()
try:
try:
language_model(mx.array([[0]]), cache = entries)
mx.eval([getattr(entry, "state", None) for entry in entries])
except Exception as exc:
+ if is_metal_queue_dead(exc):
+ raise
return 0, 0, f"its cache could not be exercised ({type(exc).__name__})", True
-
- converted = skipped = 0
- retainable = True
- for entry in entries:
- convert = getattr(entry, "to_quantized", None)
- if convert is None:
- skipped += 1
- continue
- try:
- quantized = convert(group_size = MLX_KV_GROUP_SIZE, bits = bits)
- mx.eval(quantized.state)
- converted += 1
- except Exception as exc:
- return converted, skipped, f"MLX cannot quantize it ({type(exc).__name__})", True
- # Same helper insertion uses, so the caveat matches what insertion sees.
- if retainable and _kv_entry_nbytes(quantized) is None:
- retainable = False
- return converted, skipped, None, retainable
+ try:
+ _quantize_kv_entries(entries, bits)
+ mx.eval([entries[index].state for index in targets])
+ except Exception as exc:
+ if is_metal_queue_dead(exc):
+ raise
+ return 0, 0, f"MLX cannot quantize it ({type(exc).__name__})", True
+ try:
+ language_model(mx.array([[0]]), cache = entries)
+ mx.eval([getattr(entry, "state", None) for entry in entries])
+ except Exception as exc:
+ if is_metal_queue_dead(exc):
+ raise
+ return 0, 0, f"it cannot attend over a quantized cache ({type(exc).__name__})", True
+ # Same helper insertion uses, so the caveat matches what insertion sees.
+ retainable = all(_kv_entry_nbytes(entries[index]) is not None for index in targets)
+ return len(targets), skipped, None, retainable
finally:
_restore_mlx_rng_key(rng_key)
@@ -1788,18 +1822,9 @@ def _kv_quant_eligibility(
is_vlm,
bits = MLX_KV_BITS_CHOICES[0],
):
- """Whether KV quantization can apply to this model, before generating. Returns ``(verdict,
- reason, retainable)``, verdict in full/partial/none/refused. Eligibility only: what the
- runtime converts stays its own decision. Refusing here is what stops an ineligible model
- raising mid-generation, once the leading entries are already converted."""
- language_model = getattr(model, "language_model", model) if is_vlm else model
+ """``(verdict, reason, retainable)`` for this model, verdict in full/partial/none/refused."""
try:
- if is_vlm:
- from mlx_vlm.models import cache as vlm_cache
- entries = vlm_cache.make_prompt_cache(language_model)
- else:
- from mlx_lm.models import cache as lm_cache
- entries = lm_cache.make_prompt_cache(language_model)
+ entries = _make_kv_entries(model, is_vlm)
except Exception as exc:
logger.warning("MLX KV quantization eligibility probe failed: %s", exc)
return "none", "this model's KV cache layout could not be inspected", True
@@ -1807,6 +1832,8 @@ def _kv_quant_eligibility(
if not entries:
return "none", "this model builds no KV cache to quantize", True
+ windowed = sum(_kv_entry_windowed(entry) for entry in entries)
+ language_model = getattr(model, "language_model", model) if is_vlm else model
converted, skipped, failure, retainable = _kv_quant_probe(language_model, entries, bits)
# Released only here, once the probe's own locals are gone, or the pages stay in the allocator.
import mlx.core as mx
@@ -1819,18 +1846,30 @@ def _kv_quant_eligibility(
return "refused", f"this model's KV cache cannot be quantized: {failure}", True
if not converted:
return "none", "this model's KV cache layout cannot be quantized", True
- verdict = "partial" if skipped else "full"
- reason = "only some of this model's layers use a quantizable KV cache" if skipped else ""
- return verdict, reason, retainable
+ if not skipped:
+ return "full", "", retainable
+ if windowed == skipped:
+ reason = (
+ "its sliding-window layers keep a fixed-size cache, so only the "
+ "full-attention layers are quantized"
+ )
+ else:
+ reason = "only some of this model's layers use a quantizable KV cache"
+ return "partial", reason, retainable
-def _vlm_quantized_kv_start():
- """Token offset at which mlx-vlm begins quantizing, per its own default."""
- try:
- from mlx_vlm.generate.common import DEFAULT_QUANTIZED_KV_START
- return int(DEFAULT_QUANTIZED_KV_START)
- except Exception:
- return 5000
+def _make_kv_entries(
+ model,
+ is_vlm,
+ max_kv_size = None,
+):
+ language_model = getattr(model, "language_model", model) if is_vlm else model
+ if is_vlm:
+ from mlx_vlm.models import cache as vlm_cache
+ return vlm_cache.make_prompt_cache(language_model, max_kv_size = max_kv_size)
+ from mlx_lm.models import cache as lm_cache
+
+ return lm_cache.make_prompt_cache(language_model, max_kv_size = max_kv_size)
# An override replaces an existing template, never creates one: both render selectors pick their target by whether a
@@ -2153,19 +2192,11 @@ def _kv_entry_is_bounded(entry, window):
def _kv_window_enforced(model, is_vlm, window):
- """Whether a cache built for this model at *window* is bounded in every layer. Both runtimes
- defer to a model's own make_cache when it has one and ignore max_kv_size there. Returns None
- when no cache could be built to judge."""
- language_model = getattr(model, "language_model", model) if is_vlm else model
+ """Whether a cache built at *window* is bounded in every layer, None where none could be built
+ to judge: both runtimes defer to a model's own make_cache and ignore max_kv_size there."""
try:
- if is_vlm:
- from mlx_vlm.models import cache as vlm_cache
- entries = vlm_cache.make_prompt_cache(language_model, max_kv_size = window)
- else:
- from mlx_lm.models import cache as lm_cache
- entries = lm_cache.make_prompt_cache(language_model, max_kv_size = window)
- # Inside the guard with the build: an unjudgeable shape must read as unknown, since load_model calls this
- # unguarded and a raise would fail the load.
+ entries = _make_kv_entries(model, is_vlm, max_kv_size = window)
+ # Inside the guard: load_model calls this unguarded, so a raise would fail the load.
flattened = list(_flatten_kv_entries(entries))
return bool(flattened) and all(_kv_entry_is_bounded(entry, window) for entry in flattened)
except Exception as exc:
@@ -2173,12 +2204,7 @@ def _kv_window_enforced(model, is_vlm, window):
return None
-def _kv_quant_status(
- requested_bits,
- model,
- is_vlm,
- starts_at_first_token = False,
-):
+def _kv_quant_status(requested_bits, model, is_vlm):
"""Resolve a requested bit width against this model into a status dict."""
status = {
"requested_kv_bits": requested_bits,
@@ -2194,12 +2220,7 @@ def _kv_quant_status(
status["reason"] = reason
if verdict in ("full", "partial"):
status["kv_bits"] = requested_bits
- notes = []
- if is_vlm and not starts_at_first_token:
- notes.append(MLX_KV_QUANT_VLM_CACHE_NOTE.format(start = _vlm_quantized_kv_start()))
- if not retainable:
- notes.append(MLX_KV_QUANT_NO_REUSE)
- status["note"] = " ".join(notes)
+ status["note"] = "" if retainable else MLX_KV_QUANT_NO_REUSE
else:
logger.info("MLX KV quantization not applied: %s", reason)
return status
@@ -2274,12 +2295,14 @@ class _MLXPromptCacheHistory:
max_entries,
max_bytes,
max_kv_size = None,
+ prepare = None,
):
api = _mlx_prompt_cache_api()
if api is None:
raise RuntimeError("mlx-lm is too old for LRUPromptCache")
lru_cls, make, can_trim, trim = api
self._max_kv_size = max_kv_size
+ self._prepare = prepare
self._make_prompt_cache = make
self._can_trim = can_trim
self._trim = trim
@@ -2300,8 +2323,10 @@ class _MLXPromptCacheHistory:
covered = len(head) - len(rest)
return cache, list(tokens[covered:])
if self._max_kv_size is None:
- return self._make_prompt_cache(model), list(tokens)
- return self._make_prompt_cache(model, max_kv_size = self._max_kv_size), list(tokens)
+ cache = self._make_prompt_cache(model)
+ else:
+ cache = self._make_prompt_cache(model, max_kv_size = self._max_kv_size)
+ return cache if self._prepare is None else self._prepare(cache), list(tokens)
def insert(self, key, tokens, cache):
# An over-budget entry evicts itself and every other conversation.
@@ -2716,6 +2741,7 @@ class MLXInferenceBackend:
PROMPT_CACHE_ENTRIES,
max_bytes,
self._kv_cache_window,
+ prepare = self._prepare_kv_entries,
)
except Exception as exc:
self._prompt_cache_unavailable = True
@@ -2818,7 +2844,9 @@ class MLXInferenceBackend:
key = f"{self.active_model_name}|{adapter_state!r}"
if images:
key += f"|{self._vlm_image_digest(images)}"
- make_cache = lambda: make_prompt_cache(language_model, max_kv_size = window)
+ make_cache = lambda: self._prepare_kv_entries(
+ make_prompt_cache(language_model, max_kv_size = window)
+ )
block = self._vlm_media_block(prompt, images, make_cache)
return VLMPromptCacheSession(
store,
@@ -2931,16 +2959,20 @@ class MLXInferenceBackend:
max_new_tokens = max(1, min(int(max_new_tokens), int(budget) - len(prompt_tokens)))
return max_new_tokens
+ def _kv_quant_bits(self):
+ return (getattr(self, "_kv_quant", None) or {}).get("kv_bits")
+
+ def _prepare_kv_entries(self, entries):
+ bits = self._kv_quant_bits()
+ return entries if bits is None else _quantize_kv_entries(entries, bits)
+
def _kv_quant_generate_kwargs(self):
- """Load-time runtime knobs for a generate call, empty when unset. quantized_kv_start is
- otherwise left to each runtime, whose defaults differ (0 and 5000); under a budget
- mlx-vlm's could sit above every request the budget admits, and would never be reached."""
- kv_bits = (getattr(self, "_kv_quant", None) or {}).get("kv_bits")
- if kv_bits is None:
+ """Pre-quantized cache instead of kv_bits, which converts every entry and raises on a rotating one."""
+ if self._kv_quant_bits() is None:
return {}
- if getattr(self, "_kv_context_budget", None):
- return {"kv_bits": kv_bits, "quantized_kv_start": 0}
- return {"kv_bits": kv_bits}
+ return {
+ "prompt_cache": self._prepare_kv_entries(_make_kv_entries(self._model, self._is_vlm))
+ }
def _check_context_budget(
self,
@@ -3126,7 +3158,6 @@ class MLXInferenceBackend:
_normalize_mlx_kv_bits(kv_bits),
self._model,
is_vlm,
- starts_at_first_token = pinned and enforceable,
)
if quant["kv_bits"] is None and enforceable:
logger.info("MLX KV cache limited to %d tokens", int(served))
@@ -3258,8 +3289,7 @@ class MLXInferenceBackend:
self._model, max_seq_length
)
self._served_context = _served_ctx
- # Classify before the first generation: an ineligible cache would otherwise raise inside
- # maybe_quantize_kv_cache mid-stream, after converting the leading entries.
+ # Classified now so a cache the model cannot attend over is refused here, not on a token.
(
self._kv_quant,
self._kv_cache_window,
@@ -3911,10 +3941,11 @@ class MLXInferenceBackend:
max_tokens = max_new_tokens,
sampler = sampler,
)
- gen_kwargs.update(self._kv_quant_generate_kwargs())
gen_kwargs.update(self._kv_window_generate_kwargs())
if prompt_cache is not None:
gen_kwargs["prompt_cache"] = prompt_cache
+ else:
+ gen_kwargs.update(self._kv_quant_generate_kwargs())
if logits_processors is not None:
gen_kwargs["logits_processors"] = logits_processors
for response in stream_generate(
@@ -4270,7 +4301,6 @@ class MLXInferenceBackend:
top_k = int(top_k or 0),
min_p = float(min_p or 0.0),
)
- vlm_kwargs.update(self._kv_quant_generate_kwargs())
vlm_kwargs.update(self._kv_window_generate_kwargs())
if seed is not None:
# generate_step builds its temperature/top_p/min_p/top_k sampler only when sampler is None, so a seeded
@@ -4367,6 +4397,8 @@ class MLXInferenceBackend:
vlm_kwargs.update(session.media_block.generate_kwargs())
# Reused and unreused turns must prefill on the same grid to match.
vlm_kwargs["prefill_step_size"] = session.step
+ else:
+ vlm_kwargs.update(self._kv_quant_generate_kwargs())
session_scope = session if session is not None else nullcontext()
def _stream_vlm_snapshots():
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index f748e300798..4212918d3cb 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -2964,7 +2964,7 @@ def test_worker_forwards_use_adapter_on_the_audio_command():
assert '"use_adapter"' in src
-def test_kv_quant_status_applies_only_when_eligible_and_notes_vlm_cost(monkeypatch):
+def test_kv_quant_status_applies_only_when_eligible(monkeypatch):
from core.inference import mlx_inference
monkeypatch.setattr(
@@ -2982,9 +2982,7 @@ def test_kv_quant_status_applies_only_when_eligible_and_notes_vlm_cost(monkeypat
text = mlx_inference._kv_quant_status(8, object(), False)
vlm = mlx_inference._kv_quant_status(8, object(), True)
assert text["kv_bits"] == 8 and not text["note"]
- # The threshold caveat rides with the resolved value, so an API client sees it.
- assert vlm["kv_bits"] == 8 and "vision models" in vlm["note"]
- assert str(mlx_inference._vlm_quantized_kv_start()) in vlm["note"]
+ assert vlm["kv_bits"] == 8 and not vlm["note"]
monkeypatch.setattr(
mlx_inference,
@@ -2996,8 +2994,12 @@ def test_kv_quant_status_applies_only_when_eligible_and_notes_vlm_cost(monkeypat
assert refused["requested_kv_bits"] == 8 # what the reload decision compares
-def _tiny_lm(cache_factory, dim = 128):
- """Minimal model whose forward populates whatever cache it is given."""
+def _tiny_lm(
+ cache_factory,
+ dim = 128,
+ attends_quantized = True,
+):
+ """Tiny model filling its cache; ``attends_quantized = False`` mimics Gemma 4's KV-shared layers."""
import mlx.core as mx
class _LM:
@@ -3013,7 +3015,9 @@ def _tiny_lm(cache_factory, dim = 128):
target = getattr(entry, "update_and_fetch", None)
if target is not None:
k = mx.zeros((1, 2, inputs.shape[1], dim))
- target(k, k)
+ keys, _ = target(k, k)
+ if not attends_quantized and not isinstance(keys, mx.array):
+ raise TypeError("incompatible function arguments")
return mx.zeros((1, inputs.shape[1], 8))
return _LM()
@@ -3081,16 +3085,35 @@ def test_kv_quant_probe_reports_what_the_runtime_would_really_do(monkeypatch):
pytest.importorskip("mlx_lm")
from mlx_lm.models import cache as lm_cache
- def elig(factory, dim = 128):
- lm = _tiny_lm(factory, dim)
+ def verdict(
+ factory,
+ dim = 128,
+ **kwargs,
+ ):
+ lm = _tiny_lm(factory, dim, **kwargs)
monkeypatch.setattr(lm_cache, "make_prompt_cache", lambda m, **_: lm.make_cache())
- return mlx_inference._kv_quant_eligibility(lm, False, 8)[0]
+ return mlx_inference._kv_quant_eligibility(lm, False, 8)
+
+ def elig(
+ factory,
+ dim = 128,
+ **kwargs,
+ ):
+ return verdict(factory, dim, **kwargs)[0]
assert elig(lambda: [lm_cache.KVCache(), lm_cache.KVCache()]) == "full"
# A width mx.quantize rejects is caught by attempting it, not by naming it.
assert elig(lambda: [lm_cache.KVCache()], dim = 80) == "refused"
# A container the quantizer never descends into is skipped, not fatal.
assert elig(lambda: [lm_cache.CacheList(lm_cache.KVCache())]) == "none"
+ # Gemma 4's layout: the rotating window keeps its ring, the full layers convert.
+ windowed = lambda: [lm_cache.KVCache(), lm_cache.RotatingKVCache(max_size = 8)]
+ assert elig(windowed) == "partial"
+ assert "sliding-window" in verdict(windowed)[1]
+ mixed = lambda: windowed() + [lm_cache.CacheList(lm_cache.KVCache())]
+ assert verdict(mixed)[0] == "partial" and "sliding-window" not in verdict(mixed)[1]
+ assert elig(lambda: [lm_cache.RotatingKVCache(max_size = 8)]) == "none"
+ assert elig(windowed, attends_quantized = False) == "refused"
# Mixed quantizable/non-quantizable is a real success, reported as partial.
assert elig(lambda: [lm_cache.KVCache(), lm_cache.CacheList(lm_cache.KVCache())]) == "partial"
@@ -3556,6 +3579,38 @@ def test_an_entry_the_upstream_lru_cannot_size_is_not_retainable(monkeypatch):
assert probe(SimpleNamespace(state = (), nbytes = 128))[3] is True
+def test_kv_quant_probe_raises_a_dead_metal_queue(monkeypatch):
+ """The orchestrator retires a worker on this marker; a refusal would keep it serving on a dead queue."""
+ from core.inference import mlx_inference
+
+ _install_fake_mlx(monkeypatch)
+ mx = sys.modules["mlx.core"]
+ mx.random = SimpleNamespace(state = [0])
+ mx.array = lambda v: v
+ mx.eval = lambda *a: None
+ calls = []
+
+ def language_model(*args, **kwargs):
+ calls.append(None)
+ if len(calls) > 1:
+ raise RuntimeError(f"[METAL] Command buffer execution failed: {message}")
+
+ entry = SimpleNamespace(
+ to_quantized = lambda group_size, bits: SimpleNamespace(state = (), nbytes = 1),
+ max_size = None,
+ window_size = None,
+ state = (),
+ )
+ message = "GPU Timeout Error"
+ with pytest.raises(RuntimeError, match = "GPU Timeout"):
+ mlx_inference._kv_quant_probe(language_model, [entry], 8)
+
+ calls.clear()
+ message = "Insufficient Memory"
+ failure = mlx_inference._kv_quant_probe(language_model, [entry], 8)[2]
+ assert failure == "it cannot attend over a quantized cache (RuntimeError)"
+
+
class _SentinelRandomState:
"""``mx.random.state`` as mlx >= 0.32.1 exposes it: readable, not writable."""
@@ -3610,15 +3665,81 @@ def test_kv_quant_probe_rewinds_the_rng_without_assigning_to_the_state(monkeypat
outcome = mlx_inference._kv_quant_probe(language_model, [entry], 8)
assert outcome == (1, 0, None, True)
- # A rewind that ran before the forward pass would leave the probe's own
+ # A rewind that ran before the forward passes would leave the probe's own
# draws in the stream the caller goes on to sample.
assert events == [
("forward", None),
("convert", None),
+ ("forward", None),
("seed", (words[0] << 32) | words[1]),
]
+def test_generate_kwargs_and_history_carry_a_pre_quantized_cache_and_no_kv_bits():
+ pytest.importorskip("mlx_lm")
+ from mlx_lm.models import cache as lm_cache
+ from core.inference.mlx_inference import MLXInferenceBackend
+
+ backend = MLXInferenceBackend()
+ # Rotating first, so a conversion that only reads the leading entry is visible.
+ backend._model = _tiny_lm(lambda: [lm_cache.RotatingKVCache(max_size = 8), lm_cache.KVCache()])
+ backend._kv_quant = {"kv_bits": None}
+ assert backend._kv_quant_generate_kwargs() == {}
+
+ backend._kv_quant = {"kv_bits": 4}
+ kwargs = backend._kv_quant_generate_kwargs()
+ assert set(kwargs) == {"prompt_cache"}
+ rotating, full = kwargs["prompt_cache"]
+ assert isinstance(rotating, lm_cache.RotatingKVCache)
+ assert isinstance(full, lm_cache.QuantizedKVCache) and full.bits == 4
+
+ cache, rest = backend._prompt_cache().fetch(backend._model, "key", [1, 2, 3])
+ assert isinstance(cache[1], lm_cache.QuantizedKVCache) and rest == [1, 2, 3]
+
+
+def test_vlm_prompt_cache_session_starts_from_a_pre_quantized_cache(monkeypatch):
+ """The vision session's make_cache must quantize, or a quantized load runs unquantized there."""
+ pytest.importorskip("mlx_lm")
+ from mlx_lm.models import cache as lm_cache
+ from core.inference.mlx_inference import MLXInferenceBackend, VLMPromptSnapshotStore
+
+ names = ("mlx_vlm", "mlx_vlm.generate", "mlx_vlm.generate.common", "mlx_vlm.models")
+ modules = {name: types.ModuleType(name) for name in names + ("mlx_vlm.models.cache",)}
+ modules["mlx_vlm.models.cache"].make_prompt_cache = lambda _model, max_kv_size = None: [
+ lm_cache.RotatingKVCache(max_size = 8),
+ lm_cache.KVCache(),
+ ]
+ for name, module in modules.items():
+ monkeypatch.setitem(sys.modules, name, module)
+
+ backend = MLXInferenceBackend.__new__(MLXInferenceBackend)
+ backend._vlm_snapshot_store = VLMPromptSnapshotStore(10**6)
+ backend._vlm_snapshot_store_unavailable = False
+ backend._vlm_is_diffusion_model = lambda _model: False
+ backend._model = SimpleNamespace(config = SimpleNamespace(), language_model = object())
+ backend._kv_cache_window = None
+ backend.active_model_name = "m"
+ backend._kv_quant = {"kv_bits": 4}
+ session = backend._vlm_prompt_cache_session("base")
+ kinds = [type(entry).__name__ for entry in session.cache]
+ assert kinds == ["RotatingKVCache", "QuantizedKVCache"] and session.cache[1].bits == 4
+
+ import mlx.core as mx
+ from core.inference.mlx_inference import (
+ cache_entries_nbytes,
+ cache_entries_offset,
+ copy_cache_entries,
+ )
+
+ for entry in session.cache:
+ entry.update_and_fetch(mx.ones((1, 1, 4, 64)), mx.ones((1, 1, 4, 64)))
+ snapshot = copy_cache_entries(session.cache)
+ assert type(snapshot[1]).__name__ == "QuantizedKVCache" and snapshot[1].bits == 4
+ assert cache_entries_offset(snapshot) == 4
+ assert cache_entries_nbytes(snapshot[1:]) > 0
+ assert backend._vlm_snapshot_store.store("m", [1, 2, 3, 4], snapshot)
+
+
def test_a_successful_override_does_not_pin_the_tokenizer_past_load(monkeypatch):
"""The restore pairs hold the tokenizer, so unload_model cannot free it.
@@ -4549,16 +4670,18 @@ def test_the_load_policy_bounds_a_pin_only_where_the_bound_can_be_enforced(monke
unreadable = SimpleNamespace(layers = [object()], make_cache = lambda: None)
assert policy(unreadable, None, 8192) == (None, None, None, None)
- # Under a budget quantization starts at the first token, not mlx-vlm's later start.
+ # The pre-built cache quantizes from the first token, budget or not.
backend = MLXInferenceBackend()
backend._model = honours
+ backend._is_vlm = False
budgeted, _, _, budget = backend._resolve_kv_policy(True, 4, 4096, 4096)
unpinned, _, _, _ = backend._resolve_kv_policy(True, 4, 0, 262144)
- assert budget == 4096 and budgeted["note"] == "" and unpinned["note"]
- backend._kv_quant, backend._kv_context_budget = budgeted, budget
- assert backend._kv_quant_generate_kwargs() == {"kv_bits": 4, "quantized_kv_start": 0}
- backend._kv_context_budget = None
- assert backend._kv_quant_generate_kwargs() == {"kv_bits": 4}
+ assert budget == 4096 and budgeted["note"] == "" and unpinned["note"] == ""
+ for backend._kv_context_budget in (budget, None):
+ backend._kv_quant = budgeted
+ kwargs = backend._kv_quant_generate_kwargs()
+ assert set(kwargs) == {"prompt_cache"}
+ assert [getattr(entry, "bits", None) for entry in kwargs["prompt_cache"]] == [4, 4]
def _drive_vlm_generation(
@@ -7249,6 +7372,25 @@ def test_single_image_replay_notes_describe_only_retained_pixels(monkeypatch, me
assert len(image_marker_parts(history)) == 2
[email protected]("module", ["mlx_lm.models.cache", "mlx_vlm.models.cache"])
+ "bits, head_dim", [(5, 128), (6, 128), (3, 256), (5, 256), (6, 256), (8, 128)]
+)
+def test_an_empty_cache_converted_before_generation_decodes_at_every_width(module, bits, head_dim):
+ # Upstream sizes an empty QuantizedKVCache one packed word too wide at these widths.
+ mx = pytest.importorskip("mlx.core")
+ cache_module = pytest.importorskip(module)
+ from core.inference.mlx_inference import _quantize_kv_entries
+
+ (cache,) = _quantize_kv_entries([cache_module.KVCache()], bits)
+ for _ in range(300):
+ token = mx.random.normal((1, 2, 1, head_dim))
+ keys, _values = cache.update_and_fetch(token, token)
+ restored = mx.dequantize(*keys, group_size = 64, bits = bits)
+ mx.eval(restored)
+ assert restored.shape == (1, 2, 300, head_dim)
+
+
def test_a_random_model_decoding_through_mlx_lm_emits_only_the_schema():
"""Real mlx_lm pipelining (the next step is masked before this token is yielded) with a
random model: only the grammar can make the reply a valid document."""