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.

Studio: install the supported MLX stack on fresh macOS installs (#10403)

Michael Hana42840c3581e
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index ca60fcd4686..2ce5b24a68d 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -420,6 +420,22 @@ def _macos_release_major() -> "int | None":
return None
+# The pinned MLX versions publish macosx_14_0_arm64 wheels, no sdist and no cp39, so
+# macOS 13 and Python 3.9 have nothing to resolve to (`uv pip install --python-platform
+# aarch64-apple-darwin mlx==0.32.1`). Asked before the install, like
+# _torchcodec_spec_is_installable: pip_install exits on failure, so trying would end an
+# install that today just comes up chat-only.
+_MLX_MIN_PYTHON = (3, 10)
+_MLX_MIN_MACOS_MAJOR = 14
+
+
+def _mlx_pins_are_installable() -> bool:
+ """Wheel for the pinned MLX versions here? An unreadable macOS reads as too old."""
+ if sys.version_info < _MLX_MIN_PYTHON:
+ return False
+ return (_macos_release_major() or 0) >= _MLX_MIN_MACOS_MAJOR
+
+
# The supported Python range moves three times across the lines we select from.
# Transcribed from upstream's published table (README / PyPI):
#
@@ -7349,7 +7365,7 @@ def install_python_stack() -> int:
base_total += 2 # flash-attn + torch final repair (step 13), Linux
else:
base_total += 1 # torch flavor invariant (step 13w), Windows
- if IS_MAC_ARM and not skip_base and not NO_TORCH:
+ if IS_MAC_ARM and not NO_TORCH:
base_total += 1 # MLX stack, same gate as the step itself
base_requirements = _shared_base_requirements() if skip_base else None
# Core packages and shared base requirements occupy one progress slot. A
@@ -7427,21 +7443,32 @@ def install_python_stack() -> int:
if not _repair_damaged_core_payload(_core_package_names(package_name), local_repo = local_repo):
return 1
- # macOS arm64: install MLX stack at latest (UV_OVERRIDE relaxes the
- # mlx-vlm / mlx-lm transformers pin -- set at module load).
- # 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)",
- "--no-cache-dir",
- "--upgrade",
- "mlx",
- "mlx-metal",
- "mlx-lm",
- "mlx-vlm",
- )
+ # macOS arm64: not keyed off skip_base, because a fresh install skips core packages
+ # and still needs MLX. Not on --no-torch: it declined the training stack. Pins stay
+ # aligned with utils/mlx_repair.py and unsloth-zoo; UV_OVERRIDE (set at module load)
+ # relaxes the mlx-vlm / mlx-lm transformers pin.
+ if IS_MAC_ARM and not NO_TORCH:
+ # Both branches spend the slot, so the denominator does not depend on the host.
+ if _mlx_pins_are_installable():
+ _progress("MLX stack (Apple Silicon)")
+ pip_install(
+ "Installing MLX stack (mlx + mlx-lm + mlx-vlm)",
+ "--no-cache-dir",
+ "--upgrade",
+ "mlx==0.32.1",
+ "mlx-metal==0.32.1",
+ "mlx-lm==0.31.3",
+ "mlx-vlm>=0.4.4,<0.7.0",
+ )
+ else:
+ _progress("MLX stack (skipped, no wheel for this macOS or Python)")
+ _note(
+ f"macOS {_macos_release_major() or 'unknown'} on Python "
+ f"{sys.version_info.major}.{sys.version_info.minor} publishes no wheel for the "
+ f"supported MLX versions (needs macOS {_MLX_MIN_MACOS_MAJOR}+ and Python "
+ f"{_MLX_MIN_PYTHON[0]}.{_MLX_MIN_PYTHON[1]}+) -- leaving Train/Export disabled "
+ "rather than failing the install"
+ )
# gfx906: the base install below resolves unsloth's unconditional bitsandbytes
# dep to a generic CUDA wheel (no gfx906 kernels). Record bnb's presence now so
diff --git a/tests/python/test_windows_python_venv_hardening.py b/tests/python/test_windows_python_venv_hardening.py
index e97405a3bba..2307abe0a4a 100644
--- a/tests/python/test_windows_python_venv_hardening.py
+++ b/tests/python/test_windows_python_venv_hardening.py
@@ -137,23 +137,46 @@ def _uv_cache_functions(source: str) -> str:
@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")
@pytest.mark.parametrize("shell", POWERSHELLS)
-def test_path_python_wrapper_resolves_to_real_executable(tmp_path: Path, shell: str):
+ "reported_version,accepted",
+ [
+ ("3.9.0", False),
+ ("3.10.0", False),
+ ("3.11.0", True),
+ ("3.12.0", True),
+ ("3.13.0", True),
+ ("3.13.8", False),
+ ("3.14.0", False),
+ ],
+)
+def test_path_python_wrapper_resolves_to_real_executable(
+ tmp_path: Path, shell: str, reported_version: str, accepted: bool
+):
source = INSTALL_PS1.read_text(encoding = "utf-8")
finder = _extract(r" function Find-CompatiblePython \{.*?\n \}\n", source)
(tmp_path / "sitecustomize.py").write_text('print("STARTUP_BANNER")\n', encoding = "utf-8")
if os.name == "nt":
wrapper = tmp_path / "python.bat"
- wrapper.write_text(f'@"{sys.executable}" %*\n', encoding = "utf-8")
+ wrapper.write_text(
+ f'@echo off\nif "%~1"=="--version" (\n'
+ f"echo Python {reported_version}\nexit /b 0\n)\n"
+ f'@"{sys.executable}" %*\n',
+ encoding = "utf-8",
+ )
else:
wrapper = tmp_path / "python-wrapper"
wrapper.write_text(
- f'#!/bin/sh\nexec {shlex.quote(sys.executable)} "$@"\n', encoding = "utf-8"
+ '#!/bin/sh\nif [ "$1" = "--version" ]; then\n'
+ f"printf 'Python {reported_version}\\n'\nexit 0\nfi\n"
+ f'exec {shlex.quote(sys.executable)} "$@"\n',
+ encoding = "utf-8",
)
wrapper.chmod(0o755)
script = f"""
$ErrorActionPreference = "Stop"
$PythonVersion = "3.13"
+$PythonSkip = @("3.13.8")
$script:CondaSkipPattern = '(?i)(conda|miniconda|anaconda)'
function Get-HostMachineArch {{ return "x86_64" }}
function Test-IsCondaPython {{ param([string]$Exe) return $false }}
@@ -173,7 +196,12 @@ Write-Output $found.Path
env = os.environ.copy()
env["TEST_PYTHON_WRAPPER"] = str(wrapper)
env["PYTHONPATH"] = str(tmp_path)
- assert Path(_run_powershell(shell, script, env)).resolve() == Path(sys.executable).resolve()
+ found = _run_powershell(shell, script, env)
+ if accepted:
+ assert found
+ assert Path(found).resolve() == Path(sys.executable).resolve()
+ else:
+ assert not found
@pytest.mark.skipif(not POWERSHELLS, reason = "PowerShell is unavailable")
diff --git a/tests/studio/install/test_install_manifest_damage.py b/tests/studio/install/test_install_manifest_damage.py
index b1d0cc134b0..0fdba19d38b 100644
--- a/tests/studio/install/test_install_manifest_damage.py
+++ b/tests/studio/install/test_install_manifest_damage.py
@@ -55,7 +55,8 @@ def _record(dist_info: Path, rows) -> None:
writer = csv.writer(buf, lineterminator = "\n")
for row in rows:
writer.writerow(row)
- (dist_info / "RECORD").write_text(buf.getvalue(), encoding = "utf-8", newline = "")
+ with (dist_info / "RECORD").open("w", encoding = "utf-8", newline = "") as handle:
+ handle.write(buf.getvalue())
def _write(path: Path, text: str) -> int:
diff --git a/tests/studio/install/test_mlx_install.py b/tests/studio/install/test_mlx_install.py
new file mode 100644
index 00000000000..f4f716f62cb
--- /dev/null
+++ b/tests/studio/install/test_mlx_install.py
@@ -0,0 +1,254 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""MLX installs must honor the platform, install mode, and supported versions."""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+import subprocess
+import sys
+from unittest.mock import Mock
+
+import pytest
+from packaging.requirements import Requirement
+
+import install_python_stack as stack
+
+
+class _BeforeExtras(Exception):
+ pass
+
+
+def _run_to_extras(
+ monkeypatch,
+ *,
+ platform,
+ skip_base,
+ no_torch,
+ shared_base = False,
+ mlx_error = None,
+ mlx_installable = True,
+):
+ monkeypatch.setenv("SKIP_STUDIO_BASE", "1" if skip_base else "0")
+ for name in ("STUDIO_LOCAL_REPO", "STUDIO_PACKAGE_NAME", "UNSLOTH_CI_SOURCE_OVERLAY"):
+ monkeypatch.delenv(name, raising = False)
+ for name, value in {
+ "IS_WINDOWS": platform == "windows",
+ "IS_LINUX": platform == "linux",
+ "IS_MACOS": platform.startswith("macos"),
+ "IS_MAC_ARM": platform == "macos_arm",
+ "NO_TORCH": no_torch,
+ "_rocm_windows_torch_installed": False,
+ }.items():
+ monkeypatch.setattr(stack, name, value)
+ for name, value in {
+ "_bootstrap_uv": True,
+ "_shared_base_requirements": stack.REQ_ROOT / "base.txt" if shared_base else None,
+ "_repair_duplicate_core_metadata": True,
+ "_repair_damaged_core_payload": True,
+ "_bitsandbytes_installed": False,
+ "_has_usable_nvidia_gpu": True,
+ "_ensure_cuda_torch": None,
+ "_ensure_rocm_torch": None,
+ "_ensure_xpu_torch": None,
+ "_ensure_cpu_torch": None,
+ "_ensure_xpu_triton": None,
+ "run": None,
+ # Off macOS the floor would skip every case; it has its own tests.
+ "_mlx_pins_are_installable": mlx_installable,
+ }.items():
+ monkeypatch.setattr(stack, name, Mock(return_value = value))
+ monkeypatch.setattr(stack.install_manifest, "remove_manifest", Mock(return_value = True))
+ monkeypatch.setattr(stack.install_manifest, "set_no_torch_marker", Mock())
+
+ def record_install(label, *args, **kwargs):
+ if label.startswith("Installing MLX") and mlx_error is not None:
+ raise mlx_error
+
+ install = Mock(side_effect = record_install)
+ monkeypatch.setattr(stack, "pip_install", install)
+ progress = stack._progress
+
+ steps: list[str] = []
+
+ def stop_before_extras(label):
+ if label == "unsloth extras":
+ raise _BeforeExtras
+ steps.append(label)
+ progress(label)
+
+ monkeypatch.setattr(stack, "_progress", stop_before_extras)
+ with pytest.raises(_BeforeExtras):
+ stack.install_python_stack()
+ # Labels reached before the stop, for callers asserting on the step not the install.
+ _run_to_extras.steps = steps
+ return [call for call in install.call_args_list if call.args[0].startswith("Installing MLX")]
+
+
+def _repair_specs():
+ path = Path(stack.SCRIPT_DIR) / "backend" / "utils" / "mlx_repair.py"
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ return next(
+ ast.literal_eval(node.value)
+ for node in tree.body
+ if isinstance(node, ast.Assign)
+ and any(
+ isinstance(target, ast.Name) and target.id == "_MLX_INSTALL_SPECS"
+ for target in node.targets
+ )
+ )
+
+
[email protected]("platform", ["macos_arm", "macos_intel", "linux", "windows"])
[email protected]("skip_base", [True, False], ids = ["fresh", "update"])
[email protected]("no_torch", [False, True], ids = ["training", "gguf_only"])
[email protected]("shared_base", [False, True], ids = ["empty_base", "shared_base"])
+def test_mlx_install_respects_platform_mode_and_pins(
+ monkeypatch, platform, skip_base, no_torch, shared_base
+):
+ calls = _run_to_extras(
+ monkeypatch,
+ platform = platform,
+ skip_base = skip_base,
+ no_torch = no_torch,
+ shared_base = shared_base,
+ )
+ enabled = platform == "macos_arm" and not no_torch
+ assert len(calls) == int(enabled)
+ if platform.startswith("macos"):
+ assert stack._TOTAL == (12 if skip_base and not shared_base else 13) + int(enabled)
+ if enabled:
+ requirements = [Requirement(arg) for arg in calls[0].args[1:] if not arg.startswith("-")]
+ actual = {req.name: str(req.specifier) for req in requirements}
+ expected = _repair_specs()
+ expected["mlx-metal"] = expected["mlx"]
+ assert actual == {
+ name: str(Requirement(name + spec).specifier) for name, spec in expected.items()
+ }
+
+
[email protected]("skip_base", [True, False], ids = ["fresh", "update"])
+ "error", [SystemExit(7), KeyboardInterrupt()], ids = ["failed", "interrupted"]
+)
+def test_failed_mlx_install_stops_before_extras(monkeypatch, skip_base, error):
+ write_manifest = Mock()
+ monkeypatch.setattr(stack.install_manifest, "write_manifest", write_manifest)
+ with pytest.raises(type(error)):
+ _run_to_extras(
+ monkeypatch, platform = "macos_arm", skip_base = skip_base, no_torch = False, mlx_error = error
+ )
+ write_manifest.assert_not_called()
+
+
+ "returncodes", [(0,), (1, 0), (1, 7)], ids = ["uv", "pip_fallback", "both_fail"]
+)
+def test_mlx_command_preserves_pins_and_interpreter_on_fallback(monkeypatch, returncodes):
+ with monkeypatch.context() as phase:
+ call = _run_to_extras(phase, platform = "macos_arm", skip_base = True, no_torch = False)[0]
+ monkeypatch.setattr(stack, "USE_UV", True)
+ monkeypatch.setattr(stack, "UV_NEEDS_SYSTEM", False)
+ monkeypatch.setattr(stack, "IS_WINDOWS", False)
+ monkeypatch.setattr(stack, "NO_TORCH", False)
+ commands = []
+ outcomes = iter(returncodes)
+
+ def run(cmd, **kwargs):
+ commands.append(cmd)
+ return subprocess.CompletedProcess(cmd, next(outcomes), b"resolver failed")
+
+ monkeypatch.setattr(stack.subprocess, "run", run)
+ if returncodes[-1]:
+ with pytest.raises(SystemExit) as exc:
+ stack.pip_install(*call.args, **call.kwargs)
+ assert exc.value.code == returncodes[-1]
+ else:
+ stack.pip_install(*call.args, **call.kwargs)
+ assert len(commands) == len(returncodes)
+ assert commands[0][:5] == ["uv", "pip", "install", "--python", sys.executable]
+ if len(commands) > 1:
+ assert commands[1][:4] == [sys.executable, "-m", "pip", "install"]
+ for command in commands:
+ assert {arg for arg in call.args[1:] if not arg.startswith("-")} <= set(command)
+ assert "--upgrade" in command
+ assert "-c" in command
+
+
+ "python_version, macos_major, installable",
+ [
+ ((3, 9, 6), 15, False), # macOS ships 3.9; no release in the pinned set has a cp39 wheel
+ ((3, 10, 0), 15, True),
+ ((3, 12, 0), 13, False), # Apple Silicon on Ventura: the pins are macosx_14_0 only
+ ((3, 12, 0), 14, True), # the first macOS the pinned wheels are built for
+ ((3, 12, 0), 26, True),
+ # Unreadable version: skipping costs a launch, attempting costs the install.
+ ((3, 12, 0), None, False),
+ ((3, 9, 6), 13, False),
+ ],
+)
+def test_mlx_pin_floor_matches_the_published_wheels(
+ monkeypatch, python_version, macos_major, installable
+):
+ """0.32.1 ships macosx_14_0_arm64 wheels, no sdist, and the pinned set starts at cp310."""
+ monkeypatch.setattr(stack.sys, "version_info", python_version)
+ monkeypatch.setattr(stack, "_macos_release_major", Mock(return_value = macos_major))
+ assert stack._mlx_pins_are_installable() is installable
+
+
+def test_pin_floor_is_revisited_whenever_the_pins_move():
+ """A pin bumped without its floor silently starts failing installs, so tie them here."""
+ assert _repair_specs() == {
+ "mlx": "==0.32.1",
+ "mlx-lm": "==0.31.3",
+ "mlx-vlm": ">=0.4.4,<0.7.0",
+ }
+ assert (stack._MLX_MIN_PYTHON, stack._MLX_MIN_MACOS_MAJOR) == ((3, 10), 14)
+
+
[email protected]("skip_base", [True, False], ids = ["fresh", "update"])
[email protected]("shared_base", [False, True], ids = ["empty_base", "shared_base"])
+def test_unsupported_apple_silicon_skips_mlx_without_failing_the_install(
+ monkeypatch, skip_base, shared_base
+):
+ """macOS 13 / Python 3.9 Apple Silicon still installs; it just stays chat-only.
+
+ Fresh never ran this step and update was unpinned, so neither could exit here before.
+ """
+ calls = _run_to_extras(
+ monkeypatch,
+ platform = "macos_arm",
+ skip_base = skip_base,
+ no_torch = False,
+ shared_base = shared_base,
+ mlx_installable = False,
+ )
+ assert calls == []
+ steps = _run_to_extras.steps
+ assert "MLX stack (Apple Silicon)" not in steps
+ assert "MLX stack (skipped, no wheel for this macOS or Python)" in steps
+ # A skipped step still spends its slot.
+ assert stack._TOTAL == (12 if skip_base and not shared_base else 13) + 1
+
+
+def test_supported_and_unsupported_hosts_share_one_progress_budget(monkeypatch):
+ """Same total either way, so the bar cannot end at 13/14 on an old Mac."""
+ _run_to_extras(
+ monkeypatch,
+ platform = "macos_arm",
+ skip_base = True,
+ no_torch = False,
+ mlx_installable = True,
+ )
+ supported = stack._TOTAL
+ _run_to_extras(
+ monkeypatch,
+ platform = "macos_arm",
+ skip_base = True,
+ no_torch = False,
+ mlx_installable = False,
+ )
+ assert stack._TOTAL == supported
diff --git a/tests/studio/install/test_no_torch_skips_mlx_stack.py b/tests/studio/install/test_no_torch_skips_mlx_stack.py
index 9f994821fad..66ff47cdf21 100644
--- a/tests/studio/install/test_no_torch_skips_mlx_stack.py
+++ b/tests/studio/install/test_no_torch_skips_mlx_stack.py
@@ -3,15 +3,11 @@
"""`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.
+The updater clears SKIP_STUDIO_BASE (`unsloth_cli/commands/studio.py`), so without the
+`not NO_TORCH` guard a routine update reinstalls MLX into a GGUF-only venv and the next
+launch enables Train before the no_torch verdict is reached. Invisible to the backend
+tests. Structural, like test_diffusers_pin.py: running the installer needs a Mac, and
+what must hold is a property of the gate, not of one run.
"""
from __future__ import annotations
@@ -30,22 +26,34 @@ 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``."""
+def _guard_chains_of_calls_mentioning(source: str, needle: str) -> list[list[str]]:
+ """Every enclosing `if` test, outermost first, for each call mentioning ``needle``.
+
+ A chain because the step sits under the platform gate and then under a wheel-floor
+ branch; only the outermost is the gate this file is about.
+ """
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(
+ chains: list[list[str]] = []
+
+ def walk(node, enclosing: list[str]):
+ for child in ast.iter_child_nodes(node):
+ inner = enclosing
+ if isinstance(child, ast.If):
+ inner = enclosing + [ast.get_source_segment(source, child.test) or ""]
+ if isinstance(child, ast.Call) and any(
isinstance(arg, ast.Constant) and isinstance(arg.value, str) and needle in arg.value
- for arg in call.args
+ for arg in child.args
):
- guards.append(ast.get_source_segment(source, node.test) or "")
- return guards
+ chains.append(enclosing)
+ walk(child, inner)
+
+ walk(tree, [])
+ return chains
+
+
+def _guards_of_calls_mentioning(source: str, needle: str) -> list[str]:
+ """The outermost `if` test guarding every call whose arguments mention ``needle``."""
+ return [chain[0] for chain in _guard_chains_of_calls_mentioning(source, needle) if chain]
def test_the_mlx_install_step_is_gated_on_no_torch():
@@ -64,8 +72,7 @@ def test_the_mlx_install_step_is_gated_on_no_torch():
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."""
+ """_TOTAL copies the gate; drift makes the bar count a step that never runs."""
source = _source()
step_guards = set(_guards_of_calls_mentioning(source, MLX_STEP_LABEL))
tree = ast.parse(source)
@@ -74,8 +81,8 @@ def test_the_progress_total_uses_the_same_gate_as_the_step():
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.
+ # Sliced by line: what names this branch is the trailing comment on the += 1,
+ # which a node's extent stops before.
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:
@@ -88,14 +95,12 @@ def test_the_progress_total_uses_the_same_gate_as_the_step():
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."""
+ """The premise: stop clearing this and the test above passes 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`."""
+ """No UNSLOTH_NO_TORCH is injected, so the manifest tier is what fires the gate on update."""
source = _source()
tree = ast.parse(source)
infer = next(