Skip to content

Commit 6c6af75

Browse files
committed
fix(mlx): the state cache takes mlx-lm's yarn and longrope RoPE, whose frequencies are fixed
The refusal accepted only the RoPE kinds the packed rows take (default, linear, llama3) and Gemma 4's proportional one, so a yarn or longrope model was refused the cache. In mlx-lm both compute their frequencies when they are built: a state rotated in its own forward and continued at its offset equals the whole sequence rotated at once, past max_position_embeddings too, while dynamic NTK differs there. The cache now takes them, any unknown kind is still refused, and a test rotates every kind split and whole, so a change of mlx-lm shows.
1 parent acac015 commit 6c6af75

2 files changed

Lines changed: 45 additions & 8 deletions

File tree

‎basal/engine.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3632,8 +3632,8 @@ def __init__(self, model_dir, max_rows=None, quant=None, packed=False, forward="
36323632
self.pool.submit(self._load, Path(model_dir), quant, packed, forward, compute, adapter).result()
36333633
if self.state_cache is not None and not self._cache_rope_ok():
36343634
raise SystemExit("--state-cache-gb / --prefix-cache on --mode mlx need a RoPE that does not depend on the "
3635-
"sequence length in every layer (default, linear, llama3, Gemma 4's proportional): cached "
3636-
"keys are continued in forwards of other lengths")
3635+
"sequence length in every layer (default, linear, llama3, yarn, longrope, Gemma 4's "
3636+
"proportional; not dynamic NTK): cached keys are continued in forwards of other lengths")
36373637

36383638
def _load(self, md, quant=None, packed=False, forward="mlx-lm", compute="auto", adapter=None):
36393639
"""quant: None, or "q8": MLX affine 8-bit weights (group size 64) of the decoder blocks' linear layers, made at
@@ -3754,13 +3754,17 @@ def _static_rope(rope):
37543754

37553755
def _cache_rope_ok(self):
37563756
"""Whether cached keys can be continued: every layer's RoPE rotates a position the same way at any length of the
3757-
forward (_static_rope, or Gemma 4's proportional RoPE with its fixed frequencies). A dynamic NTK base, for one,
3758-
grows with the length of the call, so a state's keys from its own forward would not match the longer one."""
3759-
from mlx_lm.models.rope_utils import ProportionalRoPE
3757+
forward, i.e. its frequencies are fixed when it is built: mlx-lm's RoPE (default, linear), Llama3RoPE, YarnRoPE,
3758+
SuScaledRoPE (longrope) and Gemma 4's ProportionalRoPE (tests/test_mlx_state_cache.py rotates each split and
3759+
whole). A dynamic NTK base grows with the length of the call, so a state's keys from its own forward would not
3760+
match the longer one; a RoPE of any other kind is refused as well."""
3761+
import mlx.nn as nn
3762+
from mlx_lm.models import rope_utils as ru
3763+
fixed = (nn.RoPE, ru.Llama3RoPE, ru.YarnRoPE, ru.SuScaledRoPE, ru.ProportionalRoPE)
37603764
for layer in self.lm.model.layers:
37613765
rope = getattr(getattr(layer, "self_attn", None), "rope", None)
37623766
rope = getattr(rope, "rope", rope) # under --mlx-packed's PositionRoPE
3763-
if rope is None or not (self._static_rope(rope) or type(rope) is ProportionalRoPE):
3767+
if rope is None or type(rope) not in fixed:
37643768
return False
37653769
return True
37663770

‎tests/test_mlx_state_cache.py‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -344,11 +344,14 @@ def test_a_state_cached_by_another_request_gives_the_uncached_bits(tmp_path, for
344344
({"rope_type": "llama3", "rope_theta": 1e6, "factor": 8.0, "low_freq_factor": 1.0, "high_freq_factor": 4.0,
345345
"original_max_position_embeddings": 64}, True),
346346
({"rope_type": "dynamic", "rope_theta": 1e6, "factor": 2.0}, False), # base depends on the length of the call
347-
({"rope_type": "yarn", "rope_theta": 1e6, "factor": 2.0, "original_max_position_embeddings": 64}, False),
347+
({"rope_type": "yarn", "rope_theta": 1e6, "factor": 2.0, "original_max_position_embeddings": 64}, True),
348+
({"rope_type": "longrope", "rope_theta": 1e6, "original_max_position_embeddings": 64, "long_factor": [1.5] * 8,
349+
"short_factor": [1.0] * 8}, True),
348350
])
349351
def test_the_cache_needs_a_static_rope(tmp_path, monkeypatch, rope, ok):
350352
"""Cached keys are continued in forwards of other lengths, so the server refuses the cache for a RoPE that depends
351-
on the sequence length; Gemma 4's proportional RoPE (basal-omni) has fixed frequencies and is accepted."""
353+
on the sequence length (dynamic NTK); mlx-lm's yarn and longrope have fixed frequencies (see below) and are
354+
accepted, as is Gemma 4's proportional RoPE (basal-omni)."""
352355
pytest.importorskip("mlx.core")
353356
from types import SimpleNamespace
354357

@@ -366,3 +369,33 @@ def test_the_cache_needs_a_static_rope(tmp_path, monkeypatch, rope, ok):
366369
assert engine.MLXBackend(tmp_path).state_cache is None # without the cache it serves as before
367370
tiny_gemma4(tmp_path / "g4")
368371
assert mlx_stub(tmp_path / "g4")._cache_rope_ok()
372+
373+
374+
@pytest.mark.parametrize("cfg, fixed", [
375+
(None, True),
376+
({"rope_type": "linear", "factor": 2.0}, True),
377+
({"rope_type": "llama3", "factor": 8.0, "low_freq_factor": 1.0, "high_freq_factor": 4.0,
378+
"original_max_position_embeddings": 32}, True),
379+
({"rope_type": "yarn", "factor": 2.0, "original_max_position_embeddings": 32}, True),
380+
({"rope_type": "longrope", "original_max_position_embeddings": 32, "long_factor": [1.5] * 8,
381+
"short_factor": [1.0] * 8}, True),
382+
({"rope_type": "proportional", "partial_rotary_factor": 0.25}, True),
383+
({"rope_type": "dynamic", "factor": 2.0}, False),
384+
], ids=lambda v: v.get("rope_type") if isinstance(v, dict) else str(v))
385+
def test_the_accepted_ropes_rotate_a_continued_state_as_the_whole(cfg, fixed):
386+
"""What the cache relies on, per RoPE kind of the installed mlx-lm: the keys of a state rotated in its own forward,
387+
then the rest at its offset, equal the whole sequence rotated in one forward, past max_position_embeddings too.
388+
The kinds _cache_rope_ok accepts must keep this; dynamic NTK does not."""
389+
mx = pytest.importorskip("mlx.core")
390+
from mlx_lm.models.rope_utils import initialize_rope
391+
rope = initialize_rope(16, 1e4, False, cfg, max_position_embeddings=64)
392+
be = MLXBackend.__new__(MLXBackend)
393+
be.model = type("M", (), {"model": type("D", (), {"layers": [
394+
type("L", (), {"self_attn": type("A", (), {"rope": rope})()})()]})()})()
395+
assert be._cache_rope_ok() is fixed
396+
mx.random.seed(0)
397+
x = mx.random.normal((1, 2, 200, 16))
398+
whole = rope(x)
399+
same = all(mx.array_equal(mx.concatenate([rope(x[:, :, :k]), rope(x[:, :, k:], offset=k)], axis=2), whole).item()
400+
for k in (8, 40, 100, 150))
401+
assert same is fixed

0 commit comments

Comments
 (0)