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: keep the last full-attention layer unquantized in the MLX KV cache (#11083)

Long Yixing164f9c892fda
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 627002c20f7..64bc72512c7 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -1724,27 +1724,36 @@ def _allocate_empty_quantized_exactly(cls):
cls.update_and_fetch = update_and_fetch
+def _kv_quant_targets(entries):
+ """``(indices, held)``: windowed entries keep their ring; past two entries the last
+ full-attention one stays float, as mlx-vlm's should_quantize_kv_layer does."""
+ targets = [
+ index
+ for index, entry in enumerate(entries)
+ if getattr(entry, "to_quantized", None) is not None and not _kv_entry_windowed(entry)
+ ]
+ if len(entries) > 2 and targets:
+ targets.pop()
+ return targets, 1
+ return targets, 0
+
+
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]))
+ for index in _kv_quant_targets(entries)[0]:
+ entry = entries[index]
+ entries[index] = entry.to_quantized(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):
- """``(converted, skipped, failure, retainable)``; runs a real second token over the converted cache,
+ """``(converted, skipped, failure, retainable)``: runs a token through the converted cache,
since static proxies (declared head_dim, window spelling) proved wrong both ways."""
import mlx.core as mx
- 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)
+ targets, held = _kv_quant_targets(entries)
+ skipped = len(entries) - len(targets) - held
if not targets:
# Verdict already known, so skip the cost of a full model call.
return 0, skipped, None, True
@@ -1832,6 +1841,7 @@ def _kv_quant_eligibility(
if not entries:
return "none", "this model builds no KV cache to quantize", True
+ total = len(entries)
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)
@@ -1845,7 +1855,14 @@ def _kv_quant_eligibility(
if failure is not None:
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
+ if skipped < total:
+ reason = (
+ "it has a single full-attention layer, and the last full-attention "
+ "layer stays unquantized"
+ )
+ else:
+ reason = "this model's KV cache layout cannot be quantized"
+ return "none", reason, True
if not skipped:
return "full", "", retainable
if windowed == skipped:
@@ -2967,7 +2984,7 @@ class MLXInferenceBackend:
return entries if bits is None else _quantize_kv_entries(entries, bits)
def _kv_quant_generate_kwargs(self):
- """Pre-quantized cache instead of kv_bits, which converts every entry and raises on a rotating one."""
+ """A pre-quantized cache, not kv_bits: both runtimes would convert a rotating entry."""
if self._kv_quant_bits() is None:
return {}
return {
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index 4212918d3cb..d94fc4090ff 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -2999,7 +2999,7 @@ def _tiny_lm(
dim = 128,
attends_quantized = True,
):
- """Tiny model filling its cache; ``attends_quantized = False`` mimics Gemma 4's KV-shared layers."""
+ """``attends_quantized = False`` rejects a quantized cache, as Gemma 4's KV-shared layers do."""
import mlx.core as mx
class _LM:
@@ -3106,13 +3106,15 @@ def test_kv_quant_probe_reports_what_the_runtime_would_really_do(monkeypatch):
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())]
+ mixed = lambda: [lm_cache.KVCache()] + 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 verdict(lambda: [lm_cache.KVCache() for _ in range(3)]) == ("full", "", True)
+ alone = verdict(lambda: [lm_cache.RotatingKVCache(max_size = 8)] * 2 + [lm_cache.KVCache()])
+ assert alone[0] == "none" and "stays unquantized" in alone[1]
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"
@@ -3678,27 +3680,37 @@ def test_kv_quant_probe_rewinds_the_rng_without_assigning_to_the_state(monkeypat
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 import mlx_inference
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._model = _tiny_lm(
+ lambda: [
+ lm_cache.RotatingKVCache(max_size = 8),
+ lm_cache.KVCache(),
+ lm_cache.KVCache(),
+ lm_cache.RotatingKVCache(max_size = 8),
+ ]
+ )
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
+ kinds = [type(entry).__name__ for entry in kwargs["prompt_cache"]]
+ assert kinds == ["RotatingKVCache", "QuantizedKVCache", "KVCache", "RotatingKVCache"]
+ assert kwargs["prompt_cache"][1].bits == 4
+ assert [
+ type(e).__name__
+ for e in mlx_inference._quantize_kv_entries([lm_cache.KVCache(), lm_cache.KVCache()], 4)
+ ] == ["QuantizedKVCache", "QuantizedKVCache"]
cache, rest = backend._prompt_cache().fetch(backend._model, "key", [1, 2, 3])
- assert isinstance(cache[1], lm_cache.QuantizedKVCache) and rest == [1, 2, 3]
+ assert [type(entry).__name__ for entry in cache] == kinds 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