Skip to content

Commit acac015

Browse files
gstark0rkinas
authored andcommitted
fix(mlx): the state cache needs a length-independent RoPE; a note on shared servers
MLXBackend refuses --state-cache-gb / --prefix-cache when a layer's RoPE depends on the sequence length (dynamic NTK, ...): cached keys are continued in forwards of other lengths, so they would not match the keys of the longer forward. Default, linear, llama3 and Gemma 4's proportional RoPE are accepted. The --state-cache-gb help and SERVING.md say that the cache is shared by all clients, so its timing tells whether a state is cached.
1 parent 08e0faf commit acac015

4 files changed

Lines changed: 51 additions & 2 deletions

File tree

‎basal/engine.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3630,6 +3630,10 @@ def __init__(self, model_dir, max_rows=None, quant=None, packed=False, forward="
36303630
self.prefill = PREFILL
36313631
self.max_rows = max_rows or self.MAX_ROWS
36323632
self.pool.submit(self._load, Path(model_dir), quant, packed, forward, compute, adapter).result()
3633+
if self.state_cache is not None and not self._cache_rope_ok():
3634+
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")
36333637

36343638
def _load(self, md, quant=None, packed=False, forward="mlx-lm", compute="auto", adapter=None):
36353639
"""quant: None, or "q8": MLX affine 8-bit weights (group size 64) of the decoder blocks' linear layers, made at
@@ -3748,6 +3752,18 @@ def _static_rope(rope):
37483752
from mlx_lm.models.rope_utils import Llama3RoPE
37493753
return type(rope) in (nn.RoPE, Llama3RoPE)
37503754

3755+
def _cache_rope_ok(self):
3756+
"""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
3760+
for layer in self.lm.model.layers:
3761+
rope = getattr(getattr(layer, "self_attn", None), "rope", None)
3762+
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):
3764+
return False
3765+
return True
3766+
37513767
def _position_rope(self):
37523768
"""Llama decoders without sliding windows and with a static RoPE (_static_rope): wraps each layer's RoPE so that an offset of shape [B, L] (one
37533769
position per token, _PackedRow) rotates every token at its own position, each token as its own row of the same

‎basal/server.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2301,7 +2301,8 @@ def add_engine_args(ap):
23012301
help="CUDA graph engine and --mode mlx: keep the keys and values of request states on the GPU "
23022302
"up to this many GB (least recently used evicted); a later request with the same state "
23032303
"computes only its questions and options, one whose state begins with a cached one only its "
2304-
"new tokens (0: off)")
2304+
"new tokens (0: off). The cache is shared by all clients: a client can tell from the response "
2305+
"time whether a state it guesses is cached")
23052306
ap.add_argument("--state-cache-lock", dest="state_cache_lock", choices=["off", "on"], default="off",
23062307
help="--state-cache-gb in the CUDA graph engine: on continues cached states under the engine's "
23072308
"launch lock, which removes a rare HTTP 500 under concurrent requests (a torch.compile "

‎docs/SERVING.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,9 @@ benchmarking a GPU.
196196
`--lean on|pass2` (one compiled layer function: faster start-up, slower
197197
under load), `--tree flex` (a FlexAttention mask for the branches of a request), `--readout-layer on`,
198198
`--state-cache-gb N` (a state cache across requests; 2.3.1: also for states that begin with a cached one, e.g.
199-
agent traces, which then compute only their new tokens; 2.5: `--state-cache-bits 8` keeps ~1.7x as many
199+
agent traces, which then compute only their new tokens; shared by all clients, so a client can tell from the
200+
response time whether a state it guesses is cached: keep it off where clients must not learn about each other's
201+
states; 2.5: `--state-cache-bits 8` keeps ~1.7x as many
200202
states per GB, answers close to the uncached ones; `--state-cache-lock on` removes a rare HTTP 500 under
201203
concurrent requests at ~8% of the throughput at 8 clients, see WHATS_NEW 2.5's known limits), `--prefix-cache`,
202204
`--long-lane`. Measurements:

‎tests/test_mlx_state_cache.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,3 +336,33 @@ def test_a_state_cached_by_another_request_gives_the_uncached_bits(tmp_path, for
336336
assert cached.run_shared([(one, LIDS[4:], len(STATE))])[0] == plain.run_shared([(one, LIDS[4:])])[0]
337337
st = cached.state_cache.stats()
338338
assert (st["entries"], st["misses"], st["hits"]) == (2, 2, 2) # one entry per row count, each found again
339+
340+
341+
@pytest.mark.parametrize("rope, ok", [
342+
(None, True),
343+
({"rope_type": "linear", "rope_theta": 1e6, "factor": 2.0}, True),
344+
({"rope_type": "llama3", "rope_theta": 1e6, "factor": 8.0, "low_freq_factor": 1.0, "high_freq_factor": 4.0,
345+
"original_max_position_embeddings": 64}, True),
346+
({"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),
348+
])
349+
def test_the_cache_needs_a_static_rope(tmp_path, monkeypatch, rope, ok):
350+
"""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."""
352+
pytest.importorskip("mlx.core")
353+
from types import SimpleNamespace
354+
355+
from basal import engine
356+
from tests.test_mlx import tiny_gemma4
357+
tiny_llama(tmp_path, rope)
358+
assert mlx_stub(tmp_path)._cache_rope_ok() is ok
359+
tok = SimpleNamespace(pad_token="<pad>", eos_token="</s>", pad_token_id=0) # no tokenizer files here
360+
monkeypatch.setattr(engine.AutoTokenizer, "from_pretrained", lambda *a, **k: tok)
361+
if ok:
362+
assert engine.MLXBackend(tmp_path, state_cache_gb=0.1).state_cache is not None
363+
else:
364+
with pytest.raises(SystemExit, match="RoPE"):
365+
engine.MLXBackend(tmp_path, state_cache_gb=0.1)
366+
assert engine.MLXBackend(tmp_path).state_cache is None # without the cache it serves as before
367+
tiny_gemma4(tmp_path / "g4")
368+
assert mlx_stub(tmp_path / "g4")._cache_rope_ok()

0 commit comments

Comments
 (0)