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 (macOS): read the Metal working set from torch when MLX is missing (#13695)
Daniel Han936e316d03c3
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex de45e984860..76884e767f3 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -13780,7 +13780,7 @@ class LlamaCppBackend:No GPU is enumerated on Metal, so the context would default to native andover-commit unified memory ("Compute error." at decode, #5118/#6529). Use a- fraction of MLX's Metal working-set, else total RAM; 0 off Apple Silicon or+ fraction of the Metal working set, else total RAM; 0 off Apple Silicon orwhen unresolvable, so callers skip the cap.Both of those inputs describe the MACHINE, not the moment. MLX's@@ -13805,13 +13805,9 @@ class LlamaCppBackend:if not is_apple_silicon():return 0- rec_bytes = 0- try:- import mlx.core as mx- if mx.metal.is_available():- rec_bytes = int(mx.device_info().get("max_recommended_working_set_size") or 0)- except Exception:- rec_bytes = 0+ from utils.hardware.hardware import _metal_recommended_working_set_bytes++ rec_bytes = _metal_recommended_working_set_bytes()vm = Nonetry:import psutil@@ -14004,15 +14000,8 @@ class LlamaCppBackend:return 0# 0 means the kernel default, Metal's recommended working set.if cap_bytes <= 0:- try:- import mlx.core as mx- from utils.hardware.hardware import _mlx_device_info- if mx.metal.is_available():- cap_bytes = int(- _mlx_device_info(mx).get("max_recommended_working_set_size") or 0- )- except Exception:- cap_bytes = 0+ from utils.hardware.hardware import _metal_recommended_working_set_bytes+ cap_bytes = _metal_recommended_working_set_bytes()if cap_bytes <= 0:return 0from utils.hardware.hardware import _read_apple_gpu_stats@@ -14035,14 +14024,10 @@ class LlamaCppBackend:headroom = LlamaCppBackend._apple_metal_wired_ceiling_bytes()if headroom <= 0:return 0.0- try:- import mlx.core as mx- from utils.hardware.hardware import _mlx_device_info+ from utils.hardware.hardware import _metal_recommended_working_set_bytes- if not mx.metal.is_available():- return 0.0- seen = int(_mlx_device_info(mx).get("max_recommended_working_set_size") or 0)- except Exception:+ seen = _metal_recommended_working_set_bytes()+ if seen <= 0:return 0.0return max(0.0, (seen - headroom) / (1024 * 1024))diff --git a/studio/backend/tests/test_llama_cpp_context_fit.py b/studio/backend/tests/test_llama_cpp_context_fit.pyindex 45ce1c0f8cb..dc5d1861adf 100644--- a/studio/backend/tests/test_llama_cpp_context_fit.py+++ b/studio/backend/tests/test_llama_cpp_context_fit.py@@ -724,8 +724,24 @@ def test_select_gpus_reserves_per_device_overhead():def _force_apple(monkeypatch):import platform as _platform+monkeypatch.setattr(_platform, "system", lambda: "Darwin")monkeypatch.setattr(_platform, "machine", lambda: "arm64")+ # The working-set reader falls back to torch.mps; keep the host's torch out of it.+ monkeypatch.setitem(sys.modules, "torch", None)+++def _install_fake_torch_mps(+ monkeypatch,+ working_set_bytes,+ available = True,+):+ fake = _types.ModuleType("torch")+ fake.backends = _types.SimpleNamespace(+ mps = _types.SimpleNamespace(is_available = lambda: available)+ )+ fake.mps = _types.SimpleNamespace(recommended_max_memory = lambda: working_set_bytes)+ monkeypatch.setitem(sys.modules, "torch", fake)def _install_fake_mlx(monkeypatch, working_set_bytes):@@ -782,6 +798,34 @@ class TestAppleUnifiedMemoryBudget:36 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION)+ def test_without_mlx_torch_mps_supplies_the_working_set(self, monkeypatch):+ """macOS 13 has no MLX wheel; budgeting from total RAM exceeds what ggml-metal can use."""+ _force_apple(monkeypatch)+ monkeypatch.setitem(sys.modules, "mlx", None)+ _install_fake_torch_mps(monkeypatch, 10 * GIB)+ _install_fake_psutil(monkeypatch, total = 16 * GIB, available = 14 * GIB)+ assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(+ 10 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION+ )++ def test_mlx_wins_over_torch_mps(self, monkeypatch):+ _force_apple(monkeypatch)+ _install_fake_mlx(monkeypatch, 10 * GIB)+ _install_fake_torch_mps(monkeypatch, 12 * GIB)+ _install_fake_psutil(monkeypatch, total = 16 * GIB, available = 14 * GIB)+ assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(+ 10 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION+ )++ def test_torch_without_mps_keeps_total_ram(self, monkeypatch):+ _force_apple(monkeypatch)+ monkeypatch.setitem(sys.modules, "mlx", None)+ _install_fake_torch_mps(monkeypatch, 10 * GIB, available = False)+ _install_fake_psutil(monkeypatch, total = 16 * GIB, available = 16 * GIB)+ assert LlamaCppBackend._apple_metal_memory_budget_bytes() == int(+ 16 * GIB * _APPLE_UNIFIED_MEMORY_FRACTION+ )+def test_a_busy_machine_budgets_from_what_is_free(self, monkeypatch):"""The reporter's shape: 16 GB Mac already holding several GB.@@ -891,6 +935,12 @@ class TestAppleWiredCeiling:_install_wired_probes(monkeypatch, sysctl_mb = 0, working_set = 0, in_use = 2 * GIB)assert _REAL_WIRED_CEILING() == 0+ def test_without_mlx_the_default_limit_comes_from_torch_mps(self, monkeypatch):+ _install_wired_probes(monkeypatch, sysctl_mb = 0, working_set = 0, in_use = 2 * GIB)+ monkeypatch.setitem(sys.modules, "mlx", None)+ _install_fake_torch_mps(monkeypatch, 48 * GIB)+ assert _REAL_WIRED_CEILING() == int(46 * GIB * _APPLE_WIRED_CEILING_FRACTION)+@pytest.mark.parametrize("counter,expected",[diff --git a/studio/backend/tests/test_metal_explicit_context_guard.py b/studio/backend/tests/test_metal_explicit_context_guard.pyindex f74b8021e31..fcaf2d880de 100644--- a/studio/backend/tests/test_metal_explicit_context_guard.py+++ b/studio/backend/tests/test_metal_explicit_context_guard.py@@ -1860,6 +1860,8 @@ class TestFitterKeepsTheWiredHeadroom:mlx.core = coremonkeypatch.setitem(sys.modules, "mlx", mlx)monkeypatch.setitem(sys.modules, "mlx.core", core)+ # The working-set reader falls back to torch.mps; keep the host's torch out of it.+ monkeypatch.setitem(sys.modules, "torch", None)@pytest.mark.parametrize("seen_gib,headroom_gib,expected_mib",diff --git a/studio/backend/tests/test_metal_working_set_sources_agree.py b/studio/backend/tests/test_metal_working_set_sources_agree.pynew file mode 100644index 00000000000..2dab2161ac0--- /dev/null+++ b/studio/backend/tests/test_metal_working_set_sources_agree.py@@ -0,0 +1,39 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""On a real Apple Silicon Mac, torch.mps and MLX report the same Metal working set.++The torch reading is the fallback for hosts without MLX (macOS 13), so it must be the same+number the MLX path has always budgeted from. Skipped anywhere both cannot be imported.+"""++import platform+import sys++import pytest++pytestmark = pytest.mark.skipif(+ sys.platform != "darwin" or platform.machine() != "arm64",+ reason = "needs Apple Silicon",+)+++def test_torch_mps_matches_mlx_working_set(monkeypatch):+ mx = pytest.importorskip("mlx.core")+ torch = pytest.importorskip("torch")+ if not (mx.metal.is_available() and torch.backends.mps.is_available()):+ pytest.skip("Metal unavailable to MLX or torch")+ if not hasattr(torch.mps, "recommended_max_memory"):+ pytest.skip("torch < 2.5")++ from utils.hardware import hardware++ with_mlx = hardware._metal_recommended_working_set_bytes()+ assert with_mlx == int(+ hardware._mlx_device_info(mx).get("max_recommended_working_set_size") or 0+ )+ assert with_mlx > 0++ monkeypatch.setitem(sys.modules, "mlx", None)+ monkeypatch.setitem(sys.modules, "mlx.core", None)+ assert hardware._metal_recommended_working_set_bytes() == with_mlxdiff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex e54a0975ac2..50d53e4df5a 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -2099,6 +2099,25 @@ def _mlx_device_info(mx: Any) -> Dict[str, Any]:return {}+def _metal_recommended_working_set_bytes() -> int:+ """Metal's recommendedMaxWorkingSetSize, or 0. MLX first; torch.mps (2.5+) covers macOS 13, which has no MLX wheel."""+ try:+ import mlx.core as mx+ if mx.metal.is_available():+ rec = int(_mlx_device_info(mx).get("max_recommended_working_set_size") or 0)+ if rec > 0:+ return rec+ except Exception:+ pass+ try:+ import torch+ if torch.backends.mps.is_available():+ return max(0, int(torch.mps.recommended_max_memory()))+ except Exception:+ pass+ return 0++def _apple_unified_free_bytes(available_bytes: int, device_info: Any) -> int:"""What is available right now, bounded by the Metal working set. Total RAM minus GPU-only usage counts host RAM as free, which the training-method policy reads as room it does not have. The cap is not reduced by the AGX "In use system memory" counter, which is whole-device and only the active subset, while the working set is the per-process budget torch.mps applies. A floor rather than a capacity: macOS reclaims compressed and file-backed pages, and reading low costs a QLoRA suggestion where reading high costs an OOM mid-run."""free = max(0, int(available_bytes or 0))