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: skip the MPS cache clear when torch has no usable Metal device (#16326)

Daniel Han56462bb1d722
diff --git a/studio/backend/tests/test_clear_mps_cache_guard.py b/studio/backend/tests/test_clear_mps_cache_guard.py
new file mode 100644
index 00000000000..769f464a994
--- /dev/null
+++ b/studio/backend/tests/test_clear_mps_cache_guard.py
@@ -0,0 +1,61 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Clearing the MPS cache must not crash an Apple Silicon host that has no usable Metal device."""
+
+from __future__ import annotations
+
+import platform
+import subprocess
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+from utils.hardware import hardware as hw
+
+BACKEND_ROOT = Path(__file__).resolve().parents[1]
+
+
+def _fake_torch(monkeypatch, available):
+ calls = []
+ torch = types.ModuleType("torch")
+ torch.mps = types.SimpleNamespace(empty_cache = lambda: calls.append("empty_cache"))
+ torch.backends = types.SimpleNamespace(
+ mps = types.SimpleNamespace(is_available = lambda: available)
+ )
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ return calls
+
+
+def test_the_mps_cache_is_left_alone_without_a_metal_device(monkeypatch):
+ calls = _fake_torch(monkeypatch, available = False)
+ hw._clear_mps_cache()
+ assert calls == []
+
+
+def test_the_mps_cache_is_still_cleared_with_a_metal_device(monkeypatch):
+ calls = _fake_torch(monkeypatch, available = True)
+ hw._clear_mps_cache()
+ assert calls == ["empty_cache"]
+
+
+ sys.platform != "darwin" or platform.machine() != "arm64", reason = "Apple Silicon only"
+)
+def test_clearing_the_mps_cache_does_not_crash_this_host():
+ """A subprocess, so a segfault in torch.mps reads as a failure rather than killing the run."""
+ pytest.importorskip("torch")
+ code = (
+ "import sys, torch\n"
+ f"sys.path.insert(0, {str(BACKEND_ROOT)!r})\n"
+ "print('mps available', torch.backends.mps.is_available(), 'built', torch.backends.mps.is_built(), flush = True)\n"
+ "from utils.hardware import hardware\n"
+ "hardware._clear_mps_cache()\n"
+ "print('cleared', flush = True)\n"
+ )
+ proc = subprocess.run([sys.executable, "-c", code], capture_output = True, text = True, timeout = 300)
+ assert (
+ proc.returncode == 0 and "cleared" in proc.stdout
+ ), f"exit {proc.returncode}\nstdout:\n{proc.stdout[-2000:]}\nstderr:\n{proc.stderr[-2000:]}"
diff --git a/studio/backend/tests/test_utils.py b/studio/backend/tests/test_utils.py
index 1a2eb278f16..b993f4ffeb3 100644
--- a/studio/backend/tests/test_utils.py
+++ b/studio/backend/tests/test_utils.py
@@ -182,6 +182,7 @@ class TestClearGpuCache:
with (
patch("utils.hardware.hardware.get_device", return_value = DeviceType.CPU),
patch("utils.hardware.hardware.is_apple_silicon", return_value = True),
+ patch("torch.backends.mps.is_available", return_value = True),
patch("torch.mps.empty_cache") as mock_empty,
):
clear_gpu_cache()
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 7f5e9af9294..ce7dce8aa9d 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -2334,8 +2334,11 @@ def _clear_mps_cache() -> None:
"""Return torch's MPS reservations to the shared pool: Apple Silicon also runs torch MPS, whose caching allocator keeps freed buffers reserved, and those bytes read as used system memory, so the next load budgets against a pool that looks smaller than it is."""
try:
import torch
+
empty_cache = getattr(getattr(torch, "mps", None), "empty_cache", None)
- if callable(empty_cache):
+ mps_backend = getattr(getattr(torch, "backends", None), "mps", None)
+ # Without a usable Metal device (a macOS VM's paravirtual GPU) empty_cache segfaults rather than raising.
+ if callable(empty_cache) and mps_backend is not None and mps_backend.is_available():
empty_cache()
except Exception as e:
logger.debug("Failed to clear MPS cache: %s", e)