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.

fix(studio): price MLX attention on the route the runtime takes (#16517)

Long Yixing4691cc65d3a1
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 48d442eedfe..f250cc14617 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -3293,7 +3293,8 @@ def _fitted_context(
logger.debug("MLX snapshot unavailable for %s: %s", model_name, exc)
return None, None
verdict = eligibility
- if verdict is None and kv_bits is not None:
+ # TurboQuant is converted by the estimator's own probe, as mlx-vlm does.
+ if verdict is None and isinstance(kv_bits, int):
verdict = _kv_quant_eligibility(model, is_vlm, kv_bits)
fitted = mlx_fit_to_memory(
model_dir,
@@ -5940,6 +5941,7 @@ class MLXInferenceBackend:
served,
fitted = False,
eligibility = None,
+ turboquant = None,
):
"""With kv_bits, only an enforceable pin or fitted window becomes a budget, since a rotating cache cannot be quantized"""
pinned = _positive_int(max_seq_length) is not None or fitted
@@ -5947,7 +5949,7 @@ class MLXInferenceBackend:
confirmed = self._kv_cache_window_enforceable(served)
enforceable = confirmed is True
if getattr(self, "_turboquant", False) and kv_bits is not None:
- quant = _turboquant_status(
+ quant = turboquant or _turboquant_status(
self._model, kv_bits, getattr(self, "_turboquant_refusal", "")
)
else:
@@ -6335,9 +6337,20 @@ class MLXInferenceBackend:
self._fast_verify = _settle_fast_verify(
self._fast_verify, self._model, getattr(self._speculative_draft, "drafter", None)
)
- # TurboQuant's layout is not one the planner prices, and a refused one stays full width:
- # fit either at full width, which only ever under-promises.
- _requested_bits = None if self._turboquant else _normalize_mlx_kv_bits(kv_bits)
+ _requested_bits = _normalize_mlx_kv_bits(kv_bits)
+ _turboquant = None
+ if self._turboquant:
+ from core.inference.mlx_memory import MlxTurboQuant
+
+ if kv_bits is not None:
+ _turboquant = _turboquant_status(self._model, kv_bits, self._turboquant_refusal)
+ _requested_bits = (
+ MlxTurboQuant(kv_bits)
+ if _turboquant is not None and _turboquant["kv_bits"] is not None
+ else None
+ )
+ # Only mlx-vlm's caches convert, so a text load is priced on the route it takes.
+ _vlm_route = _vlm_route or (_requested_bits is not None and not is_vision)
_fitted_ctx, _eligibility = (
(_drafter_ctx, _eligibility)
if _drafter_ctx is not None
@@ -6392,6 +6405,7 @@ class MLXInferenceBackend:
_served_ctx,
fitted = _fitted_ctx is not None,
eligibility = _eligibility,
+ turboquant = _turboquant,
)
if self._kv_quant["kv_bits"] is not None:
logger.info(
diff --git a/studio/backend/core/inference/mlx_memory.py b/studio/backend/core/inference/mlx_memory.py
index b02b3565459..38561062582 100644
--- a/studio/backend/core/inference/mlx_memory.py
+++ b/studio/backend/core/inference/mlx_memory.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import contextlib
import contextvars
+import copy
import glob
import functools
import json
@@ -26,6 +27,7 @@ __all__ = [
"MLX_KV_BLOCK",
"MLX_PREFILL_CHUNK",
"MlxMemoryBreakdown",
+ "MlxTurboQuant",
"mlx_fit_context",
"mlx_fit_outcome",
"mlx_memory_breakdown",
@@ -51,8 +53,10 @@ _COMPUTE_BASE_BYTES = int(0.64 * 1024**3)
_RECURRENT_DTYPE_SIZE = 4
-# Score copies an unfused call holds at the queries' width; Metal measured 1.03 to 1.15 (mlx 0.32.4).
-_SCORE_LIVE = 1.25
+# Score copies an unfused call holds; Metal measured 1.01-1.13 (mlx 0.32.4), NAX d512 tails 1.32 (in the fixed charge).
+_SCORE_LIVE = 1.13
+# A TurboQuant prefill holds the whole cache dequantized to float32 and cast to the query dtype; measured.
+_TURBOQUANT_DEQUANT_BYTES = 10
_WIDTH_NAMES = {"float64": "f64", "float32": "f32", "bfloat16": "bf16", "float16": "f16"}
@@ -61,6 +65,13 @@ _CACHE_BOUND_ATTRS = ("max_size", "chunk_size")
_MAX_SAFETENSORS_HEADER = 100_000_000
+@dataclass(frozen = True)
+class MlxTurboQuant:
+ """A TurboQuant cache of ``bits`` per element, passed where an ``mx.quantize`` width goes."""
+
+ bits: float
+
+
@dataclass
class MlxMemoryBreakdown:
weights_bytes: int
@@ -532,10 +543,29 @@ def _probe_models(config: dict, dtype):
yield prepared(_whole_tower), make_prompt_cache, getattr(arch, "Model", None)
-def _quantize_like_runtime(cache, kv_bits: Optional[int]):
+def _turboquant_like_runtime(cache, bits: float):
+ from mlx_vlm.generate.common import maybe_quantize_kv_cache
+ from mlx_vlm.turboquant import TurboQuantKVCache
+
+ # mlx-vlm converts in place, CacheLists included, and the probe still reads the full-width cache.
+ converted = [copy.copy(entry) for entry in cache]
+ maybe_quantize_kv_cache(converted, 0, _KV_GROUP_SIZE, bits, kv_quant_scheme = "turboquant")
+ return [
+ new if any(isinstance(leaf, TurboQuantKVCache) for leaf in _sub_caches(new)) else old
+ for new, old in zip(converted, cache)
+ ]
+
+
+def _quantize_like_runtime(cache, kv_bits):
"""The converted cache a load ends up with, or None if nothing in it converts."""
if not kv_bits:
return None
+ if isinstance(kv_bits, MlxTurboQuant):
+ try:
+ converted = _turboquant_like_runtime(cache, kv_bits.bits)
+ except Exception:
+ return None
+ return converted if any(new is not old for new, old in zip(converted, cache)) else None
from core.inference.mlx_inference import _quantize_kv_entries
try:
@@ -572,17 +602,13 @@ def _entry_bytes(entry) -> int:
# mlx-lm 0.32's KV `state` is the whole preallocated buffer; `keys_and_values` is the held part.
held = getattr(entry, "keys_and_values", None)
state = held() if callable(held) and getattr(entry, "keys", None) is not None else entry.state
- if isinstance(state, mx.array):
- state = (state,)
- elif not isinstance(state, (list, tuple)):
- return 0
- total = 0
- for item in state:
+
+ def nbytes(item) -> int:
if isinstance(item, mx.array):
- total += item.size * item.dtype.size
- elif isinstance(item, (list, tuple)):
- total += sum(sub.size * sub.dtype.size for sub in item if isinstance(sub, mx.array))
- return total
+ return item.size * item.dtype.size
+ return sum(nbytes(sub) for sub in item) if isinstance(item, (list, tuple)) else 0
+
+ return nbytes(state)
def _width_name(dtype) -> str:
@@ -599,7 +625,10 @@ def _cache_width_name(
if slot["slope"] <= 0:
continue
quantized = converted and slot["converts"]
- name = f"{kv_bits}-bit" if quantized else full_width
+ name = full_width
+ if quantized:
+ turboquant = isinstance(kv_bits, MlxTurboQuant)
+ name = f"TurboQuant {kv_bits.bits:g}-bit" if turboquant else f"{kv_bits}-bit"
const, slope = ("quant_const", "quant_slope") if quantized else ("const", "slope")
charged[name] = (
charged.get(name, 0.0)
@@ -729,6 +758,23 @@ def weightless_forward():
_DEFERRED_EVAL.depth -= 1
+def _turboquant_runs(model, make_prompt_cache, kv_bits) -> bool:
+ # The load keeps TurboQuant only after two decode steps over a converted cache succeed.
+ import mlx.core as mx
+
+ if not isinstance(kv_bits, MlxTurboQuant):
+ return True
+ try:
+ trial = _quantize_like_runtime(make_prompt_cache(model), kv_bits)
+ if trial is not None:
+ for _ in range(2):
+ model(mx.zeros((1, 1), dtype = mx.int32), cache = trial)
+ except Exception as exc:
+ logger.debug("MLX estimate prices a refused TurboQuant cache at full width: %s", exc)
+ return False
+ return True
+
+
def _probe(config: dict, dtype, n_tokens: int, kv_bits):
import mlx.core as mx
@@ -753,6 +799,8 @@ def _probe(config: dict, dtype, n_tokens: int, kv_bits):
if cache is None:
raise failure
quantized = _quantize_like_runtime(cache, kv_bits)
+ if quantized is not None and not _turboquant_runs(model, make_prompt_cache, kv_bits):
+ quantized = None
entries = _entries(cache, quantized)
if quantized is not None:
converted = [leaf for entry in quantized for leaf in _sub_caches(entry)]
@@ -943,18 +991,16 @@ def _dequantized_row_bytes(widths, dtype_size: int, kv_bits, kv_group_size, pref
try:
import mlx.core as mx
- from unsloth_zoo.mlx.attention import (
- _row_bytes,
- dequantizing_is_smaller,
- fused_kernel_exists,
- )
+ from unsloth_zoo.mlx.attention import _row_bytes, dequantizing_is_smaller
except Exception as exc:
logger.debug("MLX estimate cannot reach the quantized-attention wrapper: %s", exc)
return None
+ if _zoo_route() is None:
+ return None
try:
dtype = mx.float32 if dtype_size == 4 else mx.bfloat16
- # A causal chunk never fuses over fewer keys than queries; later chunks see more (#15935).
- cached = prefill_chunk + 1
+ # Long context: chunks never fuse over fewer keys than queries, and forced routes start at a key count (#15935).
+ cached = max(prefill_chunk + 1, 1 << 16)
def rows(width):
return mx.quantize(
@@ -965,7 +1011,7 @@ def _dequantized_row_bytes(widths, dtype_size: int, kv_bits, kv_group_size, pref
keys, values = rows(head_dim), rows(value_dim or head_dim)
queries = mx.zeros((1, heads, prefill_chunk, head_dim), dtype = dtype)
- if not fused_kernel_exists(queries, keys, values, kv_group_size, "causal"):
+ if not _zoo_route()(queries, keys, values, kv_group_size, "causal"):
return None
if not dequantizing_is_smaller(queries, keys, values, kv_group_size):
return None
@@ -993,17 +1039,29 @@ def _compute_bytes(
attention_width = (hidden + intermediate) * dtype_size * _ATTENTION_LIVE
recurrent_width = sum(int(entry["conv_width"]) for entry in plan) * _RECURRENT_DTYPE_SIZE
total = _COMPUTE_BASE_BYTES + prefill_chunk * (attention_width + recurrent_width)
- if quant_boundary is not None:
+ if quant_boundary is not None and isinstance(kv_bits, MlxTurboQuant):
+ # mlx-vlm decodes on its own kernel, and prefills attending over a dequantized cache.
+ kv_heads, head_dim, value_dim = widths[3:]
+ copy_row = kv_heads * (head_dim + (value_dim or head_dim)) * _TURBOQUANT_DEQUANT_BYTES
+ score = heads * dtype_size * _SCORE_LIVE
+ cells = _widest_unfused_scores(widths, dtype_size, n_ctx, prefill_chunk)
+ copy_row += _padding_row_bytes(widths, dtype_size, n_ctx)
+ total += copy_row * max(n_ctx - 1, 0) + cells * score
+ elif quant_boundary is not None:
score = heads * dtype_size * _SCORE_LIVE
row = _dequantized_row_bytes(widths, dtype_size, kv_bits, kv_group_size, prefill_chunk)
if row is None:
total += _widest_quantized_scores(n_ctx, quant_boundary, prefill_chunk) * score
else:
- total += max(row * n_ctx, (n_ctx + 1) * score)
+ cells = max(n_ctx + 1, _widest_unfused_scores(widths, dtype_size, n_ctx, prefill_chunk))
+ total += max(
+ (row + _padding_row_bytes(widths, dtype_size, n_ctx)) * n_ctx, cells * score
+ )
elif not any(entry.get("bound_spec") for entry in plan):
# Windowed models are skipped: the config's head_dim need not be the full-context layers' width.
score = heads * dtype_size * _SCORE_LIVE
- total += _widest_unfused_scores(widths, dtype_size, n_ctx, prefill_chunk) * score
+ cells = _widest_unfused_scores(widths, dtype_size, n_ctx, prefill_chunk)
+ total += max(cells * score, _padding_row_bytes(widths, dtype_size, n_ctx) * n_ctx)
return int(total)
@@ -1020,7 +1078,7 @@ def _widest_unfused_scores(widths, dtype_size: int, n_ctx: int, prefill_chunk: i
def longest_tail(whole, limit):
# The tail of a prompt holding no whole chunk is its first call, so it is square.
- short, first_fused = _unfused_tails(route, widths, dtype_size, chunk if whole else 0)
+ short, first_fused = _unfused_tails(route, widths, dtype_size, whole * chunk)
if limit > 8 and first_fused > 9:
return min(limit, first_fused - 1)
return max((r for r in short if r <= limit), default = 0)
@@ -1029,13 +1087,25 @@ def _widest_unfused_scores(widths, dtype_size: int, n_ctx: int, prefill_chunk: i
cells = [n_ctx + 1 if unfused(1, 2) or unfused(1, n_ctx + 1) else 0]
if whole and unfused(chunk, chunk):
cells.append(chunk * chunk)
- if whole >= 2 and unfused(chunk, whole * chunk):
- cells.append(chunk * whole * chunk)
+
+ # A forced route starts at a key count, so calls stop being unfused somewhere short of the context.
+ if whole >= 2 and unfused(chunk, 2 * chunk):
+ lo, hi = 2, whole + 1
+ while hi - lo > 1:
+ mid = (lo + hi) // 2
+ lo, hi = (mid, hi) if unfused(chunk, mid * chunk) else (lo, mid)
+ cells.append(chunk * lo * chunk)
r = longest_tail(whole, rest)
cells.append(r * (whole * chunk + r))
if whole:
- r = longest_tail(whole - 1, chunk - 1)
- cells.append(r * ((whole - 1) * chunk + r))
+ far = longest_tail(whole - 1, chunk - 1)
+ cells.append(far * ((whole - 1) * chunk + far))
+ # The widest tail below the floor can be any of them: it shrinks as it nears the floor.
+ for held in range(whole - 1):
+ r = longest_tail(held, chunk - 1)
+ if r <= far:
+ break
+ cells.append(r * (held * chunk + r))
return max(cells)
@@ -1062,6 +1132,16 @@ def _unfused_tails(route, widths, dtype_size: int, later: int):
return short, hi
+def _padding_row_bytes(widths, dtype_size: int, n_ctx: int) -> int:
+ """Bytes per cached token of the padded K and V a forced route holds; 0 on a zoo without one."""
+ _heads, kv_heads, head_dim, value_dim = (*widths[2:], 0, 0, 0, 0)[:4]
+ try:
+ from unsloth_zoo.mlx.attention import forced_padding_row_bytes
+ except Exception:
+ return 0
+ return forced_padding_row_bytes(head_dim, value_dim or head_dim, kv_heads, dtype_size, n_ctx)
+
+
def _zoo_route():
try:
import mlx.core # noqa: F401
@@ -1069,7 +1149,12 @@ def _zoo_route():
from unsloth_zoo.mlx.attention import fused_kernel_exists
except Exception:
return None
- return fused_kernel_exists
+ try:
+ from unsloth_zoo.mlx.attention import runtime_fuses
+ except ImportError:
+ # An older zoo leaves head_dim 256 prefill on mlx's own dispatch.
+ return fused_kernel_exists
+ return runtime_fuses
def _attention_fuses(route, widths, dtype_size: int, queries: int, keys: int) -> bool:
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index f7fa91a6370..9aaf2ed4702 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -14873,7 +14873,8 @@ def _mlx_estimate_fitted_context(config, model_dir: str, load_in_4bit: bool, kv_
ceiling,
load_in_4bit = load_in_4bit,
retains_history = (
- not getattr(config, "is_vision", False) or mlx_vlm_snapshot_store_available()
+ not (getattr(config, "is_vision", False) or route.get("vision"))
+ or mlx_vlm_snapshot_store_available()
),
kv_bits = kv_bits,
**route,
@@ -15048,16 +15049,18 @@ def _mlx_load_estimate(
mlx_kv_quant_is_refused,
mlx_vlm_snapshot_store_available,
)
- from core.inference.mlx_memory import mlx_memory_breakdown
+ from core.inference.mlx_memory import MlxTurboQuant, mlx_memory_breakdown
load_in_4bit = _mlx_estimate_load_in_4bit(config, request)
kv_bits = _mlx_estimate_kv_bits(request.mlx_kv_quant, request.mlx_kv_bits)
+ turboquant = isinstance(kv_bits, MlxTurboQuant)
# A width the cache takes makes the window a budget, pinned or fit.
- if kv_bits is not None and mlx_kv_quant_is_refused(model_dir, kv_bits):
+ if kv_bits is not None and not turboquant and mlx_kv_quant_is_refused(model_dir, kv_bits):
kv_bits = None
named_ctx = request.max_seq_length or 0
+ # As the load, which plans offload for a TurboQuant cache at full width.
offload, offloadable, offload_baseline = _mlx_estimate_offload(
- request, config, model_identifier, model_dir, load_in_4bit, kv_bits
+ request, config, model_identifier, model_dir, load_in_4bit, None if turboquant else kv_bits
)
drafter, fitted_ctx, speculates, stretched = _mlx_estimate_drafter(
request,
@@ -15069,7 +15072,8 @@ def _mlx_load_estimate(
offload_baseline,
kv_bits,
)
- route = {**({"vision": True} if speculates else {}), **offload}
+ # TurboQuant lives on mlx-vlm, which a text load then takes.
+ route = {**({"vision": True} if speculates or turboquant else {}), **offload}
if not named_ctx and fitted_ctx is None:
fitted_ctx = _mlx_estimate_fitted_context(config, model_dir, load_in_4bit, kv_bits, **route)
priced_ctx = named_ctx or fitted_ctx or _mlx_estimate_ceiling(model_dir)
@@ -15100,7 +15104,7 @@ def _mlx_load_estimate(
if breakdown is None:
return "unsizable", None
retains_history = (
- not (getattr(config, "is_vision", False) or speculates)
+ not (getattr(config, "is_vision", False) or speculates or turboquant)
or mlx_vlm_snapshot_store_available()
)
return None, _MlxLoadEstimate(
@@ -15288,10 +15292,15 @@ def _mlx_estimate_load_in_4bit(config, request) -> bool:
)
-def _mlx_estimate_kv_bits(mlx_kv_quant, mlx_kv_bits = None) -> Optional[int]:
- """The mx.quantize width the load would price, or None for a full-width cache."""
+def _mlx_estimate_kv_bits(mlx_kv_quant, mlx_kv_bits = None):
+ """The mx.quantize width or ``MlxTurboQuant`` the load would price, or None for a full-width cache."""
try:
- from core.inference.mlx_inference import MLX_KV_BITS_CHOICES, parse_mlx_kv_quant
+ from core.inference.mlx_inference import (
+ MLX_KV_BITS_CHOICES,
+ MLX_TURBOQUANT_BITS_CHOICES,
+ parse_mlx_kv_quant,
+ )
+ from core.inference.mlx_memory import MlxTurboQuant
except Exception:
return None
if mlx_kv_quant is None:
@@ -15299,10 +15308,9 @@ def _mlx_estimate_kv_bits(mlx_kv_quant, mlx_kv_bits = None) -> Optional[int]:
return None
return mlx_kv_bits if mlx_kv_bits in MLX_KV_BITS_CHOICES else None
bits, turboquant = parse_mlx_kv_quant(mlx_kv_quant)
- # TurboQuant's layout is not one the planner prices; the load fits it at full width too.
- if turboquant or bits not in MLX_KV_BITS_CHOICES:
- return None
- return bits
+ if turboquant:
+ return MlxTurboQuant(bits) if bits in MLX_TURBOQUANT_BITS_CHOICES else None
+ return bits if bits in MLX_KV_BITS_CHOICES else None
def _is_embedding_gguf(config: ModelConfig) -> bool:
diff --git a/studio/backend/tests/test_memory_estimate.py b/studio/backend/tests/test_memory_estimate.py
index 6b56a8d3fb3..b6b75cdf631 100644
--- a/studio/backend/tests/test_memory_estimate.py
+++ b/studio/backend/tests/test_memory_estimate.py
@@ -1389,8 +1389,11 @@ class TestEstimateMemoryRoute:
resp = _estimate(model_path = "org/model", n_ctx = 32_768, mlx_kv_quant = "4")
assert (seen["kv_bits"], resp.context_fitted, widths) == (4, 24_576, [(str(tmp_path), 4)])
widths.clear()
+ monkeypatch.setattr(mlx_inference, "mlx_vlm_snapshot_store_available", lambda: False)
resp = _estimate(model_path = "org/model", mlx_kv_quant = "tq-4", mlx_kv_bits = 4)
- assert (asked["kv_bits"], seen["kv_bits"], widths) == (None, None, [])
+ turboquant = mm.MlxTurboQuant(4)
+ assert (asked["kv_bits"], seen["kv_bits"], widths) == (turboquant, turboquant, [])
+ assert (asked.pop("vision"), asked["retains_history"]) == (True, False)
refuses["answer"] = True
resp = _estimate(model_path = "org/model", mlx_kv_bits = 4)
@@ -3736,11 +3739,14 @@ class TestMlxEstimateKvBits:
("4", None, 4),
(" 8 ", 4, 8),
("auto", 8, None),
- ("tq-4", 4, None),
+ ("tq-4", 4, ("turboquant", 4)),
+ ("tq-3.5", None, ("turboquant", 3.5)),
("bogus", 4, None),
],
)
def test_kv_bits_resolution(self, quant, bits, expected):
+ if isinstance(expected, tuple):
+ expected = mm.MlxTurboQuant(expected[1])
assert ri._mlx_estimate_kv_bits(quant, bits) == expected
@@ -4297,6 +4303,7 @@ class TestCacheWidthName:
"2-bit",
]
assert _caption([_GROWING] * 10, 4, False) == "bf16"
+ assert _caption([_GROWING] * 10, mm.MlxTurboQuant(3.5), True) == "TurboQuant 3.5-bit"
def test_an_entry_that_cannot_convert_keeps_its_width_through_a_converting_run(self):
staying = _plan_entry(converts = False, quant_slope = _GROWING["slope"])
@@ -4512,8 +4519,8 @@ def test_a_full_width_cache_pays_for_the_widest_call_mlx_does_not_fuse(monkeypat
floor = mm._compute_bytes(_BONSAI[:3], 2, 2048, [_GROWING], n_ctx, None)
asked = _unfused_route(monkeypatch, fuses)
priced = mm._compute_bytes(_BONSAI, 2, 2048, [_GROWING], n_ctx, None)
- assert priced - floor == cells * _SCORE
- assert (2048, 16 * 2048) in asked
+ assert priced - floor == pytest.approx(cells * _SCORE, abs = 1)
+ assert (2048, 2 * 2048) in asked
def test_a_tail_unfused_past_any_fixed_scan_is_still_priced(monkeypatch):
@@ -4521,7 +4528,7 @@ def test_a_tail_unfused_past_any_fixed_scan_is_still_priced(monkeypatch):
_unfused_route(monkeypatch, lambda L, S: L <= 8 or L > 8160)
floor = mm._compute_bytes(_BONSAI[:3], 2, 16384, [_GROWING], 32768, None)
priced = mm._compute_bytes(_BONSAI, 2, 16384, [_GROWING], 32768, None)
- assert priced - floor == 8160 * (16384 + 8160) * _SCORE
+ assert priced - floor == pytest.approx(8160 * (16384 + 8160) * _SCORE, abs = 1)
def test_the_scores_charged_never_fall_as_the_context_grows(monkeypatch):
@@ -4542,6 +4549,13 @@ def test_a_windowed_model_and_an_unreachable_zoo_keep_the_old_price(monkeypatch)
assert mm._compute_bytes(widths, 2, 2048, [_GROWING], 262144, None) == floor
+def _longest_unfused_d256_tail():
+ from unsloth_zoo.mlx.nax import nax_available
+
+ # NAX fuses head_dim 256 from 1024 queries.
+ return 1023 if nax_available() else 2047
+
+
@_NEEDS_MLX
class TestTheQuantizedAttentionRouteIsTheOneZooTakes:
"""unsloth-zoo routes each call between a score matrix and a dequantized copy of the cache."""
@@ -4557,8 +4571,6 @@ class TestTheQuantizedAttentionRouteIsTheOneZooTakes:
(GQA, 256, True),
(MHA, 2048, True),
(MHA, 256, False),
- (WIDE, 2048, False),
- (WIDE, 256, False),
],
)
def test_both_halves_of_the_wrappers_choice_are_asked(self, widths, chunk, copies):
@@ -4581,25 +4593,57 @@ class TestTheQuantizedAttentionRouteIsTheOneZooTakes:
scores = mm._widest_quantized_scores(32768, 2048, 2048) * 32 * 2 * mm._SCORE_LIVE
assert priced - floor == row * 32768 < scores
- def test_the_decode_step_still_scores_where_that_is_the_wider_of_the_two(self):
+ def test_a_short_call_still_scores_where_that_is_the_wider_of_the_two(self):
+ # 256:1 is past the vector kernel's limit, so the eight-query tail is unfused.
widths = (3584, 18944, 256, 1, 64, 0)
row = mm._dequantized_row_bytes(widths, 2, 8, 64, 2048)
floor = mm._compute_bytes(widths[:3], 2, 2048, [], 32768, None)
charged = mm._compute_bytes(widths, 2, 2048, [], 32768, 2048, 8, 64) - floor
- assert row is not None and charged == (32769) * 256 * 2 * mm._SCORE_LIVE
+ assert row is not None
+ assert charged == pytest.approx(8 * (15 * 2048 + 8) * 256 * 2 * mm._SCORE_LIVE, abs = 1)
assert charged > row * 32768
- def test_a_full_width_cache_is_charged_the_scores_mlx_builds_below_nax(self):
+ def test_a_full_width_cache_is_charged_only_the_tail_the_runtime_leaves_unfused(self):
+ from unsloth_zoo.mlx import attention
+
+ if not hasattr(attention, "runtime_fuses"):
+ pytest.skip("this zoo keeps head_dim 256 on mlx's dispatch")
+ assert mm._dequantized_row_bytes(self.WIDE, 2, 4, 64, 2048) is not None
+ plan = [_GROWING] * 4
+ unrouted = mm._compute_bytes(self.GQA[:3], 2, 2048, plan, 32768, None)
+ assert mm._compute_bytes(self.GQA, 2, 2048, plan, 32768, None) == unrouted
+ wide = mm._compute_bytes(self.WIDE, 2, 2048, plan, 32768, None)
+ tail = _longest_unfused_d256_tail()
+ assert wide - unrouted == pytest.approx(
+ tail * (3 * 2048 + tail) * 16 * 2 * mm._SCORE_LIVE, abs = 1
+ )
+
+ def test_a_copied_route_is_charged_a_tail_whose_scores_outgrow_the_copy(self):
+ from unsloth_zoo.mlx import attention
+
+ if not hasattr(attention, "runtime_fuses"):
+ pytest.skip("this zoo keeps head_dim 256 on mlx's dispatch")
+ widths, n_ctx = (3584, 18944, 32, 2, 256, 0), 262144
+ row = mm._dequantized_row_bytes(widths, 2, 4, 64, 2048)
+ floor = mm._compute_bytes(widths[:3], 2, 2048, [], n_ctx, None)
+ queries = _longest_unfused_d256_tail()
+ tail = queries * (3 * 2048 + queries) * 32 * 2 * mm._SCORE_LIVE
+ priced = mm._compute_bytes(widths, 2, 2048, [], n_ctx, 0, 4, 64) - floor
+ assert priced == int(max(row * n_ctx, tail))
+
+ def test_an_older_zoo_keeps_head_dim_256_on_mlxs_dispatch(self, monkeypatch):
+ from unsloth_zoo.mlx import attention
from unsloth_zoo.mlx.nax import nax_available
if nax_available():
pytest.skip("NAX fuses head_dim 256 prefill")
+ monkeypatch.delattr(attention, "runtime_fuses", raising = False)
+ assert mm._dequantized_row_bytes(self.WIDE, 2, 4, 64, 2048) is None
plan = [_GROWING] * 4
unrouted = mm._compute_bytes(self.GQA[:3], 2, 2048, plan, 32768, None)
- assert mm._compute_bytes(self.GQA, 2, 2048, plan, 32768, None) == unrouted
wide = mm._compute_bytes(self.WIDE, 2, 2048, plan, 32768, None)
- assert (
- wide - unrouted == mm._widest_quantized_scores(32768, 0, 2048) * 16 * 2 * mm._SCORE_LIVE
+ assert wide - unrouted == pytest.approx(
+ mm._widest_quantized_scores(32768, 0, 2048) * 16 * 2 * mm._SCORE_LIVE, abs = 1
)
def test_a_zoo_that_cannot_route_it_keeps_the_scores_whole(self, monkeypatch):
@@ -4616,8 +4660,8 @@ class TestTheQuantizedAttentionRouteIsTheOneZooTakes:
assert mm._dequantized_row_bytes(self.GQA, 2, 4, 64, 2048) is None
floor = mm._compute_bytes(self.GQA, 2, 2048, [], 32768, None)
priced = mm._compute_bytes(self.GQA, 2, 2048, [], 32768, 2048, 4, 64)
- assert priced - floor == (
- mm._widest_quantized_scores(32768, 2048, 2048) * 32 * 2 * mm._SCORE_LIVE
+ assert priced - floor == pytest.approx(
+ mm._widest_quantized_scores(32768, 2048, 2048) * 32 * 2 * mm._SCORE_LIVE, abs = 1
)
@pytest.mark.parametrize(
@@ -4639,7 +4683,7 @@ class TestTheQuantizedAttentionRouteIsTheOneZooTakes:
def test_a_tower_whose_values_are_narrower_keeps_the_scores(self):
assert mm._dequantized_row_bytes((3584, 18944, 32, 8, 128, 64), 2, 4, 64, 2048) is None
- assert mm._dequantized_row_bytes((3584, 18944, 32, 8, 192, 128), 2, 4, 64, 2048) is None
+ assert mm._dequantized_row_bytes((3584, 18944, 32, 8, 160, 128), 2, 4, 64, 2048) is None
assert mm._dequantized_row_bytes((3584, 18944, 32, 8, 128, 128), 2, 4, 64, 2048) == (
mm._dequantized_row_bytes(self.GQA, 2, 4, 64, 2048)
)
@@ -4710,6 +4754,178 @@ def test_the_route_is_asked_about_a_cache_longer_than_the_chunk(monkeypatch, chu
assert mask == "causal"
+def test_chunks_below_a_forced_routes_key_floor_still_charge_their_scores(monkeypatch):
+ _unfused_route(monkeypatch, lambda L, S: L > 15 and S >= 8192)
+ assert mm._widest_unfused_scores(_BONSAI, 2, 65536, 2048) == 2047 * (3 * 2048 + 2047)
+ assert mm._widest_unfused_scores(_BONSAI, 2, 4352, 2048) == 2048 * 2 * 2048
+ assert mm._widest_unfused_scores(_BONSAI, 2, 32768, 4096) == 4095 * 8191
+ assert mm._widest_unfused_scores(_BONSAI, 2, 65536, 16384) == 8191 * 8191
+
+
+ "fuses",
+ [
+ lambda L, S: L > 15 and S >= 256,
+ lambda L, S: L >= 32 or (L > 15 and S >= 256),
+ lambda L, S: L > 8,
+ lambda L, S: L > 8 and L == S,
+ lambda L, S: False,
+ ],
+)
+def test_the_widest_call_matches_walking_every_prompt_the_context_admits(monkeypatch, fuses):
+ _unfused_route(monkeypatch, fuses)
+ for chunk in (16, 48, 64, 80, 96, 384):
+ for n_ctx in range(2, 900, 37):
+ widest = 0
+ for prompt in range(1, n_ctx + 1):
+ whole, rest = divmod(prompt - 1, chunk)
+ calls = [(chunk, held * chunk) for held in range(1, whole + 1)]
+ calls += [(rest, whole * chunk + rest)] if rest else []
+ calls += [(1, prompt)]
+ widest = max([widest] + [L * S for L, S in calls if not fuses(L, S)])
+ charged = mm._widest_unfused_scores(_BONSAI, 2, n_ctx, chunk)
+ assert widest <= charged <= max(widest, n_ctx + 1), (chunk, n_ctx)
+
+
+def test_tails_below_a_key_floor_are_charged_though_every_full_chunk_fuses(monkeypatch):
+ # NAX head_dim 256: mlx fuses from 1024 queries, and shorter calls only past the floor.
+ _unfused_route(monkeypatch, lambda L, S: L >= 1024 or (L > 15 and S >= 8192))
+ assert mm._widest_unfused_scores(_BONSAI, 2, 65536, 2048) == 1023 * (3 * 2048 + 1023)
+
+
+@_NEEDS_MLX
[email protected]("on_nax, row", [(False, 4 * 192 * 2), (True, 4 * 512 * 2)])
+def test_a_padded_route_is_charged_its_copies_where_they_outgrow_the_scores(
+ monkeypatch, on_nax, row
+):
+ from unsloth_zoo.mlx import attention, nax
+
+ if not hasattr(attention, "forced_padding_row_bytes"):
+ pytest.skip("needs a zoo with the padded route")
+ monkeypatch.setattr(nax, "nax_available", lambda: on_nax)
+ widths = (4096, 16384, 64, 4, 192, 128)
+ n_ctx = 2**22
+ floor = mm._compute_bytes(widths[:3], 2, 2048, [], n_ctx, None)
+ assert mm._compute_bytes(widths, 2, 2048, [], n_ctx, None) - floor >= row * n_ctx
+ assert mm._padding_row_bytes(widths, 2, 8191) == 0
+
+
+@_NEEDS_MLX
+def test_the_score_multiple_is_what_an_unfused_call_really_holds():
+ import mlx.core as mx
+
+ q = mx.zeros((1, 8, 512, 112), dtype = mx.bfloat16) + 1
+ k = mx.zeros((1, 8, 8192, 112), dtype = mx.bfloat16) + 1
+ mx.eval(q, k)
+ mx.synchronize()
+ mx.clear_cache()
+ base = mx.get_active_memory()
+ mx.reset_peak_memory()
+ mx.eval(mx.fast.scaled_dot_product_attention(q, k, k, scale = 0.1, mask = "causal"))
+ held = (mx.get_peak_memory() - base) / (8 * 512 * 8192 * 2)
+ assert held <= mm._SCORE_LIVE < held * 1.1
+
+
+@_NEEDS_MLX
+class TestATurboQuantCacheIsSizedAsMlxVlmConvertsIt:
+ @pytest.fixture(autouse = True)
+ def _off_nax(self, monkeypatch):
+ from unsloth_zoo.mlx import nax
+ monkeypatch.setattr(nax, "nax_available", lambda: False)
+
+ @pytest.mark.parametrize(
+ "widths, scored_cells",
+ [
+ ((3584, 18944, 16, 4, 256, 256), 2047 * (3 * 2048 + 2047)),
+ # mlx's own kernel for this width starts above 8 queries.
+ ((3584, 18944, 32, 4, 64, 64), 8 * (16 * 2048 + 8)),
+ ],
+ )
+ def test_a_prefill_is_charged_its_dequantized_cache_and_any_scores(self, widths, scored_cells):
+ from unsloth_zoo.mlx import attention
+
+ if scored_cells and not hasattr(attention, "runtime_fuses"):
+ pytest.skip("needs a zoo with the head_dim 256 fused route")
+ n_ctx = 16 * 2048 + 1024
+ floor = mm._compute_bytes((*widths[:3], 0, 0, 0), 2, 2048, [], n_ctx, None)
+ priced = mm._compute_bytes(widths, 2, 2048, [], n_ctx, 0, mm.MlxTurboQuant(4)) - floor
+ copied = widths[3] * (widths[4] + widths[5]) * 10 * (n_ctx - 1)
+ assert priced == pytest.approx(
+ copied + scored_cells * widths[2] * 2 * mm._SCORE_LIVE, abs = 1
+ )
+
+ @staticmethod
+ def _filled(
+ entry,
+ tokens = 40,
+ width = 64,
+ ):
+ import mlx.core as mx
+ entry.update_and_fetch(
+ mx.zeros((1, 2, tokens, width), dtype = mx.bfloat16),
+ mx.zeros((1, 2, tokens, width), dtype = mx.bfloat16),
+ )
+ return entry
+
+ def test_every_layer_but_the_last_converts_and_the_probed_cache_is_left_whole(self):
+ from mlx_vlm.models.cache import CacheList, KVCache
+ from mlx_vlm.turboquant import TurboQuantKVCache
+
+ cache = [
+ CacheList(self._filled(KVCache())),
+ self._filled(KVCache()),
+ self._filled(KVCache()),
+ ]
+ converted = mm._quantize_like_runtime(cache, mm.MlxTurboQuant(4))
+ assert [
+ isinstance(leaf, TurboQuantKVCache)
+ for entry in converted
+ for leaf in mm._sub_caches(entry)
+ ] == [True, True, False]
+ assert converted[2] is cache[2]
+ assert all(isinstance(leaf, KVCache) for entry in cache for leaf in mm._sub_caches(entry))
+
+ @pytest.mark.parametrize("bits", [4, 3.5])
+ def test_the_bytes_counted_are_the_ones_mlx_vlm_holds(self, bits):
+ from mlx_vlm.models.cache import KVCache
+
+ cache = [self._filled(KVCache(), width = 128) for _ in range(3)]
+ leaf = mm._quantize_like_runtime(cache, mm.MlxTurboQuant(bits))[0]
+ assert 0 < mm._entry_bytes(leaf) == leaf.nbytes < mm._entry_bytes(cache[0])
+
+ def test_a_cache_mlx_vlm_does_not_convert_stays_full_width(self):
+ from mlx_lm.models.cache import KVCache
+ assert mm._quantize_like_runtime([KVCache() for _ in range(3)], mm.MlxTurboQuant(4)) is None
+
+ def test_a_model_whose_attention_cannot_read_the_converted_cache_is_priced_full_width(self):
+ import mlx.core as mx
+
+ # moondream2 hands the fetched TurboQuant state straight to mx.fast.
+ config = {
+ "model_type": "moondream2",
+ "text_config": {
+ "hidden_size": 64,
+ "num_hidden_layers": 2,
+ "num_attention_heads": 4,
+ "num_key_value_heads": 4,
+ "intermediate_size": 128,
+ "vocab_size": 512,
+ },
+ "vision_config": {
+ "hidden_size": 32,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 2,
+ "intermediate_size": 64,
+ },
+ }
+ probed = mm._probe(config, mx.bfloat16, 8, None)
+ with mm.weightless_forward():
+ build, make_prompt_cache, _ = next(iter(mm._probe_models(config, mx.bfloat16)))
+ cache = make_prompt_cache(build())
+ assert mm._quantize_like_runtime(cache, mm.MlxTurboQuant(4)) is not None
+ assert mm._probe(config, mx.bfloat16, 8, mm.MlxTurboQuant(4)) == probed
+
+
@pytest.mark.skipif(not _HAVE_MLX, reason = "imports architecture modules")
class TestProbeFollowsTheLoadersRoute:
"""The estimator must not price a load path that cannot be taken."""
@@ -5393,7 +5609,7 @@ _UNFUSED_HEAD_DIM_256_SCORES = {
None,
2_061_600,
98_304,
- 690_952_857,
+ 690_702_180,
2,
"bf16",
),
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index 4fc3857a7c3..e6ed2e02b8f 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -8229,7 +8229,9 @@ def test_a_width_refusal_is_asked_once_per_checkpoint_and_width(monkeypatch, tmp
def test_what_the_fit_is_asked_and_when_it_is_asked_at_all(monkeypatch, tmp_path):
from core.inference import mlx_inference
+ from core.inference.mlx_memory import MlxTurboQuant
+ turboquant = MlxTurboQuant(4)
priced, rewound = [], []
monkeypatch.setitem(
sys.modules,
@@ -8288,6 +8290,8 @@ def test_what_the_fit_is_asked_and_when_it_is_asked_at_all(monkeypatch, tmp_path
for answer in (("refused", "r", True), ("none", "n", True)):
verdict["answer"] = answer
assert fit(4) == (24_576, answer) and priced[0]["kv_bits"] is None
+ assert fit(turboquant) == (24_576, None) and asked == []
+ assert priced[0]["kv_bits"] == turboquant
monkeypatch.setitem(
sys.modules,
@@ -8431,8 +8435,21 @@ def test_only_a_load_that_asked_for_nothing_is_fitted_to_the_machine(monkeypatch
requested_kv_bits = bits, kv_bits = bits, eligibility = "full", reason = "", note = ""
),
)
+ from core.inference.mlx_memory import MlxTurboQuant
+
load(max_seq_length = 0, kv_quant = "tq-4")
- assert verdicts == [] and [kw["kv_bits"] for _, _, kw in asked] == [None]
+ assert verdicts == [] and [kw["kv_bits"] for _, _, kw in asked] == [MlxTurboQuant(4)]
+ assert asked[0][2]["vision"] is True
+ probed = []
+ monkeypatch.setattr(
+ mlx_inference,
+ "_turboquant_status",
+ lambda _m, bits, refusal = "": probed.append(bits)
+ or dict(requested_kv_bits = bits, kv_bits = None, eligibility = "refused", reason = "r", note = ""),
+ )
+ _, info = load(max_seq_length = 0, kv_quant = "tq-4")
+ assert [kw["kv_bits"] for _, _, kw in asked] == [None] and probed == [4]
+ assert info["mlx_kv_bits"] is None
for available, reserved in ((True, True), (False, False)):
monkeypatch.setattr(