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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: name what is keeping Train off on Apple Silicon (#8303)
Daniel Han34ee2bf1fa86
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex a1328708463..3301453a270 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1324,8 +1324,8 @@ async def _await_hardware_detection(budget: float) -> bool:return True-def _hardware_snapshot() -> Optional[tuple[bool, Optional[str]]]:- """``(chat_only, chat_only_reason)`` if detection is settled, else ``None``.+def _hardware_snapshot() -> Optional[tuple[bool, Optional[str], Optional[str]]]:+ """``(chat_only, chat_only_reason, chat_only_detail)`` if detection is settled, else ``None``.A seqlock read rather than ``_DETECT_LOCK``: that lock would park the endpoint for thewhole torch import, the stall this startup path removes. A forced re-detect clears the@@ -1344,12 +1344,16 @@ def _hardware_snapshot() -> Optional[tuple[bool, Optional[str]]]:device = _hw_module.DEVICEchat_only = bool(_hw_module.CHAT_ONLY)reason = getattr(_hw_module, "CHAT_ONLY_REASON", None)+ # Inside the guarded read, with the reason it belongs to. Read after it, a forced+ # re-detect starting in between would pair this reply's reason with a detail from+ # a different pass, or with none at all.+ detail = getattr(_hw_module, "CHAT_ONLY_DETAIL", None)if (device is not Noneand _hw_module.DETECTION_COMPLETE.is_set()and _hw_module.DETECTION_GENERATION == generation):- return chat_only, reason+ return chat_only, reason, detailreturn None@@ -1593,6 +1597,12 @@ async def health_check(request: Request):# Why chat_only is set; fingerprints the host, so keep it authed. One snapshot for all three.authed["chat_only"] = snapshot[0]authed["chat_only_reason"] = snapshot[1]+ # What specifically blocked that reason, when detection recorded one. Only the MLX+ # gate does today, and only because it is all-or-nothing: without it the greyed-out+ # Train row can only say "run `unsloth studio update`", which is no help to someone+ # whose update has already run and left one package behind. From the snapshot, so it+ # cannot come from a different detection pass than the reason beside it.+ authed["chat_only_detail"] = snapshot[2]authed["device_type"] = device_type# base predates the bearer await; never ship "detecting" beside a measurement.authed.pop("hardware_detecting", None)diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 0eff3b7208e..88e4b0a6ab6 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -431,6 +431,10 @@ worker.is_apple_silicon = lambda: Truehardware.is_apple_silicon = lambda: Truehardware._has_torch = lambda: Falsemlx_repair._mlx_versions_satisfy_minimums = lambda: True+# The fake mlx packages have no dist-info, so the version check has to be stood down at+# the level the gate reads: it now asks for the blocker LIST, since the same measurement+# both decides the verdict and explains it.+mlx_repair._mlx_version_blockers = lambda: []transformers_version._VENV_T5_530_DIR = os.environ["SIDECAR"]transformers_version._ensure_venv_t5_530_exists = lambda: Truediff --git a/studio/backend/tests/test_mlx_stack_blockers.py b/studio/backend/tests/test_mlx_stack_blockers.pynew file mode 100644index 00000000000..b7e13d9eaa1--- /dev/null+++ b/studio/backend/tests/test_mlx_stack_blockers.py@@ -0,0 +1,374 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The MLX gate has to say what it is unhappy about.++`mlx_unavailable` is a single verdict covering three packages and four runtime+imports, and the greyed-out Train row could only answer it with "run `unsloth+studio update`". That is a dead end for the usual cause: an update that ran, and+a resolver backtrack that left one package missing or too old for the pinned+transformers. These cover the blocker list that message is built from.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import utils.mlx_repair as mr # noqa: E402+++def _fake_versions(monkeypatch, installed: dict[str, str]):+ """Report `installed` as the distributions present, and nothing else."""+ from importlib.metadata import PackageNotFoundError++ def version(name: str) -> str:+ if name in installed:+ return installed[name]+ raise PackageNotFoundError(name)++ monkeypatch.setattr("importlib.metadata.version", version)+++def test_a_healthy_stack_reports_no_blockers(monkeypatch):+ _fake_versions(monkeypatch, {"mlx": "0.30.0", "mlx-lm": "0.30.0", "mlx-vlm": "0.5.0"})+ monkeypatch.setattr(mr, "_mlx_runtime_import_blocker", lambda: None)+ assert mr.mlx_stack_blockers() == []+ assert mr.mlx_stack_available() is True+++def test_a_missing_package_is_named_with_the_version_it_needs(monkeypatch):+ _fake_versions(monkeypatch, {"mlx": "0.30.0", "mlx-lm": "0.30.0"})+ monkeypatch.setattr(mr, "_mlx_runtime_import_blocker", lambda: None)+ blockers = mr.mlx_stack_blockers()+ assert any("mlx-vlm is not installed" in blocker for blocker in blockers)+ assert any("0.4.4" in blocker for blocker in blockers)+ assert mr.mlx_stack_available() is False+++def test_a_backtracked_package_names_the_version_it_found(monkeypatch):+ # The reported shape: present, importable, and too old for VLM Train/Export.+ _fake_versions(monkeypatch, {"mlx": "0.30.0", "mlx-lm": "0.30.0", "mlx-vlm": "0.1.0"})+ monkeypatch.setattr(mr, "_mlx_runtime_import_blocker", lambda: None)+ blockers = mr.mlx_stack_blockers()+ assert blockers == ["mlx-vlm 0.1.0 is older than 0.4.4"]+++def test_every_bad_package_is_listed_not_just_the_first(monkeypatch):+ _fake_versions(monkeypatch, {"mlx": "0.1.0"})+ monkeypatch.setattr(mr, "_mlx_runtime_import_blocker", lambda: None)+ blockers = mr.mlx_stack_blockers()+ assert len(blockers) == 3, blockers+++def test_an_import_that_raises_is_reported_with_its_error(monkeypatch):+ # Versions satisfied but the module will not load, which is what a mlx-vlm+ # built against a different transformers looks like from here.+ _fake_versions(monkeypatch, {"mlx": "0.30.0", "mlx-lm": "0.30.0", "mlx-vlm": "0.5.0"})++ def explode(module: str):+ raise ImportError("cannot import name 'AutoProcessor' from 'transformers'")++ monkeypatch.setattr(mr.importlib, "import_module", explode)+ blockers = mr.mlx_stack_blockers()+ assert len(blockers) == 1+ assert "does not import" in blockers[0]+ assert "AutoProcessor" in blockers[0]+ assert mr.mlx_stack_available() is False+++def test_versions_are_checked_before_imports(monkeypatch):+ """A too-old package must be named without loading it into this process."""+ _fake_versions(monkeypatch, {"mlx": "0.30.0", "mlx-lm": "0.30.0", "mlx-vlm": "0.1.0"})++ def never(module: str):+ raise AssertionError("imported a package the version check already rejected")++ monkeypatch.setattr(mr.importlib, "import_module", never)+ assert mr.mlx_stack_blockers() == ["mlx-vlm 0.1.0 is older than 0.4.4"]+++def test_the_detail_line_never_raises_and_stays_short(monkeypatch):+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "_MLX_BLOCKERS_MEASURED", None)++ def explode() -> list[str]:+ raise RuntimeError("no")++ monkeypatch.setattr(mr, "mlx_stack_blockers", explode)+ assert hw._mlx_stack_detail() is None++ monkeypatch.setattr(mr, "mlx_stack_blockers", lambda: [])+ assert hw._mlx_stack_detail() is None++ monkeypatch.setattr(mr, "mlx_stack_blockers", lambda: ["a", "b", "c", "d"])+ detail = hw._mlx_stack_detail()+ assert detail == "a; b; c"++[email protected]("reason", ["intel_mac", "no_gpu", "detection_failed", None])+def test_only_the_mlx_verdict_carries_a_detail(monkeypatch, reason):+ """Nothing else has anything specific to add, so nothing else may claim to."""+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", reason)+ monkeypatch.setattr(hw, "CHAT_ONLY_DETAIL", None)+ assert hw.CHAT_ONLY_DETAIL is None+++# The detail only means anything beside the reason it explains, so it travels with it+# through every place the verdict is saved, restored, discarded or read.+def test_a_failed_forced_redetect_restores_the_detail(monkeypatch):+ """detect_hardware() puts back the verdict a raising pass clobbered, detail included.++ Without it the restored verdict is still mlx_unavailable but has lost the blocker,+ so the row goes back to the generic message this change exists to replace.+ """+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU)+ monkeypatch.setattr(hw, "CHAT_ONLY", True)+ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", "mlx_unavailable")+ monkeypatch.setattr(hw, "CHAT_ONLY_DETAIL", "mlx-vlm 0.1.0 is older than 0.4.4")+ hw.DETECTION_COMPLETE.set()++ def explode():+ # A pass clears the verdict before it probes; this one dies in between.+ hw.CHAT_ONLY_REASON = None+ hw.CHAT_ONLY_DETAIL = None+ raise RuntimeError("probe died")++ monkeypatch.setattr(hw, "_detect_hardware_locked", explode)+ with pytest.raises(RuntimeError):+ hw.detect_hardware()++ assert hw.CHAT_ONLY_REASON == "mlx_unavailable"+ assert hw.CHAT_ONLY_DETAIL == "mlx-vlm 0.1.0 is older than 0.4.4"+++def test_a_discarded_verdict_takes_the_detail_with_it(monkeypatch):+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", "mlx_unavailable")+ monkeypatch.setattr(hw, "CHAT_ONLY_DETAIL", "mlx-lm is not installed (needs >=0.22.0)")+ hw._discard_detection_locked()+ assert hw.CHAT_ONLY_REASON is None+ assert hw.CHAT_ONLY_DETAIL is None+++def test_health_reads_the_detail_inside_the_guarded_snapshot(monkeypatch):+ """A forced re-detect starting mid-read must not pair one pass's reason with another's+ detail, which is what reading the global after the snapshot allowed."""+ import main++ monkeypatch.setattr(main._hw_module, "DEVICE", main._hw_module.DeviceType.CPU)+ monkeypatch.setattr(main._hw_module, "CHAT_ONLY", True)+ monkeypatch.setattr(main._hw_module, "CHAT_ONLY_REASON", "mlx_unavailable")+ monkeypatch.setattr(main._hw_module, "CHAT_ONLY_DETAIL", "mlx-vlm 0.1.0 is older than 0.4.4")+ main._hw_module.DETECTION_COMPLETE.set()++ snapshot = main._hardware_snapshot()+ assert snapshot is not None+ assert len(snapshot) == 3, "the detail has to come out of the same guarded read"+ assert snapshot[1] == "mlx_unavailable"+ assert snapshot[2] == "mlx-vlm 0.1.0 is older than 0.4.4"++ # A later pass clearing the globals cannot change what this snapshot reports.+ monkeypatch.setattr(main._hw_module, "CHAT_ONLY_DETAIL", None)+ assert snapshot[2] == "mlx-vlm 0.1.0 is older than 0.4.4"+++# The gate and the detail ask the same question, so it is asked once. On the host that+# needs the detail the mlx imports are the ones that hang, and this module already treats+# them as able to park indefinitely; asking twice there is what a second call costs.+def test_the_gate_measures_the_stack_once(monkeypatch):+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "_MLX_BLOCKERS_MEASURED", None)+ calls: list[int] = []++ def counted() -> list[str]:+ calls.append(1)+ return ["mlx-vlm 0.1.0 is older than 0.4.4"]++ monkeypatch.setattr(mr, "mlx_stack_blockers", counted)+ assert hw._has_usable_mlx_stack() is False+ assert hw._mlx_stack_detail() == "mlx-vlm 0.1.0 is older than 0.4.4"+ assert len(calls) == 1, f"the stack was probed {len(calls)} times for one verdict"+++def test_a_measurement_is_used_once_and_not_kept(monkeypatch):+ """A list left over from an earlier pass describes a stack since re-measured."""+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "_MLX_BLOCKERS_MEASURED", None)+ monkeypatch.setattr(mr, "mlx_stack_blockers", lambda: ["mlx is not installed"])+ hw._has_usable_mlx_stack()+ assert hw._mlx_stack_detail() == "mlx is not installed"+ assert hw._MLX_BLOCKERS_MEASURED is None++ # Nothing measured, so the detail measures for itself rather than reusing the above.+ monkeypatch.setattr(mr, "mlx_stack_blockers", lambda: ["mlx-lm is not installed"])+ assert hw._mlx_stack_detail() == "mlx-lm is not installed"+++def test_a_healthy_gate_still_reads_as_usable(monkeypatch):+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "_MLX_BLOCKERS_MEASURED", None)+ monkeypatch.setattr(mr, "mlx_stack_blockers", lambda: [])+ assert hw._has_usable_mlx_stack() is True+++def test_an_unreadable_gate_falls_back_to_the_bare_import(monkeypatch):+ """mlx_repair should always import; a host where it cannot is not forced chat-only."""+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "_MLX_BLOCKERS_MEASURED", ["stale"])++ def explode() -> list[str]:+ raise RuntimeError("mlx_repair is unimportable")++ monkeypatch.setattr(mr, "mlx_stack_blockers", explode)+ monkeypatch.setattr(hw, "_has_mlx", lambda: True)+ assert hw._has_usable_mlx_stack() is True+ # And it published nothing, rather than leaving the stale list to be read as this+ # pass's answer.+ assert hw._MLX_BLOCKERS_MEASURED is None+++# A blocker line goes into /api/health and into the Train row's native tooltip. Neither+# renders a paragraph, and a dyld failure lists every path it tried.+def test_a_long_import_error_is_folded_to_one_bounded_line(monkeypatch):+ _fake_versions(monkeypatch, {"mlx": "0.30.0", "mlx-lm": "0.30.0", "mlx-vlm": "0.5.0"})++ def explode(module: str):+ raise ImportError(+ "dlopen failed:\n tried: '/opt/one/lib.so' (no such file)\n"+ " tried: '/opt/two/lib.so' (mach-o, but wrong architecture)\n" + "x" * 400+ )++ monkeypatch.setattr(mr.importlib, "import_module", explode)+ blocker = mr.mlx_stack_blockers()[0]+ assert "\n" not in blocker+ assert len(blocker) < 200, f"{len(blocker)} chars reaches the tooltip: {blocker}"+ assert blocker.endswith("...)"), blocker+ # Still says which module and which error, which is the whole point of the line.+ assert blocker.startswith("mlx.core does not import (ImportError:")+++def test_a_malformed_installed_version_is_bounded_too(monkeypatch):+ """Version metadata is read from disk, and an interrupted install can leave junk."""+ junk = "1.0\n" + "y" * 500+ _fake_versions(monkeypatch, {"mlx": junk, "mlx-lm": "0.30.0", "mlx-vlm": "0.5.0"})+ monkeypatch.setattr(mr, "_mlx_runtime_import_blocker", lambda: None)+ blocker = mr.mlx_stack_blockers()[0]+ assert "\n" not in blocker+ assert len(blocker) < 200, f"{len(blocker)} chars reaches the tooltip"+ assert blocker.startswith("mlx 1.0 y")+++# A repair that installed and then failed its own validation has still changed the+# environment, so the verdict beside it was measured against a stack that no longer exists:+# it can name a package the install has since put there.+def _fake_hardware(monkeypatch, calls: list[str]):+ """Stand the real hardware module's re-detection down, keeping the module identity."""+ from contextlib import nullcontext++ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "detect_hardware", lambda: calls.append("detect"))+ monkeypatch.setattr(hw, "owning_detection_epoch", lambda epoch: nullcontext())+ monkeypatch.setattr(hw, "current_detection_epoch", lambda: None)+ return hw+++def test_a_repair_that_failed_validation_still_remeasures(monkeypatch):+ called: list[str] = []+ _fake_hardware(monkeypatch, called)+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda: False)+ monkeypatch.setattr(mr, "_environment_mutated", True)+ mr._run_repair_and_redetect()+ assert called == ["detect"], "the stale detail was left describing a replaced stack"+++def test_a_repair_that_never_ran_does_not_remeasure(monkeypatch):+ """Nothing changed, so re-running the mlx imports would cost latency for nothing."""+ called: list[str] = []+ _fake_hardware(monkeypatch, called)+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda: False)+ monkeypatch.setattr(mr, "_environment_mutated", False)+ mr._run_repair_and_redetect()+ assert called == []+++def test_a_successful_repair_still_remeasures(monkeypatch):+ called: list[str] = []+ _fake_hardware(monkeypatch, called)+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda: True)+ monkeypatch.setattr(mr, "_environment_mutated", True)+ mr._run_repair_and_redetect()+ assert called == ["detect"]+++# uv passes every package with --reinstall-package, so it removes and replaces them as it+# goes: a timeout or a non-zero exit part way through has already changed the stack.+ "outcome",+ ["timeout", "nonzero"],+)+def test_an_install_that_died_part_way_still_counts_as_mutating(monkeypatch, outcome):+ import subprocess as sp++ monkeypatch.setattr(mr, "_environment_mutated", False)+ monkeypatch.setattr(mr, "_uv_install_cmd", lambda *a, **k: ["uv", "pip", "install"])+ monkeypatch.setattr(mr, "_transformers_constraint_args", lambda: ([], None))+ monkeypatch.setattr(mr, "_mlx_install_env", dict)++ def run(*a, **k):+ if outcome == "timeout":+ raise sp.TimeoutExpired(cmd = "uv", timeout = 1)+ return sp.CompletedProcess(args = "uv", returncode = 1, stdout = "boom")++ monkeypatch.setattr(mr.subprocess, "run", run)+ assert mr.attempt_mlx_repair() is False+ assert mr._environment_mutated is True, (+ "a half-applied reinstall leaves the pre-repair detail describing a stack that "+ "is no longer on disk"+ )+++def test_a_venv_uv_refuses_is_not_marked_mutated(monkeypatch):+ """uv gave up before resolving an interpreter, so it installed nothing."""+ import subprocess as sp++ monkeypatch.setattr(mr, "_environment_mutated", False)+ monkeypatch.setattr(mr, "_uv_install_cmd", lambda *a, **k: ["uv", "pip", "install"])+ monkeypatch.setattr(mr, "_transformers_constraint_args", lambda: ([], None))+ monkeypatch.setattr(mr, "_mlx_install_env", dict)+ monkeypatch.setattr(+ mr.subprocess,+ "run",+ lambda *a, **k: sp.CompletedProcess(+ args = "uv",+ returncode = 2,+ stdout = mr._UNRESOLVED_PYTHON_MARKER + " at /x",+ ),+ )+ assert mr.attempt_mlx_repair() is False+ assert mr._environment_mutated is False+++def test_uv_missing_never_marks_the_environment(monkeypatch):+ monkeypatch.setattr(mr, "_environment_mutated", False)+ monkeypatch.setattr(mr, "_uv_install_cmd", lambda *a, **k: None)+ monkeypatch.setattr(mr, "_transformers_constraint_args", lambda: ([], None))+ assert mr.attempt_mlx_repair() is False+ assert mr._environment_mutated is Falsediff --git a/studio/backend/tests/test_warm_window_review_fixes.py b/studio/backend/tests/test_warm_window_review_fixes.pyindex 6b20441f968..94ed3f103f3 100644--- a/studio/backend/tests/test_warm_window_review_fixes.py+++ b/studio/backend/tests/test_warm_window_review_fixes.py@@ -661,7 +661,9 @@ def test_health_snapshot_returns_a_settled_verdict(monkeypatch):monkeypatch.setattr(hw_mod, "CHAT_ONLY", True, raising = False)monkeypatch.setattr(hw_mod, "CHAT_ONLY_REASON", "mlx_unavailable", raising = False)hw_mod.DETECTION_COMPLETE.set()- assert main_mod._hardware_snapshot() == (True, "mlx_unavailable")+ # Three items: the detail travels with the reason it explains, out of the same+ # guarded read, so the two can never be paired across different detection passes.+ assert main_mod._hardware_snapshot() == (True, "mlx_unavailable", None)def test_health_rereads_the_verdict_after_authentication():diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 4422b478dc4..f951596aeb9 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -78,6 +78,12 @@ CHAT_ONLY: bool = True # No CUDA GPU -> GGUF chat only (Mac, CPU-only, etc.)# (the usual cause of "Train/Export greyed out" on Macs after a reinstall dropped MLX);# "intel_mac": Intel Mac (no PyTorch/MLX); "no_gpu": CPU-only non-Mac host.CHAT_ONLY_REASON: Optional[str] = None+# What exactly blocked the reason above, when there is something specific to say. Only+# "mlx_unavailable" sets it today: the gate is all-or-nothing across mlx, mlx-lm and+# mlx-vlm, so "run `unsloth studio update`" was the whole message even to someone who+# had just run it. Naming the package that is missing, too old, or refusing to import+# is the difference between a dead end and a fix. Never shown on its own.+CHAT_ONLY_DETAIL: Optional[str] = NoneIS_ROCM: bool = False # True when running on AMD ROCm (HIP) -- routes GPU monitoring to amd.py# Detection has concurrent callers (the warm thread plus any early get_device()).@@ -126,10 +132,11 @@ def owning_detection_epoch(epoch: Optional[int]):def _discard_detection_locked() -> None:"""Drop a verdict produced for an epoch that has been retired."""- global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM+ global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, CHAT_ONLY_DETAIL, IS_ROCMDEVICE = NoneCHAT_ONLY = TrueCHAT_ONLY_REASON = None+ CHAT_ONLY_DETAIL = NoneIS_ROCM = FalseDETECTION_COMPLETE.clear()@@ -260,22 +267,68 @@ def _has_mlx() -> bool:return False+# What the last gate call measured, so the CPU fallback can name a blocker without+# running the mlx imports a second time. This module already treats those imports as+# able to park indefinitely on a broken stack, and that is exactly the host that needs+# the detail, so a second run there can double detection latency or keep the pass from+# reaching the repair scheduler. Written and consumed inside one locked detection pass.+_MLX_BLOCKERS_MEASURED: Optional[list[str]] = None++def _has_usable_mlx_stack() -> bool:"""True only when the FULL Unsloth MLX training/export stack is usable(mlx + mlx-lm + mlx-vlm at the minimum versions unsloth-zoo requires), notjust a bare ``import mlx.core``. A backtracked/old mlx-vlm still imports butbreaks VLM Train/Export, so the training gate must match the self-heal's own- criterion (utils.mlx_repair.mlx_stack_available) -- otherwise detect_hardware- would enable Train/Export on exactly the inadequate stack the MLX self-heal- is trying to repair, leaving the user with greyed-in-but-broken buttons."""+ criterion (utils.mlx_repair) -- otherwise detect_hardware would enable+ Train/Export on exactly the inadequate stack the MLX self-heal is trying to+ repair, leaving the user with greyed-in-but-broken buttons.++ Asked as "no blockers" rather than through mlx_stack_available(), which is the+ same question: both run the version checks before the imports, in the same order,+ and stop at the first failure. Reading the list is what lets the answer be+ explained without measuring it again."""+ global _MLX_BLOCKERS_MEASURED+ _MLX_BLOCKERS_MEASURED = Nonetry:- from utils.mlx_repair import mlx_stack_available- return mlx_stack_available()+ from utils.mlx_repair import mlx_stack_blockers+ blockers = mlx_stack_blockers()except Exception as exc:# mlx_repair should always import; if it somehow cannot, fall back to the# bare import check rather than forcing a working host into chat-only.logger.debug("MLX stack availability check failed, using bare import: %s", exc)return _has_mlx()+ _MLX_BLOCKERS_MEASURED = blockers+ return not blockers+++def _mlx_stack_detail() -> Optional[str]:+ """One line naming what the MLX gate is unhappy about, or None if it cannot tell.++ Never raises and never re-runs the gate's own verdict: this only describes a+ verdict already reached, so a failure here costs a sentence, not Train.++ Takes what the gate measured when there is any. Measuring again is the fallback+ for a caller that reached here without one, e.g. a test driving this alone.+ """+ global _MLX_BLOCKERS_MEASURED+ blockers = _MLX_BLOCKERS_MEASURED+ # Consumed, not kept: a list left behind by an earlier pass describes a stack that+ # has since been re-measured, and the whole point of the detail is that it belongs+ # to the verdict beside it.+ _MLX_BLOCKERS_MEASURED = None+ if blockers is None:+ try:+ from utils.mlx_repair import mlx_stack_blockers+ blockers = mlx_stack_blockers()+ except Exception as exc:+ logger.debug("MLX blocker detail unavailable: %s", exc)+ return None+ if not blockers:+ # The gate said no and the detail says yes, which means the stack changed+ # under us. Saying nothing beats naming a blocker that is no longer there.+ return None+ return "; ".join(blockers[:3])def verdict_pending_mlx_repair(chat_only: bool, reason: Optional[str]) -> bool:@@ -360,7 +413,7 @@ def detect_hardware() -> DeviceType:4. MLX (Apple Silicon via MLX framework)5. CPU (fallback)"""- global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM, DETECTION_GENERATION+ global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, CHAT_ONLY_DETAIL, IS_ROCM, DETECTION_GENERATIONwith _DETECT_LOCK:# A forced pass mutates the globals partway through; leaving the event set lets# /api/health serve that as settled, so the sidebar MLX poll caches reason=None,@@ -369,7 +422,7 @@ def detect_hardware() -> DeviceType:# Snapshot the whole verdict, not just the event: a raise mid-pass leaves a# half-written answer the autorepair path swallows, and losing "mlx_unavailable"# stops the sidebar poll for good.- published = (DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM)+ published = (DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, CHAT_ONLY_DETAIL, IS_ROCM)# Owning epoch first, current only as a fallback. The MLX self-heal calls this# after a pip install that can outlast the lifespan; reading current would adopt# the epoch shutdown moved to, so the next lifespan finds DEVICE set and skips@@ -391,7 +444,7 @@ def detect_hardware() -> DeviceType:# cleared, and the next lifespan would treat that as measured._discard_detection_locked()raise- DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM = published+ DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, CHAT_ONLY_DETAIL, IS_ROCM = published# Restore rather than leave it clear: start_background_detection() declines# once DEVICE is set, so an unset event keeps health provisional forever.if was_complete:@@ -419,7 +472,7 @@ def ensure_hardware_detected(epoch: Optional[int] = None) -> DeviceType:Thread.start(), since the thread can be scheduled after a shutdown retired it andreading it here would bind the pass to the retirement it must lose to. Direct callerspass nothing and own the current epoch."""- global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, DETECTION_GENERATION+ global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, CHAT_ONLY_DETAIL, DETECTION_GENERATIONwith _DETECT_LOCK:if epoch is None:# A nested read inside an owning scope belongs to that pass, not to whatever@@ -446,6 +499,8 @@ def ensure_hardware_detected(epoch: Optional[int] = None) -> DeviceType:DEVICE = DeviceType.CPUCHAT_ONLY = TrueCHAT_ONLY_REASON = "detection_failed"+ # The pass may have got as far as recording one for a different reason.+ CHAT_ONLY_DETAIL = None# Inside the branch: the orchestrator rebuilds its curated defaults whenever this# counter moves, so bumping on the cached path caused needless rebuilds. Forced# detect_hardware() bumps it too.@@ -467,9 +522,12 @@ def ensure_hardware_detected(epoch: Optional[int] = None) -> DeviceType:def _detect_hardware_locked() -> DeviceType:"""detect_hardware() body. Call only with _DETECT_LOCK held."""- global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM+ global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, CHAT_ONLY_DETAIL, IS_ROCM+ global _MLX_BLOCKERS_MEASUREDCHAT_ONLY = True # reset -- only CUDA/ROCm/XPU/MLX sets it to FalseCHAT_ONLY_REASON = None+ CHAT_ONLY_DETAIL = None+ _MLX_BLOCKERS_MEASURED = NoneIS_ROCM = False# Probe torch once per pass: a failed probe is expensive and a second can disagree.@@ -572,10 +630,12 @@ def _detect_hardware_locked() -> DeviceType:# too old, or broken. This is usually an environment problem recoverable# with `unsloth studio update`.CHAT_ONLY_REASON = "mlx_unavailable"+ CHAT_ONLY_DETAIL = _mlx_stack_detail()logger.warning("Apple Silicon detected but the MLX stack is incomplete or too old; "- "Train/Export disabled (chat-only). Run `unsloth studio update` to "- "restore MLX training."+ "Train/Export disabled (chat-only)%s Run `unsloth studio update` to "+ "restore MLX training.",+ f" ({CHAT_ONLY_DETAIL})." if CHAT_ONLY_DETAIL else ".",)elif TORCH_IMPORT_ERROR is not None:# torch installed but broken, so this host was never measured. "no_gpu" would lie.diff --git a/studio/backend/utils/mlx_repair.py b/studio/backend/utils/mlx_repair.pyindex 1716cfad59f..0b7da1bd1ae 100644--- a/studio/backend/utils/mlx_repair.py+++ b/studio/backend/utils/mlx_repair.py@@ -132,6 +132,10 @@ _repair_started_at: Optional[float] = None_WORKER_BUDGET_S = _REPAIR_TIMEOUT_S + 300# Indirected so the tests can drive the budget without sleeping through it._repair_clock = time.monotonic+# True once the install subprocess has actually run, which is what tells a repair that+# changed the environment and then failed its own validation apart from one that never+# touched it. Single-writer: the _attempted latch allows one repair per process.+_environment_mutated = Falsedef is_apple_silicon() -> bool:@@ -146,32 +150,93 @@ def mlx_available() -> bool:return False-def _mlx_runtime_imports_available() -> bool:+# An import error is free-form and can be a paragraph: a compiled-against-the-wrong-+# transformers ImportError carries the hint text, and a dyld failure carries a list of+# paths tried, and an interrupted install can leave malformed version metadata behind.+# The blocker line ends up in /api/health and in the Train row's native tooltip, neither+# of which can render a paragraph, so everything read from outside is folded and cut.+# Each piece read from outside, and the finished line. Both, because a blocker can hold+# two of them: a malformed version and the error parsing it are individually short enough+# and together are not.+_BLOCKER_PART_CAP = 80+_BLOCKER_LINE_CAP = 200+++def _bounded(text: str, cap: int = _BLOCKER_PART_CAP) -> str:+ """One line, capped, with an ellipsis marking anything dropped."""+ folded = " ".join(str(text).split())+ if len(folded) > cap:+ folded = folded[: cap - 3].rstrip() + "..."+ return folded+++def _one_line(exc: BaseException) -> str:+ """An exception's message as one bounded line."""+ return _bounded(str(exc))+++def _mlx_runtime_import_blocker() -> Optional[str]:+ """The first runtime import that will not load, and why. None when all do."""for module in _MLX_RUNTIME_IMPORTS:try:importlib.import_module(module)- except Exception:- return False- return True+ except Exception as exc:+ return f"{module} does not import ({type(exc).__name__}: {_one_line(exc)})"+ return None-def _mlx_versions_satisfy_minimums() -> bool:+def _mlx_runtime_imports_available() -> bool:+ return _mlx_runtime_import_blocker() is None+++def _mlx_version_blockers() -> list[str]:+ """Every MLX package that is missing or below the minimum, named."""try:from importlib.metadata import PackageNotFoundErrorfrom importlib.metadata import version as _dist_versionfrom packaging.version import Version- except Exception:- return False+ except Exception as exc:+ return [f"the version check could not run ({type(exc).__name__}: {_one_line(exc)})"]+ blockers: list[str] = []for name, minimum in _MLX_MIN_VERSIONS.items():try:- if Version(_dist_version(name)) < Version(minimum):- return False+ installed = _dist_version(name)except PackageNotFoundError:- return False- except Exception:- return False- return True+ blockers.append(f"{name} is not installed (needs >={minimum})")+ continue+ except Exception as exc:+ blockers.append(f"{name} could not be read ({type(exc).__name__}: {_one_line(exc)})")+ continue+ try:+ if Version(installed) < Version(minimum):+ blockers.append(f"{name} {_bounded(installed)} is older than {minimum}")+ except Exception as exc:+ blockers.append(+ f"{name} {_bounded(installed)} is unreadable "+ f"({type(exc).__name__}: {_one_line(exc)})"+ )+ return blockers+++def _mlx_versions_satisfy_minimums() -> bool:+ return not _mlx_version_blockers()+++def mlx_stack_blockers() -> list[str]:+ """Why this host cannot train with MLX, in the order the gate checks it.++ The gate itself is all-or-nothing, and "run `unsloth studio update`" is no help+ to someone who has just run it: a resolver backtrack leaves a stack that is+ present but unusable, and nothing said which package or which import was the+ problem. Same order as ``mlx_stack_available`` so the two cannot disagree.+ Empty means the stack is usable.+ """+ versions = _mlx_version_blockers()+ if versions:+ return [_bounded(line, _BLOCKER_LINE_CAP) for line in versions]+ blocker = _mlx_runtime_import_blocker()+ return [_bounded(blocker, _BLOCKER_LINE_CAP)] if blocker else []def mlx_stack_available() -> bool:@@ -354,6 +419,7 @@ def attempt_mlx_repair(*, timeout: int = _REPAIR_TIMEOUT_S) -> bool:Best-effort; returns True iff the resulting stack meets unsloth-zoo's minimums(so a backtracked old mlx-vlm is rejected, not accepted). transformers is heldat its pinned version so the install can never upgrade it underneath Unsloth."""+ global _environment_mutated# Prepare the constraint inside the try: this runs on a daemon thread, so an# exception here (e.g. tempfile.mkstemp failing on a full disk or bad TMPDIR)# must leave Unsloth chat-only, not crash the background self-heal thread.@@ -374,6 +440,11 @@ def attempt_mlx_repair(*, timeout: int = _REPAIR_TIMEOUT_S) -> bool:)return Falselogger.info("MLX self-heal: installing %s", ", ".join(MLX_PACKAGES))+ # Before the wait, not after it. Every package is passed with+ # --reinstall-package, so uv removes and replaces them as it goes: a timeout or a+ # non-zero exit part way through leaves a stack neither the one detection measured+ # nor the one asked for. Nothing before this line touches the environment.+ _environment_mutated = Trueresult = subprocess.run(cmd,env = _mlx_install_env(),@@ -406,6 +477,12 @@ def attempt_mlx_repair(*, timeout: int = _REPAIR_TIMEOUT_S) -> bool:# resolve. Only rebuilding the environment fixes it, so name the command# that does. uv's own text says to run `uv venv`, which would build an# environment Unsloth does not manage.+ #+ # uv gave up before resolving an interpreter, so it installed nothing and the+ # stack is exactly as detection last measured it. Take the mark back: a+ # re-detect here would re-run the mlx imports for a verdict that cannot have+ # changed, on a host where those imports are already suspect.+ _environment_mutated = Falselogger.warning("MLX self-heal could not use the Unsloth environment at %s: uv did not ""recognise it as a virtual environment. This usually means the venv's "@@ -430,7 +507,14 @@ def attempt_mlx_repair(*, timeout: int = _REPAIR_TIMEOUT_S) -> bool:def _run_repair_and_redetect(epoch: Optional[int] = None) -> None:- if not attempt_mlx_repair():+ repaired = attempt_mlx_repair()+ # Re-detect after a failed validation too, as long as the install ran. That path has+ # already changed the environment, and the verdict beside it was measured before the+ # change: its detail can name a package the install has since put there, or an import+ # error the install has since replaced. The verdict itself stays chat-only, correctly.+ # A repair that never ran (opted out, uv refused, subprocess died) is skipped, since+ # re-detecting there would re-run the mlx imports on a stack nothing has touched.+ if not repaired and not _environment_mutated:returntry:from utils.hardware import hardware as hw@@ -445,10 +529,17 @@ def _run_repair_and_redetect(epoch: Optional[int] = None) -> None:# existed and the _attempted latch blocks any later repair. Re-detect under# the live epoch, or a now-capable Mac stays chat-only until a restart.hw.detect_hardware()- logger.info(- "MLX self-heal succeeded; Train/Export enabled (reload the page). chat_only=%s",- hw.CHAT_ONLY,- )+ if repaired:+ logger.info(+ "MLX self-heal succeeded; Train/Export enabled (reload the page). chat_only=%s",+ hw.CHAT_ONLY,+ )+ else:+ logger.info(+ "MLX self-heal installed but the stack is still unusable; re-measured so "+ "the reason matches what is now on disk: %s",+ hw.CHAT_ONLY_DETAIL,+ )except Exception as exc: # pragma: no cover - defensivelogger.warning("MLX installed but hardware re-detection failed: %s", exc)diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 222313d04d3..c3c5cfe2694 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -618,6 +618,7 @@ export function AppSidebar() {const chatOnly = usePlatformStore((s) => s.isChatOnly());const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);+ const chatOnlyDetail = usePlatformStore((s) => s.chatOnlyDetail);const detectionDeferred = usePlatformStore((s) => s.detectionDeferred);// Until /api/health answers, `chatOnly` is the browser-platform guess, so every Mac painted// Train and Video blacked out on load and only recovered once the backend reported. Gate the@@ -629,7 +630,13 @@ export function AppSidebar() {const trainDisabledHint: string | undefined = !chatOnlyMeasured? undefined: chatOnlyReason === "mlx_unavailable"- ? "Training needs MLX. Run `unsloth studio update` to enable Train."+ ? // The gate is all-or-nothing across mlx, mlx-lm and mlx-vlm, and a resolver+ // backtrack leaves a stack that is present but unusable. Naming the package+ // that is missing, too old, or refusing to import is what makes this+ // actionable to someone whose `unsloth studio update` has already run.+ chatOnlyDetail+ ? `Training needs MLX: ${chatOnlyDetail}. Run \`unsloth studio update\` to enable Train.`+ : "Training needs MLX. Run `unsloth studio update` to enable Train.": chatOnlyReason === "intel_mac"? "Training needs Apple Silicon or a GPU. Intel Macs are chat-only.": chatOnlyReason === "no_gpu"diff --git a/studio/frontend/src/config/env.ts b/studio/frontend/src/config/env.tsindex cae937205da..45ad41471e4 100644--- a/studio/frontend/src/config/env.ts+++ b/studio/frontend/src/config/env.ts@@ -27,6 +27,10 @@ interface PlatformState {// e.g. "mlx_unavailable" on Apple Silicon -> the UI explains the greyed-out// Train/Export instead of silently disabling them.chatOnlyReason: string | null;+ // What specifically blocked that reason, when the backend can name it. Today only the+ // MLX gate does: it is all-or-nothing across mlx, mlx-lm and mlx-vlm, so without this+ // the greyed-out Train row can only repeat "run `unsloth studio update`".+ chatOnlyDetail: string | null;// From /api/health (authed): live tunnel URL, direct (non-tunnel) base, and// whether the server was launched with --secure.cloudflareUrl: string | null;@@ -63,6 +67,7 @@ export const usePlatformStore = create<PlatformState>()((_, get) => ({// capabilitiesUnknown() first and hold, not gray a tab out on this.chatOnly: localDeviceType === "mac",chatOnlyReason: null,+ chatOnlyDetail: null,cloudflareUrl: null,serverUrl: null,secure: false,@@ -172,7 +177,10 @@ export async function fetchDeviceType(options?: {const deviceType =data.device_type ?? (keepPlatform ? previous.deviceType : detectLocalPlatform());// A still-provisional reply keeps the stored verdict: see resolveVerdict.- const { chatOnly, chatOnlyReason } = resolveVerdict(data, previous);+ const { chatOnly, chatOnlyReason, chatOnlyDetail } = resolveVerdict(+ data,+ previous,+ );// Cache only a server-reported platform. Unauthenticated responses fall// back to the browser platform, which can differ from the host (WSL,// SSH); keeping fetched=false retries once a token exists.@@ -180,6 +188,7 @@ export async function fetchDeviceType(options?: {deviceType,chatOnly,chatOnlyReason,+ chatOnlyDetail,cloudflareUrl: data.cloudflare_url ?? null,serverUrl: data.server_url ?? null,secure: data.secure ?? false,diff --git a/studio/frontend/src/config/hardware-verdict.ts b/studio/frontend/src/config/hardware-verdict.tsindex b5b5bb0c9eb..6ab06253574 100644--- a/studio/frontend/src/config/hardware-verdict.ts+++ b/studio/frontend/src/config/hardware-verdict.ts@@ -9,6 +9,8 @@export type HealthVerdict = {chat_only?: boolean;chat_only_reason?: string | null;+ /** What blocked that reason, when the backend knows something specific. */+ chat_only_detail?: string | null;hardware_detecting?: boolean;hardware_detection_deferred?: boolean;};@@ -16,6 +18,7 @@ export type HealthVerdict = {export type ResolvedVerdict = {chatOnly: boolean;chatOnlyReason: string | null;+ chatOnlyDetail: string | null;};/** True while the backend is still measuring the host, so chat_only is its@@ -64,11 +67,18 @@ export function resolveVerdict(return {chatOnly: data.chat_only ?? true,chatOnlyReason: data.chat_only_reason ?? previous.chatOnlyReason,+ // The detail belongs to the reason, so it travels with it: keeping a stale one+ // beside a new reason would name a blocker for a verdict it never explained.+ chatOnlyDetail:+ data.chat_only_reason === undefined+ ? previous.chatOnlyDetail+ : (data.chat_only_detail ?? null),};}if (isProvisionalVerdict(data)) return previous;return {chatOnly: data.chat_only ?? false,chatOnlyReason: data.chat_only_reason ?? null,+ chatOnlyDetail: data.chat_only_detail ?? null,};}diff --git a/studio/frontend/tests/provisional-hardware-verdict.test.ts b/studio/frontend/tests/provisional-hardware-verdict.test.tsindex 1872e98c251..e363f8823e0 100644--- a/studio/frontend/tests/provisional-hardware-verdict.test.ts+++ b/studio/frontend/tests/provisional-hardware-verdict.test.ts@@ -17,8 +17,8 @@ const { isDetectionDeferred, isProvisionalVerdict, resolveVerdict, videoNavHint"../src/config/hardware-verdict.ts");-const GPU_HOST = { chatOnly: false, chatOnlyReason: null };-const MAC_DEFAULT = { chatOnly: true, chatOnlyReason: null };+const GPU_HOST = { chatOnly: false, chatOnlyReason: null, chatOnlyDetail: null };+const MAC_DEFAULT = { chatOnly: true, chatOnlyReason: null, chatOnlyDetail: null };test("a detecting reply is provisional, a settled one is not", () => {assert.equal(isProvisionalVerdict({ hardware_detecting: true }), true);@@ -45,7 +45,7 @@ test("a provisional reply does not send a GPU host to chat-only", () => {test("a provisional reply does not clear a reason the UI is explaining", () => {const resolved = resolveVerdict({ chat_only: true, hardware_detecting: true },- { chatOnly: true, chatOnlyReason: "mlx_unavailable" },+ { chatOnly: true, chatOnlyReason: "mlx_unavailable", chatOnlyDetail: null },);assert.equal(resolved.chatOnlyReason,@@ -102,7 +102,7 @@ test("a deferred verdict falls back to the backend's conservative default", () =hardware_detection_deferred: true,};assert.equal(- resolveVerdict(deferred, { chatOnly: false, chatOnlyReason: null }).chatOnly,+ resolveVerdict(deferred, { chatOnly: false, chatOnlyReason: null, chatOnlyDetail: null }).chatOnly,true,"a never-settling reply left the optimistic platform default in place",);@@ -115,7 +115,7 @@ test("a deferred verdict does not clear a reason the UI is explaining", () => {hardware_detection_deferred: true,};assert.equal(- resolveVerdict(deferred, { chatOnly: true, chatOnlyReason: "mlx_unavailable" })+ resolveVerdict(deferred, { chatOnly: true, chatOnlyReason: "mlx_unavailable", chatOnlyDetail: null }).chatOnlyReason,"mlx_unavailable","the sidebar recovery poll only runs while it reads mlx_unavailable",diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 8e0a44942b1..695aa4a2486 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport globimport importlib.util+import jsonimport osimport platformimport re@@ -3787,6 +3788,48 @@ def _has_working_git() -> bool:return False+_MLX_HEALTH_PROBE = (+ "import json, sys;"+ "sys.path.insert(0, sys.argv[1]);"+ "from utils.mlx_repair import mlx_stack_blockers;"+ "print(json.dumps(mlx_stack_blockers()))"+)+++def _report_mlx_stack_health() -> None:+ """Name what would keep Train off on this Apple Silicon host, if anything.++ Advisory only: the install has already succeeded, chat still works, and the+ background self-heal gets another go at startup. It just must not be silent,+ which is the whole of the reported "Train is blacked out after an update".++ Run out of process: the probe imports mlx, mlx_lm and mlx_vlm, and a half+ installed one of those can abort rather than raise.+ """+ backend = str(SCRIPT_DIR / "backend")+ try:+ probe = subprocess.run(+ [sys.executable, "-c", _MLX_HEALTH_PROBE, backend],+ capture_output = True,+ text = True,+ timeout = 180,+ **_windows_hidden_subprocess_kwargs(),+ )+ blockers = json.loads(probe.stdout.strip() or "null")+ except Exception as exc: # noqa: BLE001 - advisory, never fail the install+ _step("mlx", f"could not verify the MLX stack ({exc})", _dim)+ return+ if blockers is None:+ _step("mlx", "could not verify the MLX stack", _dim)+ return+ if not blockers:+ _step("mlx", "training stack ready")+ return+ _step("mlx", "Train and Export will stay off until this is resolved:", _cyan)+ for blocker in blockers:+ _step("", blocker, _cyan)++def install_python_stack() -> int:global USE_UV, _STEP, _TOTAL, _PROGRESS_LINE_ACTIVE_STEP = 0@@ -4246,6 +4289,21 @@ def install_python_stack() -> int:)return 1+ # 16. Apple Silicon: say so when the MLX stack this install just laid down is not+ # one Train can use. The gate is all-or-nothing across mlx, mlx-lm and mlx-vlm, and+ # a resolver backtrack (or an mlx-vlm built against a different transformers) leaves+ # packages present but unusable. Without this the install reports success and the app+ # silently comes up chat-only, telling the user to run the update that has just+ # finished.+ #+ # AFTER the manifest, not before it. The probe is advisory and out of process, and on+ # the host it exists for the imports are the ones that hang, so it can hold its full+ # timeout; run ahead of the manifest, a kill during that wait leaves every dependency+ # step done and no record of it, and verify-install, the desktop preflight and the+ # setup fast path all then call a complete install incomplete.+ if IS_MAC_ARM and not NO_TORCH:+ _report_mlx_stack_health()+_step(_LABEL, "installed")return 0diff --git a/tests/studio/test_hardware_dispatch_matrix.py b/tests/studio/test_hardware_dispatch_matrix.pyindex 19619bc318d..cd2173f587a 100644--- a/tests/studio/test_hardware_dispatch_matrix.py+++ b/tests/studio/test_hardware_dispatch_matrix.py@@ -204,16 +204,20 @@ def spoof_hardware(monkeypatch):fake_mlx.core = fake_mlx_coremonkeypatch.setitem(sys.modules, "mlx", fake_mlx)monkeypatch.setitem(sys.modules, "mlx.core", fake_mlx_core)- # detect_hardware now gates MLX on the full stack via- # utils.mlx_repair.mlx_stack_available() (it imports mlx_lm/mlx_vlm and- # checks dist versions), which faking only mlx.core cannot satisfy. An- # mlx profile means a complete, healthy stack, so model that here;- # mlx_stack_available's own internals are covered by test_mlx_repair.py.+ # detect_hardware gates MLX on the full stack via utils.mlx_repair (it+ # imports mlx_lm/mlx_vlm and checks dist versions), which faking only+ # mlx.core cannot satisfy. An mlx profile means a complete, healthy stack,+ # so model that here; the internals are covered by test_mlx_repair.py.+ # Both entry points, because the gate asks for the blocker LIST: one+ # measurement decides the verdict and explains it. Stubbing only+ # mlx_stack_available() runs the real check against a Linux runner with no+ # MLX distributions, so the Apple Silicon profile detects CPU.if str(STUDIO_BACKEND) not in sys.path:sys.path.insert(0, str(STUDIO_BACKEND))import utils.mlx_repair as _mlx_repair # type: ignoremonkeypatch.setattr(_mlx_repair, "mlx_stack_available", lambda: True)+ monkeypatch.setattr(_mlx_repair, "mlx_stack_blockers", lambda: [])else:# Drop cached mlx and patch find_spec so the unsloth gate sees mlx as absent.monkeypatch.delitem(sys.modules, "mlx", raising = False)