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): rewind the MLX PRNG in the KV quantization probe without item assignment (#9478)

Long Yixing067e2ffc8dd1
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 8607e8142ef..48c71eb9ea1 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -410,6 +410,34 @@ def _normalize_mlx_kv_bits(value):
return bits
+def _mlx_rng_key_words():
+ """The MLX PRNG key as its two 32-bit words, or None if it cannot be read.
+
+ Deciding it here is what lets the rewind below stay unconditional.
+ """
+ import mlx.core as mx
+
+ try:
+ words = mx.random.state[0].tolist()
+ except Exception:
+ return None
+ return (int(words[0]), int(words[1])) if len(words) == 2 else None
+
+
+def _restore_mlx_rng_key(words):
+ """Rewind the MLX PRNG to a key captured by ``_mlx_rng_key_words``.
+
+ mlx 0.32.1 made mx.random.state a sentinel that refuses item assignment.
+ mx.random.key packs a seed as its two 32-bit halves, so reseeding with a
+ key's own words restores it exactly, over the whole unsigned 64-bit range.
+ """
+ import mlx.core as mx
+
+ if words is None:
+ return
+ mx.random.seed((words[0] << 32) | words[1])
+
+
def _kv_quant_probe(language_model, entries, bits):
"""Attempt the conversion the runtime will perform, on a real cache.
@@ -438,8 +466,7 @@ def _kv_quant_probe(language_model, entries, bits):
return 0, 0, "it uses a bounded sliding window", True
# The forward pass below draws random numbers, so keep sampled output stable.
- # mx.random.state is mutated in place, so restore element-wise, not by rebinding.
- rng_state = list(mx.random.state)
+ rng_key = _mlx_rng_key_words()
try:
try:
language_model(mx.array([[0]]), cache = entries)
@@ -465,7 +492,7 @@ def _kv_quant_probe(language_model, entries, bits):
retainable = False
return converted, skipped, None, retainable
finally:
- mx.random.state[:] = rng_state
+ _restore_mlx_rng_key(rng_key)
def _kv_quant_eligibility(
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index b1d52a69c48..251cf7119d7 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -2711,6 +2711,69 @@ def test_an_entry_the_upstream_lru_cannot_size_is_not_retainable(monkeypatch):
assert probe(SimpleNamespace(state = (), nbytes = 128))[3] is True
+class _SentinelRandomState:
+ """``mx.random.state`` as mlx >= 0.32.1 exposes it: readable, not writable."""
+
+ def __init__(self, words):
+ self._words = list(words)
+
+ def __len__(self):
+ return 1
+
+ def __getitem__(self, index):
+ if index not in (0, -1):
+ raise IndexError("random state index out of range")
+ return SimpleNamespace(tolist = lambda: list(self._words))
+
+ def __iter__(self):
+ return iter([self[0]])
+
+
+def test_kv_quant_probe_rewinds_the_rng_without_assigning_to_the_state(monkeypatch):
+ """mlx 0.32.1 made mx.random.state a sentinel with no __setitem__, so the
+ assignment this used to do raised out of the probe's finally and failed the
+ whole model load.
+ """
+ from core.inference import mlx_inference
+
+ _install_fake_mlx(monkeypatch)
+ mx = sys.modules["mlx.core"]
+ # High word's top bit set, so a rewind that packs the seed as signed is visible.
+ words = (0xFEDCBA98, 0x76543210)
+ events = []
+ mx.random = SimpleNamespace(
+ state = _SentinelRandomState(words),
+ seed = lambda value: events.append(("seed", value)),
+ )
+ mx.array = lambda v: v
+ mx.eval = lambda *a: None
+ mx.clear_cache = lambda: None
+
+ def language_model(*args, **kwargs):
+ events.append(("forward", None))
+
+ def to_quantized(group_size, bits):
+ events.append(("convert", None))
+ return SimpleNamespace(state = (), nbytes = 128)
+
+ entry = SimpleNamespace(
+ to_quantized = to_quantized,
+ max_size = None,
+ window_size = None,
+ state = (),
+ )
+ 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
+ # draws in the stream the caller goes on to sample.
+ assert events == [
+ ("forward", None),
+ ("convert", None),
+ ("seed", (words[0] << 32) | words[1]),
+ ]
+
+
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.