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
Do not self-heal MLX into a --no-torch install (#10409)
Michael Han12b224406a87
diff --git a/studio/backend/tests/test_chat_only_reason.py b/studio/backend/tests/test_chat_only_reason.pyindex 405bb2d28f9..49b09dd9841 100644--- a/studio/backend/tests/test_chat_only_reason.py+++ b/studio/backend/tests/test_chat_only_reason.py@@ -27,6 +27,10 @@ import utils.hardware.hardware as hw # noqa: E402def _no_torch(monkeypatch):# Force the non-CUDA/XPU path regardless of the test host's real GPUs.monkeypatch.setattr(hw, "_has_torch", lambda: False)+ # The no_torch verdict reads the venv's install manifest; pin it so the answer does+ # not depend on which venv runs these tests.+ monkeypatch.setattr(hw, "_installed_without_torch", lambda: False)+ monkeypatch.setattr(hw, "_NO_TORCH_SETTLED_EPOCH", None)# detect_hardware() assigns these module globals directly (not via monkeypatch),# so save and restore them; otherwise a chat-only verdict here leaks into other# backend tests (e.g. test_utils.py) when they share a process on a GPU host.@@ -65,6 +69,95 @@ def test_apple_silicon_with_incomplete_mlx_stack_stays_chat_only(monkeypatch):assert hw.CHAT_ONLY_REASON == "mlx_unavailable"+def _no_torch_apple_silicon(monkeypatch, *, mlx_on_disk: bool):+ monkeypatch.setattr(hw, "is_apple_silicon", lambda: True)+ monkeypatch.setattr(hw, "_installed_without_torch", lambda: True)+ monkeypatch.setattr(hw, "_mlx_distribution_installed", lambda: mlx_on_disk)+ monkeypatch.setattr(hw, "_has_usable_mlx_stack", lambda: False)+++def test_apple_silicon_no_torch_install_without_mlx_is_off_by_request(monkeypatch):+ # GGUF-only by request: not a broken stack, so the UI must not send the user to+ # `unsloth studio update`, which keeps no-torch and cannot enable Train.+ _no_torch_apple_silicon(monkeypatch, mlx_on_disk = False)+ assert hw.detect_hardware() == hw.DeviceType.CPU+ assert hw.CHAT_ONLY is True+ assert hw.CHAT_ONLY_REASON == "no_torch"+ assert hw.CHAT_ONLY_DETAIL is None+++def test_apple_silicon_no_torch_install_with_mlx_on_disk_waits_for_the_probe(monkeypatch):+ # A hand-installed stack can lose the warm's import race (#9120) and be usable a moment+ # later. no_torch would stop the sidebar polling before the overturn lands, so the verdict+ # stays mlx_unavailable, which the post-warm probe can still overturn, until it settles.+ _no_torch_apple_silicon(monkeypatch, mlx_on_disk = True)+ hw.detect_hardware()+ assert hw.CHAT_ONLY is True+ assert hw.CHAT_ONLY_REASON == "mlx_unavailable"+ assert hw.verdict_blames_the_mlx_stack() is True+++def test_the_probe_settles_a_no_torch_host_once_the_stack_measures_unusable(monkeypatch):+ _no_torch_apple_silicon(monkeypatch, mlx_on_disk = True)+ hw.detect_hardware()+ assert hw.settle_the_no_torch_verdict(hw.current_detection_epoch()) is True+ assert hw.CHAT_ONLY_REASON == "no_torch"+ assert hw.CHAT_ONLY_DETAIL is None+ assert hw.verdict_blames_the_mlx_stack() is False+ # And a later pass in this lifespan stays settled rather than re-arming the poll.+ hw.detect_hardware()+ assert hw.CHAT_ONLY_REASON == "no_torch"+++def test_a_probe_retired_by_a_shutdown_settles_nothing(monkeypatch):+ # The worker's epoch predates its measurement; a shutdown since means the next lifespan+ # measures for itself, so a stale settle neither flips the verdict nor pins the flag.+ _no_torch_apple_silicon(monkeypatch, mlx_on_disk = True)+ hw.detect_hardware()+ assert hw.settle_the_no_torch_verdict(hw.current_detection_epoch() - 1) is False+ assert hw.CHAT_ONLY_REASON == "mlx_unavailable"+ assert hw._NO_TORCH_SETTLED_EPOCH is None+++def test_a_settled_flag_does_not_outlive_its_lifespan(monkeypatch):+ # A new lifespan must run its own probe: a transient import failure at its detection+ # would otherwise publish no_torch and skip the probe that would have overturned it.+ _no_torch_apple_silicon(monkeypatch, mlx_on_disk = True)+ monkeypatch.setattr(hw, "_NO_TORCH_SETTLED_EPOCH", hw.current_detection_epoch() - 1)+ hw.detect_hardware()+ assert hw.CHAT_ONLY_REASON == "mlx_unavailable"+++def test_settling_leaves_any_other_verdict_alone(monkeypatch):+ for chat_only, reason in ((False, None), (True, "intel_mac"), (True, "no_torch")):+ hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = chat_only, reason+ assert hw.settle_the_no_torch_verdict(hw.current_detection_epoch()) is False+ assert (hw.CHAT_ONLY, hw.CHAT_ONLY_REASON) == (chat_only, reason)+++def test_a_declined_settle_does_not_mark_the_epoch(monkeypatch):+ # A settle that arrives after another pass has enabled training declines, and must not+ # record the epoch on the way out: the next transient MLX import failure in this+ # lifespan would then publish no_torch, which reads as settled, and+ # start_mlx_autorepair_if_needed() would skip the probe that restores Train.+ _no_torch_apple_silicon(monkeypatch, mlx_on_disk = True)+ hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = False, None+ assert hw.settle_the_no_torch_verdict(hw.current_detection_epoch()) is False+ assert hw._NO_TORCH_SETTLED_EPOCH != hw.current_detection_epoch()++ hw.detect_hardware()+ assert hw.CHAT_ONLY_REASON == "mlx_unavailable"+++def test_apple_silicon_no_torch_install_with_usable_mlx_enables_training(monkeypatch):+ monkeypatch.setattr(hw, "is_apple_silicon", lambda: True)+ monkeypatch.setattr(hw, "_installed_without_torch", lambda: True)+ monkeypatch.setattr(hw, "_has_usable_mlx_stack", lambda: True)+ hw.detect_hardware()+ assert hw.CHAT_ONLY is False+ assert hw.CHAT_ONLY_REASON is None++def test_intel_mac_reason(monkeypatch):monkeypatch.setattr(hw, "is_apple_silicon", lambda: False)monkeypatch.setattr(hw, "_has_mlx", lambda: False)diff --git a/studio/backend/tests/test_export_capability.py b/studio/backend/tests/test_export_capability.pyindex d086d48b659..06ab76b5647 100644--- a/studio/backend/tests/test_export_capability.py+++ b/studio/backend/tests/test_export_capability.py@@ -88,6 +88,17 @@ def test_apple_without_mlx_reports_mlx_unavailable(monkeypatch):assert "MLX" in cap["export_unsupported_message"]+def test_apple_no_torch_install_reports_no_torch(monkeypatch):+ # GGUF-only by request: the message must not send the user to `unsloth studio update`.+ _patch(monkeypatch, torch = False, device = hw.DeviceType.CPU, apple = True)+ monkeypatch.setattr(hw, "current_chat_only_verdict", lambda: ("no_torch", None))+ cap = hw.export_capability()+ assert cap["export_supported"] is False+ assert cap["export_unsupported_reason"] == "no_torch"+ assert "--no-torch" in cap["export_unsupported_message"]+ assert "unsloth studio update" not in cap["export_unsupported_message"]++# -- import safety without PyTorch --------------------------------------------------------------diff --git a/studio/backend/tests/test_health_holds_verdict_during_mlx_repair.py b/studio/backend/tests/test_health_holds_verdict_during_mlx_repair.pyindex 328c9340e8b..8c275d9c56c 100644--- a/studio/backend/tests/test_health_holds_verdict_during_mlx_repair.py+++ b/studio/backend/tests/test_health_holds_verdict_during_mlx_repair.py@@ -67,6 +67,9 @@ def apple_silicon(monkeypatch):# start_mlx_autorepair_if_needed() gates on this, and the real one imports mlx_vlm,# which is not installed here anyway.monkeypatch.setattr(mlx_repair, "mlx_stack_available", lambda: False)+ # The self-heal declines on a --no-torch install, so pin the install mode rather+ # than inherit the manifest of whatever venv these tests run in.+ monkeypatch.setattr(mlx_repair, "_installed_without_torch", lambda: False)# The pre-start hold is stamped on first use and keyed by detection generation, so a# stamp left by an earlier test would decide this one's answer.import main as main_mod@@ -138,6 +141,13 @@ def test_the_opt_out_settles_the_verdict_immediately(apple_silicon, monkeypatch)assert mlx_repair.mlx_repair_in_flight() is False+def test_a_no_torch_install_settles_the_verdict_immediately(apple_silicon, monkeypatch):+ """A --no-torch install declines the self-heal the way the kill switch does, so no repair+ is coming and the not-yet-started half must not hold the verdict for the grace."""+ monkeypatch.setattr(mlx_repair, "_installed_without_torch", lambda: True)+ assert mlx_repair.mlx_repair_in_flight() is False++def test_a_non_apple_host_is_never_in_flight(apple_silicon, monkeypatch):"""The self-heal is Apple Silicon only, Intel Macs included."""monkeypatch.setattr(mlx_repair, "is_apple_silicon", lambda: False)@@ -408,6 +418,21 @@ def test_health_settles_the_verdict_once_the_window_is_spent(apple_silicon, clocassert body["chat_only_reason"] == "mlx_unavailable"+def test_health_settles_the_verdict_at_once_on_a_no_torch_install(apple_silicon, monkeypatch):+ """End to end: the opt-out recorded at install time settles health on the first reply,+ exactly as the kill switch does, rather than after the 30s handoff grace."""+ import main as main_mod++ monkeypatch.setattr(mlx_repair, "_installed_without_torch", lambda: True)+ monkeypatch.setattr(main_mod, "_torch_warm_in_progress", lambda: False)+ body = _health(monkeypatch, chat_only = True, reason = "mlx_unavailable")++ assert "hardware_detecting" not in body+ assert body["device_type"]+ assert body["chat_only"] is True+ assert body["chat_only_reason"] == "mlx_unavailable"++def test_an_unaskable_self_heal_settles_the_verdict(apple_silicon, monkeypatch):"""If mlx_repair cannot even be consulted, settle rather than spin forever."""diff --git a/studio/backend/tests/test_mlx_autorepair_no_torch_optout.py b/studio/backend/tests/test_mlx_autorepair_no_torch_optout.pynew file mode 100644index 00000000000..96df0cc7fdf--- /dev/null+++ b/studio/backend/tests/test_mlx_autorepair_no_torch_optout.py@@ -0,0 +1,291 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A --no-torch install declined the training stack, so the self-heal must not put it back.++`install.sh --no-torch` is GGUF-only by request. The runtime self-heal used to gate on+Apple Silicon, the kill switch and stack availability, but never on the install mode, so+it reinstalled mlx/mlx-lm/mlx-vlm about 20 seconds after first launch and turned Train and+Export on for someone who had opted out.++The half that is easy to get wrong is the unknown case. `recorded_no_torch()` answers+Optional[bool], and None means "nothing recorded it", which is what every install predating+the manifest key looks like. Reading None as False keeps today's behaviour, which is right;+reading it as True would silently disable the repair for every older install on the+planet. These tests pin both halves, plus every way the lookup can fail.+"""++from __future__ import annotations++import json+import sys+import threading+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++[email protected](autouse = True)+def _isolated(monkeypatch):+ """Same reset as test_mlx_repair.py: the attempt latch is process-global, and a worker+ that outlives its test runs the real repair against the next one."""+ monkeypatch.setattr(mr, "_attempted", False)+ monkeypatch.setattr(mr, "_environment_mutated", False)+ monkeypatch.delenv(mr.DISABLE_ENV_VAR, raising = False)+ yield+ for thread in threading.enumerate():+ if thread.name == "mlx-autorepair":+ thread.join(timeout = 5)+ assert not thread.is_alive()+++def _install_manifest_returning(monkeypatch, value):+ """Stand in for studio.install_manifest, which _installed_without_torch imports lazily.++ A callable raising is spelled by passing an exception instance, since that is the other+ thing the real module can do here (an unreadable manifest, a partially installed tree).+ """+ import types++ module = types.ModuleType("studio.install_manifest")++ def recorded_no_torch():+ if isinstance(value, BaseException):+ raise value+ return value++ module.recorded_no_torch = recorded_no_torch+ package = types.ModuleType("studio")+ package.install_manifest = module+ monkeypatch.setitem(sys.modules, "studio", package)+ monkeypatch.setitem(sys.modules, "studio.install_manifest", module)+++# --- _installed_without_torch: only a literal True opts out ------------------------+++def test_true_means_no_torch(monkeypatch):+ _install_manifest_returning(monkeypatch, True)+ assert mr._installed_without_torch() is True+++def test_false_means_a_normal_install(monkeypatch):+ _install_manifest_returning(monkeypatch, False)+ assert mr._installed_without_torch() is False+++def test_unknown_keeps_todays_behaviour(monkeypatch):+ """None is an install made before anything recorded the mode. It must read as False, or+ this change would disable the self-heal for every venv installed before it landed."""+ _install_manifest_returning(monkeypatch, None)+ assert mr._installed_without_torch() is False++[email protected]("value", ["1", "true", 1, ["no-torch"], object()])+def test_a_truthy_non_bool_is_not_an_opt_out(monkeypatch, value):+ """recorded_no_torch normalises a hand-edited manifest itself, so anything that reaches+ here as a non-bool is a contract violation, not consent. `is True` says so."""+ _install_manifest_returning(monkeypatch, value)+ assert mr._installed_without_torch() is False+++ "error",+ [ImportError("no studio package"), OSError("unreadable manifest"), ValueError("bad json")],+)+def test_a_failed_lookup_fails_open(monkeypatch, error):+ """Fail open, not closed: an unreadable manifest must not quietly cost an Apple Silicon+ user their training stack."""+ _install_manifest_returning(monkeypatch, error)+ assert mr._installed_without_torch() is False+++def test_a_missing_studio_package_fails_open(monkeypatch):+ monkeypatch.setitem(sys.modules, "studio", None) # import raises+ assert mr._installed_without_torch() is False+++def _real_install_manifest(monkeypatch, venv_root: Path):+ """The shipped studio/install_manifest.py, reading a real manifest file.++ Loaded by path and registered as `studio.install_manifest`, because that is the name+ _installed_without_torch imports and the repo root is not on sys.path in the backend+ test job. Everything below it is the real code: read_manifest, the marker fallback and+ the truthy-string tolerance all run for real."""+ import importlib.util+ import types++ source = Path(__file__).resolve().parents[2] / "install_manifest.py"+ spec = importlib.util.spec_from_file_location("studio.install_manifest", source)+ module = importlib.util.module_from_spec(spec)+ package = types.ModuleType("studio")+ package.install_manifest = module+ monkeypatch.setitem(sys.modules, "studio", package)+ monkeypatch.setitem(sys.modules, "studio.install_manifest", module)+ spec.loader.exec_module(module)+ monkeypatch.setattr(module, "venv_root", lambda: venv_root)+ return module+++ ("manifest", "expected"),+ [+ ({"no_torch": True}, True),+ ({"no_torch": False}, False),+ ({"no_torch": "1"}, True), # tolerated hand edit+ ({"no_torch": "no"}, False),+ ({"steps_total": 12}, False), # an install predating the key+ (None, False), # no manifest at all+ ],+)+def test_against_a_real_manifest_on_disk(monkeypatch, tmp_path, manifest, expected):+ """The same question asked through the shipped manifest reader rather than a stub, so a+ change to its parsing cannot pass this file while breaking the gate."""+ module = _real_install_manifest(monkeypatch, tmp_path)+ if manifest is not None:+ (tmp_path / module.MANIFEST_NAME).write_text(json.dumps(manifest), encoding = "utf-8")+ assert mr._installed_without_torch() is expected+++def test_a_corrupt_manifest_does_not_disable_the_repair(monkeypatch, tmp_path):+ module = _real_install_manifest(monkeypatch, tmp_path)+ (tmp_path / module.MANIFEST_NAME).write_text("{not json", encoding = "utf-8")+ assert mr._installed_without_torch() is False+++# --- start_mlx_autorepair_if_needed: the gate itself -------------------------------+++def _hardware(monkeypatch, *, blames_mlx: bool):+ """start_mlx_autorepair_if_needed imports utils.hardware.hardware inside the function, so+ patch the module rather than a name on mlx_repair."""+ import utils.hardware.hardware as hw++ monkeypatch.setattr(hw, "verdict_blames_the_mlx_stack", lambda: blames_mlx)+ monkeypatch.setattr(hw, "current_detection_epoch", lambda: 1)+ monkeypatch.setattr(hw, "detect_hardware", lambda: None)+ monkeypatch.setattr(hw, "settle_the_no_torch_verdict", lambda epoch: False)+ overturns = []+ monkeypatch.setattr(+ hw, "overturn_the_mlx_verdict", lambda epoch: bool(overturns.append(epoch)) or True+ )+ return overturns+++def _apple_silicon_without_mlx(monkeypatch):+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)+ monkeypatch.setattr(mr, "mlx_stack_available", lambda: False)+++def test_no_torch_install_starts_no_repair(monkeypatch):+ _apple_silicon_without_mlx(monkeypatch)+ _hardware(monkeypatch, blames_mlx = False)+ monkeypatch.setattr(mr, "_installed_without_torch", lambda: True)+ attempts = []+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda **_kw: attempts.append(1) or True)++ assert mr.start_mlx_autorepair_if_needed() is False+ assert attempts == [], "a --no-torch install must not be given the training stack back"+++def test_no_torch_install_starts_no_repair_even_when_the_verdict_blames_mlx(monkeypatch):+ """The verdict blaming MLX is what carries the opt-out past the first gate, so the+ second one has to hold. Without it, a --no-torch venv whose health check says+ 'mlx_unavailable' would still be handed a reinstall, which is the reported bug."""+ _apple_silicon_without_mlx(monkeypatch)+ _hardware(monkeypatch, blames_mlx = True)+ monkeypatch.setattr(mr, "_installed_without_torch", lambda: True)+ attempts = []+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda **_kw: attempts.append(1) or True)++ assert mr.start_mlx_autorepair_if_needed() is False+ assert attempts == []+ assert mr._attempted is False, "the one-shot latch must not be spent by a declined repair"+++def test_a_normal_install_still_repairs(monkeypatch):+ """The regression check: the opt-out must not cost the users it is not about."""+ _apple_silicon_without_mlx(monkeypatch)+ _hardware(monkeypatch, blames_mlx = False)+ monkeypatch.setattr(mr, "_installed_without_torch", lambda: False)+ attempts = []+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda **_kw: attempts.append(1) or True)++ assert mr.start_mlx_autorepair_if_needed() is True+ for thread in threading.enumerate():+ if thread.name == "mlx-autorepair":+ thread.join(timeout = 5)+ assert attempts == [1]+++def test_an_older_install_with_no_recorded_mode_still_repairs(monkeypatch):+ """End to end through the real _installed_without_torch, on the manifest an install+ predating the key leaves: unknown, so the repair runs as it always did."""+ _apple_silicon_without_mlx(monkeypatch)+ _hardware(monkeypatch, blames_mlx = False)+ _install_manifest_returning(monkeypatch, None)+ attempts = []+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda **_kw: attempts.append(1) or True)++ assert mr.start_mlx_autorepair_if_needed() is True+ for thread in threading.enumerate():+ if thread.name == "mlx-autorepair":+ thread.join(timeout = 5)+ assert attempts == [1]+++def test_a_no_torch_install_still_overturns_a_verdict_that_blames_mlx(monkeypatch):+ """Opting out declines a reinstall, not a correct verdict. That is why the opt-out was+ spelled into the kill switch's condition rather than given an early return of its own:+ a venv that does have a usable stack must still be allowed to say so, and a --no-torch+ install can have one, for instance from a `pip install mlx-lm` the user ran themselves."""+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)+ monkeypatch.setattr(mr, "mlx_stack_available", lambda: True)+ monkeypatch.setattr(mr, "_installed_without_torch", lambda: True)+ overturns = _hardware(monkeypatch, blames_mlx = True)+ attempts = []+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda **_kw: attempts.append(1) or True)++ assert mr.start_mlx_autorepair_if_needed() is False+ assert overturns == [1], "the chat-only verdict was left standing against a usable stack"+ assert attempts == [], "an adequate stack needs no reinstall"+++def test_a_no_torch_install_settles_its_verdict_once_the_probe_measures_unusable(monkeypatch):+ """With mlx on disk the verdict boots as mlx_unavailable so the sidebar keeps polling for+ the overturn; once the probe measures the stack unusable, nothing is coming, so it settles+ as the opt-out it is and the poll stops on the next read."""+ import utils.hardware.hardware as hw++ _apple_silicon_without_mlx(monkeypatch)+ _hardware(monkeypatch, blames_mlx = True)+ monkeypatch.setattr(mr, "_installed_without_torch", lambda: True)+ settled = []+ monkeypatch.setattr(+ hw, "settle_the_no_torch_verdict", lambda epoch: settled.append(epoch) or True+ )++ assert mr.start_mlx_autorepair_if_needed() is False+ assert settled == [1], "settled with the epoch read before the measurement"+++def test_the_kill_switch_does_not_settle_the_verdict_as_no_torch(monkeypatch):+ import utils.hardware.hardware as hw++ _apple_silicon_without_mlx(monkeypatch)+ _hardware(monkeypatch, blames_mlx = True)+ monkeypatch.setattr(mr, "_installed_without_torch", lambda: False)+ monkeypatch.setenv(mr.DISABLE_ENV_VAR, "1")+ settled = []+ monkeypatch.setattr(+ hw, "settle_the_no_torch_verdict", lambda epoch: settled.append(epoch) or True+ )++ assert mr.start_mlx_autorepair_if_needed() is False+ assert settled == [], "the kill switch is a normal install; its verdict is not an opt-out"diff --git a/studio/backend/tests/test_mlx_repair.py b/studio/backend/tests/test_mlx_repair.pyindex f5dc3e9e857..ae9e782114e 100644--- a/studio/backend/tests/test_mlx_repair.py+++ b/studio/backend/tests/test_mlx_repair.py@@ -29,6 +29,12 @@ def _reset_attempt_guard(monkeypatch):# latch an earlier test left set and re-detects for real against the next test.monkeypatch.setattr(mr, "_environment_mutated", False)monkeypatch.delenv(mr.DISABLE_ENV_VAR, raising = False)+ # The self-heal now declines on a --no-torch install, and the answer comes from the+ # manifest of whatever venv these tests happen to run in. Left ambient, four tests below+ # fail inside a GGUF-only Studio venv, which is a real place to run them. Pin it here and+ # let the file that owns the opt-out drive the True case:+ # test_mlx_autorepair_no_torch_optout.py.+ monkeypatch.setattr(mr, "_installed_without_torch", lambda: False)yield# Join inside the test's stubs: an outliving worker would run the real detect_hardware()# against the next test's globals.diff --git a/studio/backend/tests/test_warm_window_review_fixes.py b/studio/backend/tests/test_warm_window_review_fixes.pyindex 4ff15852c18..a70727dc3d7 100644--- a/studio/backend/tests/test_warm_window_review_fixes.py+++ b/studio/backend/tests/test_warm_window_review_fixes.py@@ -2622,7 +2622,10 @@ def test_the_mlx_worker_reads_its_epoch_before_start():with mock.patch.object(repair.threading, "Thread", _Recorder):with mock.patch.object(repair, "is_apple_silicon", lambda: True):- with mock.patch.object(repair, "mlx_stack_available", lambda: False):+ with (+ mock.patch.object(repair, "mlx_stack_available", lambda: False),+ mock.patch.object(repair, "_installed_without_torch", lambda: False),+ ):with mock.patch.dict(os.environ, {}, clear = False):os.environ.pop(repair.DISABLE_ENV_VAR, None)repair._attempted = Falsediff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 44205a40bfc..94343d5529a 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -80,6 +80,10 @@ CHAT_ONLY: bool = True # No CUDA GPU -> GGUF chat only (Mac, CPU-only, etc.)# Why CHAT_ONLY is True (Train/Export disabled). None when training is enabled.# "mlx_unavailable": Apple Silicon but the MLX stack is missing, too old, or broken# (the usual cause of "Train/Export greyed out" on Macs after a reinstall dropped MLX);+# "no_torch": Apple Silicon installed --no-torch, GGUF-only by request, so nothing is+# broken and `unsloth studio update` cannot change it. Published at once when no mlx is+# on disk; a present but unusable stack stays "mlx_unavailable" until the post-warm probe+# has measured it, so a usable one that lost the warm's import race is still overturned;# "intel_mac": Intel Mac (no PyTorch/MLX); "no_gpu": CPU-only non-Mac host;# "torch_cpu_build" / "torch_cuda_unavailable": the host HAS GPUs, this PyTorch cannot# use them -- see classify_torch_build(). Those two must not read as "no_gpu": the fix@@ -287,6 +291,11 @@ def _has_mlx() -> bool:# 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+# The lifespan whose post-warm probe measured a --no-torch host's stack unusable: a later+# detection pass in that lifespan publishes no_torch directly rather than re-arming the+# sidebar's poll. Keyed by epoch so the next lifespan runs its own probe, and so a worker+# retired by a shutdown mid-probe cannot settle the lifespan that replaced it.+_NO_TORCH_SETTLED_EPOCH: Optional[int] = Nonedef _has_usable_mlx_stack() -> bool:@@ -993,6 +1002,25 @@ def _stated_torch_index_source() -> str:return (os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY") or "").strip()+def _installed_without_torch() -> bool:+ # The self-heal's reader, so the verdict and the gate that declines on it agree.+ try:+ from utils.mlx_repair import _installed_without_torch as recorded+ return recorded()+ except Exception:+ return False+++def _mlx_distribution_installed() -> bool:+ try:+ pkg_version("mlx")+ except PackageNotFoundError:+ return False+ except Exception:+ return True+ return True++def _recorded_install_flavor() -> "tuple[str, bool]":"""``(expected_torch_tag, expected_torch_tag_pinned)`` from the venv's manifest.@@ -1573,6 +1601,27 @@ def verdict_blames_the_mlx_stack() -> bool:return bool(CHAT_ONLY) and CHAT_ONLY_REASON == "mlx_unavailable"+def settle_the_no_torch_verdict(epoch: int) -> bool:+ """For the post-warm probe that measured a --no-torch host's stack unusable: nothing will+ overturn mlx_unavailable now, so publish no_torch and let the sidebar stop polling.+ ``epoch`` predates the measurement, as for overturn_the_mlx_verdict: a shutdown since+ retired that probe, and the next lifespan measures for itself."""+ global CHAT_ONLY_REASON, CHAT_ONLY_DETAIL, _NO_TORCH_SETTLED_EPOCH+ with _DETECT_LOCK:+ if epoch != current_detection_epoch():+ return False+ if not CHAT_ONLY or CHAT_ONLY_REASON != "mlx_unavailable":+ return False+ # Recorded only once the verdict this probe measured is still the live one. Set+ # before the check, a settle that arrives after another pass has enabled training+ # still marks the epoch, and the next transient MLX failure in that lifespan+ # publishes no_torch straight away, which reads as settled and skips the post-warm+ # probe that would have restored Train.+ _NO_TORCH_SETTLED_EPOCH = epoch+ CHAT_ONLY_REASON, CHAT_ONLY_DETAIL = "no_torch", None+ return True++def overturn_the_mlx_verdict(epoch: Optional[int] = None) -> bool:"""For a caller that has just measured the stack as usable.@@ -1862,7 +1911,25 @@ def _detect_hardware_locked() -> DeviceType:# CHAT_ONLY is still True here (every training-capable branch returned early),# so record WHY so the UI can explain the greyed-out Train/Export instead of# silently disabling them.- if is_apple_silicon():+ if (+ is_apple_silicon()+ and _installed_without_torch()+ and (+ _NO_TORCH_SETTLED_EPOCH == current_detection_epoch()+ or not _mlx_distribution_installed()+ )+ ):+ # GGUF-only by request: not a broken stack, and `unsloth studio update` cannot+ # change it. With mlx on disk the verdict stays mlx_unavailable until the post-warm+ # probe measures it, so a stack that only lost the import race is still overturned+ # and the sidebar keeps polling until settle_the_no_torch_verdict() lands.+ CHAT_ONLY_REASON = "no_torch"+ _MLX_BLOCKERS_MEASURED = None+ logger.info(+ "Apple Silicon installed --no-torch (GGUF-only); Train/Export are off by "+ "request. Reinstall without --no-torch to enable them."+ )+ elif is_apple_silicon():# Reached the CPU fallback on Apple Silicon, so the MLX stack is missing,# too old, or broken. This is usually an environment problem recoverable# with `unsloth studio update`.@@ -2117,6 +2184,12 @@ def export_capability() -> dict:"Hardware detection failed on this host, so export is disabled. The server log records ""the underlying error; restart Unsloth Studio to retry detection.")+ elif verdict[0] == "no_torch":+ reason = "no_torch"+ message = (+ "This install was set up without the training stack (--no-torch), so export is "+ "disabled. Reinstall Unsloth Studio without --no-torch to enable export."+ )elif is_apple_silicon():reason = "mlx_unavailable"message = (diff --git a/studio/backend/utils/mlx_repair.py b/studio/backend/utils/mlx_repair.pyindex 227315b7b11..5ab1dcaa006 100644--- a/studio/backend/utils/mlx_repair.py+++ b/studio/backend/utils/mlx_repair.py@@ -264,6 +264,10 @@ def mlx_repair_in_flight() -> bool:return Falseif not is_apple_silicon():return False+ # A --no-torch install declines the self-heal like the kill switch, so no repair is+ # coming and the verdict settles now instead of after the pre-start grace.+ if _installed_without_torch():+ return Falsewith _attempted_lock:attempted, thread, started_at = _attempted, _repair_thread, _repair_started_atif not attempted:@@ -515,12 +519,25 @@ def _run_repair_and_redetect(epoch: Optional[int] = None) -> None:logger.warning("MLX installed but hardware re-detection failed: %s", exc)+def _installed_without_torch() -> bool:+ """True when this venv was installed --no-torch (GGUF-only).++ Unknown reads as False: an install predating the manifest keeps today's+ repair behaviour rather than silently losing it.+ """+ try:+ from studio.install_manifest import recorded_no_torch+ return recorded_no_torch() is True+ except Exception:+ return False++def start_mlx_autorepair_if_needed() -> bool:"""If this is an Apple Silicon host whose MLX stack is missing or too old, reinstall it ona daemon thread (off the startup critical path) and re-detect on success. True iff a repair- thread was started; False off Apple Silicon, when already attempted this process, or when- disabled via UNSLOTH_DISABLE_MLX_AUTOREPAIR=1. An adequate stack starts no repair but still- overturns a verdict that contradicts it."""+ thread was started; False off Apple Silicon, when already attempted this process, when the+ venv was installed --no-torch, or when disabled via UNSLOTH_DISABLE_MLX_AUTOREPAIR=1. An+ adequate stack starts no repair but still overturns a verdict that contradicts it."""global _attempted, _repair_thread, _repair_started_atif not is_apple_silicon():return False@@ -529,7 +546,10 @@ def start_mlx_autorepair_if_needed() -> bool:# Opting out declines a reinstall, not a correct verdict, so the overturn still runs, but# only when one waits on it: under the warm's kill switch it would be a first MLX import# for no one.- opted_out = os.environ.get(DISABLE_ENV_VAR) == "1"+ # A --no-torch install declined the training stack on purpose, so treat it+ # exactly like the kill switch: no reinstall, but a correct verdict still wins.+ no_torch = _installed_without_torch()+ opted_out = os.environ.get(DISABLE_ENV_VAR) == "1" or no_torchif opted_out and not _hw.verdict_blames_the_mlx_stack():return False# Read before the measurement, so a shutdown during it discards whatever is published on@@ -546,6 +566,13 @@ def start_mlx_autorepair_if_needed() -> bool:)return Falseif opted_out:+ # Measured unusable and nothing will reinstall it, so a --no-torch host's verdict+ # settles as the opt-out it is instead of staying a repairable mlx_unavailable.+ if no_torch and _hw.settle_the_no_torch_verdict(epoch):+ logger.info(+ "MLX stack measures unusable on a --no-torch install; Train/Export stay "+ "off by request. Reinstall without --no-torch to enable them."+ )return Falsewith _attempted_lock:diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex a46ac2ad3aa..b64d331746c 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -835,7 +835,10 @@ export function AppSidebar() {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"+ : chatOnlyReason === "no_torch"+ ? // GGUF-only by request. `unsloth studio update` keeps no-torch, so it is not the fix.+ "Training was left out of this install (--no-torch). Reinstall without --no-torch to enable Train."+ : chatOnlyReason === "intel_mac"? "Training needs Apple Silicon or a GPU. Intel Macs are chat-only.": chatOnlyReason === "torch_cpu_build" ||chatOnlyReason === "torch_cuda_unavailable"diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.tsindex d1eaf8a37b5..00fdf5294fe 100644--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts@@ -117,6 +117,7 @@ export const CONTEXT_LENGTH_MIN = 128;// Reasons a Mac still cannot serve with MLX.const NO_MLX_REASONS = new Set(["mlx_unavailable",+ "no_torch","intel_mac","detection_failed",]);diff --git a/studio/frontend/tests/gpu-torch-mismatch.test.ts b/studio/frontend/tests/gpu-torch-mismatch.test.tsindex 371dde7a164..f826c9e44d5 100644--- a/studio/frontend/tests/gpu-torch-mismatch.test.ts+++ b/studio/frontend/tests/gpu-torch-mismatch.test.ts@@ -341,7 +341,7 @@ test("the sidebar keeps polling while the inventory can still change the verdictsource.indexOf("INVENTORY_SENSITIVE_REASONS = new Set(["),);const listed = set.slice(0, set.indexOf("]"));- for (const settled of ["mlx_unavailable", "intel_mac"]) {+ for (const settled of ["mlx_unavailable", "no_torch", "intel_mac"]) {assert.ok(!listed.includes(settled),`${settled} cannot change on a probe and must not keep polling`,@@ -411,6 +411,10 @@ test("only a host the inventory can still reclassify keeps polling", () => {"a healthy GPU host must not gain a forced read a minute",);assert.ok(!polls(true, "intel_mac"), "an Intel Mac stays an Intel Mac");+ assert.ok(+ !polls(true, "no_torch"),+ "a --no-torch install declined the training stack; nothing is coming to change it",+ );// detection_failed is NOT settled when torch is the thing that failed: the backend// classifies the wheel from disk and swaps in the mismatch once the inventory recovers,// so stopping the poll froze the sidebar on the failure for the session.diff --git a/studio/frontend/tests/mlx-context-helpers.test.ts b/studio/frontend/tests/mlx-context-helpers.test.tsindex ff379ebb384..377c1a663d0 100644--- a/studio/frontend/tests/mlx-context-helpers.test.ts+++ b/studio/frontend/tests/mlx-context-helpers.test.ts@@ -108,7 +108,12 @@ test("MLX is a Mac non-GGUF load, and the reasons that rule it out", () => {assert.equal(isServedByMlx(false, "mac", null), true);assert.equal(isServedByMlx(true, "mac", null), false);assert.equal(isServedByMlx(false, "cuda", null), false);- for (const reason of ["mlx_unavailable", "intel_mac", "detection_failed"]) {+ for (const reason of [+ "mlx_unavailable",+ "no_torch",+ "intel_mac",+ "detection_failed",+ ]) {assert.equal(isServedByMlx(false, "mac", reason), false, reason);}});diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 438ac7066d0..e45b80c0c55 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -7120,7 +7120,7 @@ def install_python_stack() -> int:base_total += 2 # flash-attn + torch final repair (step 13), Linuxelse:base_total += 1 # torch flavor invariant (step 13w), Windows- if IS_MAC_ARM and not skip_base:+ if IS_MAC_ARM and not skip_base and not NO_TORCH:base_total += 1 # MLX stack, same gate as the step itselfbase_requirements = _shared_base_requirements() if skip_base else None# Core packages and shared base requirements occupy one progress slot. A@@ -7200,7 +7200,9 @@ def install_python_stack() -> int:# macOS arm64: install MLX stack at latest (UV_OVERRIDE relaxes the# mlx-vlm / mlx-lm transformers pin -- set at module load).- if IS_MAC_ARM and not skip_base:+ # Not on a --no-torch install: it declined the training stack, and the runtime's+ # no_torch verdict tells the user an update will not put it back.+ if IS_MAC_ARM and not skip_base and not NO_TORCH:_progress("MLX stack (Apple Silicon)")pip_install("Installing MLX stack (mlx + mlx-lm + mlx-vlm)",diff --git a/tests/studio/install/test_no_torch_skips_mlx_stack.py b/tests/studio/install/test_no_torch_skips_mlx_stack.pynew file mode 100644index 00000000000..9f994821fad--- /dev/null+++ b/tests/studio/install/test_no_torch_skips_mlx_stack.py@@ -0,0 +1,114 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""`unsloth studio update` must not hand a --no-torch install the MLX stack back.++Gating the runtime self-heal is only half of the opt-out. The installer's own MLX step+runs on `IS_MAC_ARM and not skip_base`, and the updater clears SKIP_STUDIO_BASE+(`unsloth_cli/commands/studio.py`), so before the `not NO_TORCH` guard a routine update+installed mlx/mlx-lm/mlx-vlm into a GGUF-only venv and the next launch enabled Train+before the no_torch verdict was ever reached. That is the one line that makes the opt-out+survive an update, and it is invisible to the backend tests.++Structural rather than behavioural for the reason test_diffusers_pin.py is: running the+installer needs a Mac, and what has to hold is a property of the gate, not of one run.+"""++from __future__ import annotations++import ast+import pathlib++REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]+STACK = REPO_ROOT / "studio" / "install_python_stack.py"+STUDIO_CLI = REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"++MLX_STEP_LABEL = "Installing MLX stack"+++def _source() -> str:+ return STACK.read_text(encoding = "utf-8")+++def _guards_of_calls_mentioning(source: str, needle: str) -> list[str]:+ """The `if` test guarding every call whose arguments mention ``needle``."""+ tree = ast.parse(source)+ guards = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.If):+ continue+ for call in ast.walk(node):+ if not isinstance(call, ast.Call):+ continue+ if any(+ isinstance(arg, ast.Constant) and isinstance(arg.value, str) and needle in arg.value+ for arg in call.args+ ):+ guards.append(ast.get_source_segment(source, node.test) or "")+ return guards+++def test_the_mlx_install_step_is_gated_on_no_torch():+ guards = _guards_of_calls_mentioning(_source(), MLX_STEP_LABEL)+ assert guards, f"no call carrying {MLX_STEP_LABEL!r} found in {STACK.name}"+ for guard in guards:+ assert "NO_TORCH" in guard and "not NO_TORCH" in guard, (+ f"the MLX install step is guarded by `{guard}`, which does not exclude a "+ f"--no-torch install. The updater clears SKIP_STUDIO_BASE, so without this the "+ f"next `unsloth studio update` reinstalls the stack the user declined."+ )+ assert "IS_MAC_ARM" in guard, (+ f"the MLX install step is guarded by `{guard}`, which no longer scopes to "+ f"Apple Silicon"+ )+++def test_the_progress_total_uses_the_same_gate_as_the_step():+ """_TOTAL is computed from a copy of the gate. If the two drift, the progress bar+ counts a step that never runs, and on a --no-torch install it would stall one short."""+ source = _source()+ step_guards = set(_guards_of_calls_mentioning(source, MLX_STEP_LABEL))+ tree = ast.parse(source)+ lines = source.splitlines()+ total_guards = set()+ for node in ast.walk(tree):+ if not isinstance(node, ast.If):+ continue+ # Sliced by line rather than ast.get_source_segment: what names this branch is the+ # trailing comment on the += 1, and a node's extent stops before it.+ segment = "\n".join(lines[node.lineno - 1 : node.end_lineno])+ # The += 1 whose comment names the MLX stack, i.e. the accounting twin.+ if "base_total += 1" in segment and "MLX stack" in segment:+ total_guards.add(ast.get_source_segment(source, node.test) or "")+ assert total_guards, "no base_total accounting found for the MLX stack step"+ assert total_guards == step_guards, (+ f"the MLX step runs under {step_guards} but is counted under {total_guards}; "+ f"they have to be the same expression"+ )+++def test_the_updater_still_clears_skip_studio_base():+ """The premise of the guard. If the updater ever stopped clearing this, the MLX step+ would be skipped for a different reason and the test above would pass vacuously."""+ assert 'os.environ.pop("SKIP_STUDIO_BASE", None)' in STUDIO_CLI.read_text(encoding = "utf-8")+++def test_no_torch_is_resolved_from_the_manifest_not_only_from_the_environment():+ """The updater injects no UNSLOTH_NO_TORCH, so the manifest tier is what makes the gate+ fire on `unsloth studio update` rather than only on a fresh `install.sh --no-torch`."""+ source = _source()+ tree = ast.parse(source)+ infer = next(+ (+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_infer_no_torch"+ ),+ None,+ )+ assert infer is not None, "_infer_no_torch is gone; NO_TORCH now comes from somewhere else"+ body = ast.get_source_segment(source, infer) or ""+ assert "recorded_no_torch" in body, (+ "_infer_no_torch no longer consults the install manifest, so an update would run "+ "with NO_TORCH False in a GGUF-only venv and reinstall the MLX stack"+ )