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.

Harden the Studio MLX PRNG rewind against words that are not uint32 (#9558)

Daniel Han15b9102c0e01
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 48c71eb9ea1..90a73b930d3 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -413,7 +413,9 @@ def _normalize_mlx_kv_bits(value):
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.
+ Deciding it here is what lets the rewind below stay unconditional. A key
+ that reads but is not two words is not the same as an unreadable one: the
+ rewind no longer works on the installed mlx, so say so before declining.
"""
import mlx.core as mx
@@ -421,7 +423,45 @@ def _mlx_rng_key_words():
words = mx.random.state[0].tolist()
except Exception:
return None
- return (int(words[0]), int(words[1])) if len(words) == 2 else None
+ if len(words) != 2:
+ logger.warning(
+ "MLX exposes a %d-word random key; Unsloth can only rewind the "
+ "two-word form, so the KV quantization probe will not restore the "
+ "PRNG and sampling after a load may differ from an unprobed run.",
+ len(words),
+ )
+ return None
+ return _as_uint32_pair(int(words[0]), int(words[1]))
+
+
+def _as_uint32_pair(high, low):
+ """Both words as uint32, or None if either is not a 32-bit word at all.
+
+ mx.random.seed takes a uint64 and raises outside [0, 2**64); that raise would
+ land in the probe's finally and replace the probe's own outcome. So the words
+ are range-checked here rather than passed through, which is what lets the
+ rewind below stay unguarded.
+
+ Range-checked and not simply masked, though. A negative reads as the two's
+ complement of the uint32 mlx stores, so reinterpreting it loses nothing. A
+ value at or above 2**32 is not a 32-bit word under any reading, and masking
+ it would turn a key we cannot represent into a plausible wrong one: (2**32, 0)
+ would restore as (0, 0), the probe would report success, and sampling would
+ silently diverge from an unprobed run. Decline instead, which is the outcome
+ the caller already handles.
+ """
+ converted = []
+ for word in (high, low):
+ if not -(2**31) <= word < 2**32:
+ logger.warning(
+ "MLX exposed a random key word of %d, which is not a 32-bit "
+ "word; the KV quantization probe will not restore the PRNG and "
+ "sampling after a load may differ from an unprobed run.",
+ word,
+ )
+ return None
+ converted.append(word & 0xFFFFFFFF)
+ return (converted[0], converted[1])
def _restore_mlx_rng_key(words):
@@ -430,12 +470,19 @@ def _restore_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.
+
+ Unguarded on purpose: the range check in _as_uint32_pair removes the only way
+ this can raise, so there is no failure to swallow, and a blanket except here
+ would be a failure indistinguishable from an intentional no-op.
"""
import mlx.core as mx
if words is None:
return
- mx.random.seed((words[0] << 32) | words[1])
+ pair = _as_uint32_pair(int(words[0]), int(words[1]))
+ if pair is None:
+ return
+ mx.random.seed((pair[0] << 32) | pair[1])
def _kv_quant_probe(language_model, entries, bits):
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index 251cf7119d7..e6e35a68360 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -2927,3 +2927,116 @@ def test_a_vision_override_is_checked_even_when_the_native_render_needs_recovery
assert backend._template_override["applied"] is None
assert backend._template_override["reason"] == mlx_inference.MLX_TEMPLATE_DROPS_IMAGE
assert backend._processor.chat_template == "{{ native }}"
+
+
+def _fake_rng_state(monkeypatch, words):
+ from core.inference import mlx_inference
+
+ _install_fake_mlx(monkeypatch)
+ mx = sys.modules["mlx.core"]
+ seeded = []
+ mx.random = SimpleNamespace(
+ state = _SentinelRandomState(words),
+ seed = lambda value: seeded.append(value),
+ )
+ return mlx_inference, seeded
+
+
+ "words,expected",
+ [
+ ((-1, -2), (0xFFFFFFFF, 0xFFFFFFFE)),
+ ((-2147483648, 5), (0x80000000, 5)),
+ ((0, -1), (0, 0xFFFFFFFF)),
+ ((0, 0), (0, 0)),
+ ((0xFFFFFFFF, 0xFFFFFFFF), (0xFFFFFFFF, 0xFFFFFFFF)),
+ ],
+)
+def test_rng_capture_reinterprets_signed_words(monkeypatch, words, expected):
+ """A negative word is the two's complement of the uint32 mlx stores.
+
+ Reinterpreting it loses nothing, and it is what keeps the seed inside the
+ uint64 domain. The rewind is deliberately unguarded, which only holds if the
+ words cannot put it out of range; capture does not type-check the state, so
+ this conversion is what makes that true. A raise would land in the probe's
+ finally and replace the probe's own outcome, the failure shape #9478 set out
+ to remove.
+ """
+ mlx_inference, seeded = _fake_rng_state(monkeypatch, words)
+
+ captured = mlx_inference._mlx_rng_key_words()
+ assert captured == expected
+
+ mlx_inference._restore_mlx_rng_key(captured)
+ assert seeded == [(expected[0] << 32) | expected[1]]
+ assert 0 <= seeded[0] < 2**64
+
+
+ "words", [(2**32, 0), (0, 2**32), (2**63, 1), (-(2**31) - 1, 0), (0, -(2**40))]
+)
+def test_rng_capture_declines_words_that_are_not_32_bit(monkeypatch, words):
+ """Masking these would be worse than declining them.
+
+ (2**32, 0) masks to (0, 0): a key we cannot represent becomes a plausible
+ wrong one, the probe reports success, and sampling silently diverges from an
+ unprobed run. Declining is the outcome the caller already handles, and it is
+ the only one that says so out loud.
+ """
+ mlx_inference, seeded = _fake_rng_state(monkeypatch, words)
+ warnings = _capture_rng_warnings(monkeypatch, mlx_inference)
+
+ assert mlx_inference._mlx_rng_key_words() is None
+ assert any("32-bit word" in w for w in warnings), warnings
+
+ # The rewind must stay a no-op on the value capture actually returns, and
+ # total besides: handed these words directly it declines rather than raising
+ # into the probe's finally, and never seeds a wrong key.
+ mlx_inference._restore_mlx_rng_key(None)
+ mlx_inference._restore_mlx_rng_key(words)
+ assert seeded == []
+
+
+def _capture_rng_warnings(monkeypatch, mlx_inference):
+ """Collect this module's warnings. It logs through structlog, which caplog
+ does not see."""
+ warnings = []
+ monkeypatch.setattr(
+ mlx_inference.logger,
+ "warning",
+ lambda msg, *args, **kwargs: warnings.append(msg % args if args else msg),
+ )
+ return warnings
+
+
[email protected]("n", [1, 3, 4])
+def test_rng_capture_reports_a_key_that_is_not_two_words(monkeypatch, n):
+ """Returning a bare None would leave the probe silently not restoring, which
+ is the same shape of silent divergence the item assignment used to cause,
+ just moved from the write to the read."""
+ from core.inference import mlx_inference
+
+ _install_fake_mlx(monkeypatch)
+ mx = sys.modules["mlx.core"]
+ mx.random = SimpleNamespace(
+ state = _SentinelRandomState(tuple(range(n))),
+ seed = lambda value: None,
+ )
+ warnings = _capture_rng_warnings(monkeypatch, mlx_inference)
+
+ assert mlx_inference._mlx_rng_key_words() is None
+ assert any("random key" in w for w in warnings), warnings
+
+
+def test_rng_capture_stays_quiet_when_the_state_cannot_be_read(monkeypatch):
+ """An unreadable state is an intentional no-op, not a surprise. Warning on it
+ every call would train operators to ignore the warning that matters."""
+ from core.inference import mlx_inference
+
+ _install_fake_mlx(monkeypatch)
+ mx = sys.modules["mlx.core"]
+ mx.random = SimpleNamespace(state = lambda: {"counter": 0}, seed = lambda value: None)
+ warnings = _capture_rng_warnings(monkeypatch, mlx_inference)
+
+ assert mlx_inference._mlx_rng_key_words() is None
+ assert warnings == []