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: contain RAG embedder torch allocation crashes (#8609)

oobaboogaec9db28de1e5
diff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.py
index 642117c77bd..cab2b81dbd6 100644
--- a/studio/backend/core/rag/embeddings.py
+++ b/studio/backend/core/rag/embeddings.py
@@ -10,6 +10,9 @@ degrade to llama.cpp rather than crash when ST breaks on a machine: an init-time
probe falls back before any vector is produced (so spaces can't mix), and a
runtime ``encode`` failure swaps the process to llama-server for the rest of its
life (KBs already embedded with ST should then be reindexed).
+
+Torch driver faults bypass Python handlers, so ``_load_device`` probes allocation
+in a child and falls back to CPU without changing the embedding space.
"""
from __future__ import annotations
@@ -50,6 +53,36 @@ def _device() -> str:
return _TORCH_DEVICE.get(get_device(), "cpu")
+class TorchDeviceUnusableError(RuntimeError):
+ """Raised when torch cannot allocate safely on the accelerator or CPU."""
+
+
+def _load_device() -> str:
+ """Choose a device after probing for fatal torch driver failures in a child.
+
+ Fall back to CPU to preserve the embedding space. Raise only if CPU also
+ crashes, allowing the caller to select the GGUF backend."""
+ device = _device()
+ if device == "cpu":
+ return device
+
+ from utils.torch_device_probe import device_can_allocate
+
+ if device_can_allocate(device):
+ return device
+ if device_can_allocate("cpu"):
+ logger.warning(
+ "torch cannot allocate on %s without crashing; loading the embedding model "
+ "on CPU instead. This install's torch build does not match this machine.",
+ device,
+ )
+ return "cpu"
+ raise TorchDeviceUnusableError(
+ f"torch crashes when allocating on {device}; this install's torch build does "
+ "not match this machine"
+ )
+
+
_torchao_stub_done = False
@@ -351,17 +384,19 @@ def _get(model_name: str | None = None):
local_only = hf_env_offline()
with _lock:
if _model is None or _name != name:
+ # Probe before loading sentence-transformers on the selected device.
+ device = _load_device()
+ degraded_to_cpu = device == "cpu" and _device() != "cpu"
_install_torchao_stub_once()
from sentence_transformers import SentenceTransformer
from utils.hf_cache_settings import active_hf_hub_cache
- device = _device()
logger.info("loading embedding model %s on %s", name, device)
_guard_model_security(name, local_only)
st_kwargs = dict(
device = device,
cache_folder = active_hf_hub_cache(),
- model_kwargs = dtype_kwargs("float16"),
+ model_kwargs = dtype_kwargs("float32" if degraded_to_cpu else "float16"),
)
load_target = name
if local_only:
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index 621702dcfc0..44090c8fd0e 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -38,6 +38,8 @@ os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")
# it per-test; pin the default off for the whole suite so a new test elsewhere cannot
# reintroduce that by accident. setdefault, so an explicit override still wins.
os.environ.setdefault("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "0")
+# Avoid a cold torch subprocess in unrelated RAG tests. The probe tests re-enable it.
+os.environ.setdefault("UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE", "1")
@pytest.fixture(scope = "session")
diff --git a/studio/backend/tests/test_rag_embeddings.py b/studio/backend/tests/test_rag_embeddings.py
index fddb4d9be48..113c17a3b09 100644
--- a/studio/backend/tests/test_rag_embeddings.py
+++ b/studio/backend/tests/test_rag_embeddings.py
@@ -180,6 +180,36 @@ def test_sentence_transformer_load_uses_live_cache(monkeypatch, tmp_path):
assert observed["name"] == "Org/Embedder"
assert observed["cache_folder"] == str(tmp_path / "selected-hub")
+ assert list(observed["model_kwargs"].values()) == ["float16"]
+
+
+def test_accelerator_fallback_loads_float32_on_cpu(monkeypatch, tmp_path):
+ observed = {}
+
+ class FakeSentenceTransformer:
+ def __init__(self, name, **kwargs):
+ observed.update(kwargs)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "sentence_transformers",
+ SimpleNamespace(SentenceTransformer = FakeSentenceTransformer),
+ )
+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)
+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)
+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")
+ monkeypatch.setattr(embeddings, "_device", lambda: "cuda")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.active_hf_hub_cache",
+ lambda: str(tmp_path / "selected-hub"),
+ )
+ embeddings._model = None
+ embeddings._name = None
+
+ embeddings._get("Org/Embedder")
+
+ assert observed["device"] == "cpu"
+ assert list(observed["model_kwargs"].values()) == ["float32"]
class _SentinelLlamaBackend:
@@ -272,3 +302,83 @@ def test_st_encode_failure_without_llama_binary_reraises(monkeypatch):
embeddings._reset_backend()
with pytest.raises(RuntimeError, match = "CUDA error during encode"):
embeddings.encode(["alpha", "beta"])
+
+
+# Device selection after a fatal torch driver failure.
+
+
+def _patch_probe(monkeypatch, usable):
+ """Return configured probe results and record the devices checked."""
+ from utils import torch_device_probe
+
+ asked = []
+
+ def _can_allocate(device):
+ asked.append(device)
+ return usable[device]
+
+ monkeypatch.setattr(torch_device_probe, "device_can_allocate", _can_allocate)
+ return asked
+
+
+class _ImportIsACrash:
+ """Fail if sentence-transformers is reached after both device probes crash."""
+
+ def __getattr__(self, name):
+ raise AssertionError(f"sentence-transformers was reached ({name}) on a crashing host")
+
+
+def test_load_device_keeps_the_accelerator_when_it_is_usable(monkeypatch):
+ monkeypatch.setattr(embeddings, "_device", lambda: "cuda")
+ asked = _patch_probe(monkeypatch, {"cuda": True})
+ assert embeddings._load_device() == "cuda"
+ assert asked == ["cuda"]
+
+
+def test_load_device_degrades_to_cpu_when_the_accelerator_crashes(monkeypatch):
+ monkeypatch.setattr(embeddings, "_device", lambda: "cuda")
+ _patch_probe(monkeypatch, {"cuda": False, "cpu": True})
+ assert embeddings._load_device() == "cpu"
+
+
+def test_load_device_raises_when_torch_crashes_on_cpu_too(monkeypatch):
+ monkeypatch.setattr(embeddings, "_device", lambda: "cuda")
+ _patch_probe(monkeypatch, {"cuda": False, "cpu": False})
+ with pytest.raises(embeddings.TorchDeviceUnusableError):
+ embeddings._load_device()
+
+
+def test_load_device_does_not_probe_a_cpu_only_host(monkeypatch):
+ monkeypatch.setattr(embeddings, "_device", lambda: "cpu")
+ asked = _patch_probe(monkeypatch, {})
+ assert embeddings._load_device() == "cpu"
+ assert asked == []
+
+
+def test_a_real_crashing_child_moves_the_load_to_cpu(monkeypatch):
+ from utils import torch_device_probe
+
+ monkeypatch.setenv(torch_device_probe.DISABLE_ENV_VAR, "0")
+ monkeypatch.setattr(
+ torch_device_probe,
+ "_PROBE_SCRIPT",
+ "import ctypes, sys\nif sys.argv[1] != 'cpu': ctypes.string_at(0)",
+ )
+ torch_device_probe.device_can_allocate.cache_clear()
+ monkeypatch.setattr(embeddings, "_device", lambda: "cuda")
+ try:
+ assert embeddings._load_device() == "cpu"
+ finally:
+ torch_device_probe.device_can_allocate.cache_clear()
+
+
+def test_crashing_torch_falls_back_to_llama_server(monkeypatch):
+ monkeypatch.setattr(embeddings, "_device", lambda: "cuda")
+ _patch_probe(monkeypatch, {"cuda": False, "cpu": False})
+ _patch_llama_backend(monkeypatch, binary = "/fake/llama-server")
+ monkeypatch.setitem(sys.modules, "sentence_transformers", _ImportIsACrash())
+ embeddings._model = None
+ embeddings._name = None
+ embeddings._reset_backend()
+
+ assert isinstance(embeddings._get_backend(), _SentinelLlamaBackend)
diff --git a/studio/backend/tests/test_torch_device_probe.py b/studio/backend/tests/test_torch_device_probe.py
new file mode 100644
index 00000000000..9979003c38d
--- /dev/null
+++ b/studio/backend/tests/test_torch_device_probe.py
@@ -0,0 +1,498 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the out-of-process torch allocation probe."""
+
+import ast
+import os
+import signal
+import subprocess
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+from utils import process_lifetime, torch_device_probe
+
+
[email protected](autouse = True)
+def _fresh_probe(monkeypatch):
+ monkeypatch.setenv(torch_device_probe.DISABLE_ENV_VAR, "0")
+ monkeypatch.setattr(process_lifetime, "adopt_pid", lambda _pid: None)
+ monkeypatch.setattr(process_lifetime, "forget_pid", lambda _pid: None)
+ torch_device_probe.device_can_allocate.cache_clear()
+ yield
+ torch_device_probe.device_can_allocate.cache_clear()
+
+
+class _FakeProcess:
+ def __init__(
+ self,
+ *,
+ returncode = 0,
+ stderr = "",
+ timeouts = 0,
+ ):
+ self.returncode = returncode
+ self.pid = 4242
+ self.stderr = stderr
+ self.timeouts = timeouts
+ self.calls: list[str] = []
+
+ def communicate(self, timeout = None):
+ self.calls.append("communicate")
+ if self.timeouts:
+ self.timeouts -= 1
+ raise subprocess.TimeoutExpired("probe", timeout or 0)
+ return None, self.stderr
+
+ def terminate(self):
+ self.calls.append("terminate")
+
+ def kill(self):
+ self.calls.append("kill")
+
+ def wait(self):
+ self.calls.append("wait")
+
+
+def _patch_popen(
+ monkeypatch,
+ process,
+ calls = None,
+):
+ def _popen(argv, **kwargs):
+ if calls is not None:
+ calls.append((argv, kwargs))
+ return process
+
+ monkeypatch.setattr(subprocess, "Popen", _popen)
+
+
+def _run_script(monkeypatch, script):
+ monkeypatch.setattr(torch_device_probe, "_PROBE_SCRIPT", script)
+
+
+def test_probe_script_is_valid_python():
+ compile(torch_device_probe._PROBE_SCRIPT, "<probe>", "exec")
+
+
+def test_probe_script_initializes_blas_and_synchronizes():
+ script = torch_device_probe._PROBE_SCRIPT
+ assert "torch.ones" in script
+ assert "tensor @ tensor" in script
+ assert ".item()" in script
+
+
+def test_child_that_crashes_marks_the_device_unusable(monkeypatch):
+ _run_script(monkeypatch, "import ctypes; ctypes.string_at(0)")
+ assert torch_device_probe.device_can_allocate("cuda") is False
+
+
+def test_clean_child_marks_the_device_usable(monkeypatch):
+ _run_script(monkeypatch, "pass")
+ assert torch_device_probe.device_can_allocate("cuda") is True
+
+
+def test_child_raising_an_exception_does_not_condemn_the_device(monkeypatch):
+ _run_script(monkeypatch, "raise RuntimeError('no torch here')")
+ assert torch_device_probe.device_can_allocate("cuda") is True
+
+
+def test_hung_child_marks_the_device_unusable(monkeypatch):
+ _run_script(monkeypatch, "import time; time.sleep(30)")
+ monkeypatch.setattr(torch_device_probe, "PROBE_TIMEOUT_SECONDS", 1.0)
+ assert torch_device_probe.device_can_allocate("cuda") is False
+
+
+def test_unspawnable_probe_does_not_claim_the_accelerator_works(monkeypatch):
+ # A probe that never ran proves nothing, and the two ways of being wrong are not
+ # symmetric: CPU costs embedding speed, the accelerator costs the backend.
+ def _no_spawn(*_args, **_kwargs):
+ raise OSError("fork failed")
+
+ monkeypatch.setattr(subprocess, "Popen", _no_spawn)
+ assert torch_device_probe.device_can_allocate("cuda") is False
+
+
+def test_an_unrunnable_probe_still_leaves_cpu_available(monkeypatch):
+ # The opposite trade for CPU: it cannot fault a GPU driver, so a probe that never ran
+ # says nothing against it. Condemning it would push the caller past its CPU fallback
+ # to the GGUF backend, changing the embedding space over a passing failure to fork.
+ def _no_spawn(*_args, **_kwargs):
+ raise OSError("fork failed")
+
+ monkeypatch.setattr(subprocess, "Popen", _no_spawn)
+ assert torch_device_probe.device_can_allocate("cpu") is True
+
+
+def test_unreadable_probe_result_cleans_up_and_does_not_claim_the_device_works(monkeypatch):
+ process = _FakeProcess()
+
+ def _broken_communicate(timeout = None):
+ raise OSError("pipe failed")
+
+ process.communicate = _broken_communicate
+ _patch_popen(monkeypatch, process)
+
+ assert torch_device_probe.device_can_allocate("cuda") is False
+ assert "terminate" in process.calls
+
+
+def test_a_read_failure_during_teardown_does_not_escape(monkeypatch):
+ # The post-kill read used to sit inside the timeout branch, where the trailing
+ # except OSError was a sibling and could not catch it. A pipe failure there escaped
+ # device_can_allocate, so a device that really did time out raised instead of
+ # returning False, and the child never reached the reaper.
+ process = _FakeProcess(returncode = None, timeouts = 1)
+ reaped = threading.Event()
+ process.wait = lambda: reaped.set()
+ original = process.communicate
+
+ def _fail_after_first(timeout = None):
+ try:
+ return original(timeout = timeout)
+ finally:
+ process.communicate = _boom
+
+ def _boom(timeout = None):
+ process.calls.append("communicate")
+ raise OSError("pipe failed")
+
+ process.communicate = _fail_after_first
+ _patch_popen(monkeypatch, process)
+
+ assert torch_device_probe.device_can_allocate("cuda") is False
+ assert reaped.wait(timeout = 5), "unconfirmed child was never handed to the reaper"
+
+
+def test_result_is_cached_per_device(monkeypatch):
+ calls: list = []
+ _patch_popen(monkeypatch, _FakeProcess(), calls)
+
+ assert torch_device_probe.device_can_allocate("cuda") is True
+ assert torch_device_probe.device_can_allocate("cuda") is True
+ assert torch_device_probe.device_can_allocate("cpu") is True
+ assert [call[0][-2] for call in calls] == ["cuda", "cpu"]
+
+
+ "variable",
+ [
+ "CUDA_VISIBLE_DEVICES",
+ "HIP_VISIBLE_DEVICES",
+ "ROCR_VISIBLE_DEVICES",
+ "GPU_DEVICE_ORDINAL",
+ "HSA_OVERRIDE_GFX_VERSION",
+ # _TORCH_DEVICE maps DeviceType.XPU to "xpu", so the probe runs on Intel too and
+ # its selectors move the silicon underneath a cached verdict just as the rest do.
+ "ZE_AFFINITY_MASK",
+ "ONEAPI_DEVICE_SELECTOR",
+ ],
+)
+def test_device_identity_change_invalidates_cache(monkeypatch, variable):
+ calls: list = []
+ _patch_popen(monkeypatch, _FakeProcess(), calls)
+ monkeypatch.delenv(variable, raising = False)
+
+ assert torch_device_probe.device_can_allocate("cuda") is True
+ monkeypatch.setenv(variable, "changed")
+ assert torch_device_probe.device_can_allocate("cuda") is True
+ assert len(calls) == 2
+
+
+def test_every_visibility_mask_hardware_honours_is_part_of_the_cache_key():
+ """The two lists have to move together, or a cached verdict outlives its device.
+
+ hardware.py decides whether a visibility mask is filtering the device set. Any variable
+ it counts there renames the silicon behind "cuda", so a verdict cached before the change
+ would describe a GPU that is no longer the one being asked about. Read out of the source
+ rather than imported, since that module reaches for torch.
+ """
+ source = Path(torch_device_probe.__file__).with_name("hardware") / "hardware.py"
+ tree = ast.parse(source.read_text(encoding = "utf-8"))
+ masks = {
+ node.value
+ for function in ast.walk(tree)
+ if isinstance(function, ast.FunctionDef) and function.name == "_rocm_visibility_mask_active"
+ for node in ast.walk(function)
+ if isinstance(node, ast.Constant) and isinstance(node.value, str) and node.value.isupper()
+ }
+
+ assert masks, "hardware._rocm_visibility_mask_active no longer lists its variables"
+ assert masks <= set(torch_device_probe._DEVICE_IDENTITY_ENV_VARS)
+
+
+def test_disable_env_var_skips_the_child(monkeypatch):
+ def _no_spawn(*_args, **_kwargs):
+ raise AssertionError("probe spawned despite opt-out")
+
+ monkeypatch.setenv(torch_device_probe.DISABLE_ENV_VAR, "1")
+ monkeypatch.setattr(subprocess, "Popen", _no_spawn)
+ assert torch_device_probe.device_can_allocate("cuda") is True
+
+
+def test_child_uses_selected_device_without_preexec(monkeypatch):
+ calls: list = []
+ _patch_popen(monkeypatch, _FakeProcess(), calls)
+
+ assert torch_device_probe.device_can_allocate("xpu") is True
+ argv, kwargs = calls[0]
+ assert argv[0] == sys.executable
+ assert argv[-2] == "xpu"
+ assert "preexec_fn" not in kwargs
+
+
+def test_a_child_that_hit_its_own_deadline_is_a_failed_probe(monkeypatch):
+ # A child that stopped itself hung, and a hang is a device failure. Neither form was
+ # recognised before: SIGALRM is not a hard fault so it fell through _died_by_signal,
+ # and the Windows status is an ordinary non-zero exit. Both read as a healthy device,
+ # which let the parent make the allocation the probe stands in front of.
+ monkeypatch.setattr(torch_device_probe.os, "name", "posix")
+ _patch_popen(monkeypatch, _FakeProcess(returncode = -torch_device_probe._SIGALRM_NUMBER))
+ assert torch_device_probe.device_can_allocate("cuda") is False
+
+
+def test_the_windows_watchdog_status_is_a_failed_probe(monkeypatch):
+ monkeypatch.setattr(torch_device_probe.os, "name", "nt")
+ _patch_popen(monkeypatch, _FakeProcess(returncode = torch_device_probe._WATCHDOG_EXIT_STATUS))
+ assert torch_device_probe.device_can_allocate("cuda") is False
+
+
+def test_a_windows_crt_abort_is_a_failed_probe(monkeypatch):
+ # A native abort() on Windows leaves plain exit status 3, not an NTSTATUS, so nothing
+ # else here recognises it and the crashing device was being reported as usable.
+ monkeypatch.setattr(torch_device_probe.os, "name", "nt")
+ _patch_popen(
+ monkeypatch,
+ _FakeProcess(returncode = torch_device_probe._WINDOWS_ABORT_EXIT_STATUS),
+ )
+ assert torch_device_probe.device_can_allocate("cuda") is False
+
+
+def test_the_abort_status_is_read_as_a_crash_only_on_windows(monkeypatch):
+ # Elsewhere 3 is just an exit status a child chose, and an abort arrives as SIGABRT.
+ monkeypatch.setattr(torch_device_probe.os, "name", "posix")
+ assert (
+ torch_device_probe._died_by_signal(torch_device_probe._WINDOWS_ABORT_EXIT_STATUS) is False
+ )
+
+
+def test_the_abort_status_matches_the_one_llama_cpp_already_uses():
+ # Same CRT convention, two readers; a divergence here would be silent.
+ source = Path(torch_device_probe.__file__).parents[1] / "core" / "inference" / "llama_cpp.py"
+ tree = ast.parse(source.read_text(encoding = "utf-8"))
+ (function,) = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "_is_abort_exit"
+ ]
+ statuses = {
+ node.value
+ for node in ast.walk(function)
+ if isinstance(node, ast.Constant) and isinstance(node.value, int)
+ }
+ assert statuses == {torch_device_probe._WINDOWS_ABORT_EXIT_STATUS}
+
+
+def test_the_windows_watchdog_uses_the_status_the_parent_looks_for(monkeypatch):
+ # The child writes the number and the parent matches on the constant; they have to agree.
+ assert (
+ f"os._exit({torch_device_probe._WATCHDOG_EXIT_STATUS})" in torch_device_probe._PROBE_SCRIPT
+ )
+
+
+def test_the_child_deadline_does_not_depend_on_the_gil(monkeypatch):
+ # The deadline exists for a torch that hangs in a native call, and that is exactly when
+ # a threading.Timer cannot fire: its callback needs the GIL, which a long C call never
+ # returns to the interpreter to release. SIGALRM with no handler is enforced by the
+ # kernel, so it runs no Python at all.
+ script = torch_device_probe._PROBE_SCRIPT
+ assert "signal.alarm" in script
+ assert script.index("signal.alarm") < script.index("import torch")
+ # Windows has no alarm, so the timer stays as the fallback there.
+ assert "threading.Timer" in script
+
+
+def test_the_kernel_enforces_the_child_deadline():
+ # Proves the mechanism rather than trusting it: no handler is installed, so the default
+ # disposition terminates the process, and the exit is the signal itself.
+ if not hasattr(signal, "alarm"):
+ pytest.skip("POSIX only")
+ done = subprocess.run(
+ [sys.executable, "-c", "import signal, time; signal.alarm(1); time.sleep(30)"],
+ capture_output = True,
+ timeout = 60,
+ )
+ assert done.returncode == -int(signal.SIGALRM)
+
+
+def test_an_inherited_sigalrm_disposition_cannot_disarm_the_deadline():
+ # exec keeps an inherited SIG_IGN and an inherited blocked mask, so a supervisor that
+ # ignores or blocks SIGALRM would leave the deadline unenforceable and an orphaned probe
+ # running against a hung driver forever. The child restores the disposition itself.
+ if not hasattr(signal, "alarm"):
+ pytest.skip("POSIX only")
+ prologue = torch_device_probe._PROBE_SCRIPT.split("if sys.platform")[0]
+ child = prologue + "\nimport time\ntime.sleep(30)\n"
+ hostile = (
+ "import os, signal, sys\n"
+ "signal.signal(signal.SIGALRM, signal.SIG_IGN)\n"
+ "signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGALRM})\n"
+ "os.execv(sys.executable, [sys.executable, '-c', sys.argv[1], 'cpu', '1'])\n"
+ )
+ done = subprocess.run(
+ [sys.executable, "-c", hostile, child],
+ capture_output = True,
+ timeout = 60,
+ )
+ assert done.returncode == -int(signal.SIGALRM)
+
+
+def test_child_has_its_own_deadline(monkeypatch):
+ calls: list = []
+ _patch_popen(monkeypatch, _FakeProcess(), calls)
+
+ torch_device_probe.device_can_allocate("cuda")
+ argv = calls[0][0]
+ assert float(argv[-1]) > torch_device_probe.PROBE_TIMEOUT_SECONDS
+ script = argv[2]
+ assert script.index("threading.Timer") < script.index("import torch")
+ assert "daemon = True" in script
+ assert "os._exit" in script
+
+
+def test_child_is_tracked_until_it_exits(monkeypatch):
+ adopted: list[int] = []
+ forgotten: list[int] = []
+ monkeypatch.setattr(process_lifetime, "adopt_pid", adopted.append)
+ monkeypatch.setattr(process_lifetime, "forget_pid", forgotten.append)
+ process = _FakeProcess()
+ _patch_popen(monkeypatch, process)
+
+ torch_device_probe.device_can_allocate("cuda")
+ assert adopted == [process.pid]
+ assert forgotten == [process.pid]
+
+
+def test_timeout_escalates_and_reaps_a_survivor(monkeypatch):
+ forgotten: list[int] = []
+ monkeypatch.setattr(process_lifetime, "forget_pid", forgotten.append)
+ process = _FakeProcess(returncode = None, timeouts = 3)
+ reaped = threading.Event()
+
+ def _wait():
+ process.calls.append("wait")
+ reaped.set()
+
+ process.wait = _wait
+ _patch_popen(monkeypatch, process)
+
+ assert torch_device_probe.device_can_allocate("cuda") is False
+ assert process.calls[:5] == ["communicate", "terminate", "communicate", "kill", "communicate"]
+ assert reaped.wait(timeout = 5)
+ for _ in range(50):
+ if forgotten:
+ break
+ threading.Event().wait(0.02)
+ assert forgotten == [process.pid]
+
+
+def test_timeout_that_terminates_does_not_kill(monkeypatch):
+ process = _FakeProcess(returncode = -int(signal.SIGTERM), timeouts = 1)
+ _patch_popen(monkeypatch, process)
+
+ assert torch_device_probe.device_can_allocate("cuda") is False
+ assert "terminate" in process.calls
+ assert "kill" not in process.calls
+
+
+def test_windows_child_registers_rocm_dll_directories_before_torch(monkeypatch, tmp_path):
+ rocm_bin = tmp_path / "rocm" / "bin"
+ rocm_bin.mkdir(parents = True)
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setenv("HIP_PATH", str(tmp_path / "rocm"))
+ calls: list = []
+ _patch_popen(monkeypatch, _FakeProcess(), calls)
+
+ torch_device_probe.device_can_allocate("cuda")
+ argv, kwargs = calls[0]
+ assert str(rocm_bin) in kwargs["env"][torch_device_probe.ROCM_DLL_DIRS_ENV_VAR]
+ assert argv[2].index("add_dll_directory") < argv[2].index("import torch")
+
+
+def test_windows_rocm_directories_use_numeric_version_order(monkeypatch, tmp_path):
+ for version in ("6.3", "10.0", "7.0"):
+ (tmp_path / "AMD" / "ROCm" / version / "bin").mkdir(parents = True)
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setenv("ProgramFiles", str(tmp_path))
+ monkeypatch.delenv("HIP_PATH", raising = False)
+ monkeypatch.delenv("ROCM_PATH", raising = False)
+
+ found = torch_device_probe._rocm_dll_directories()
+ assert [Path(path).parent.name for path in found] == ["10.0", "7.0", "6.3"]
+
+
+ "returncode, on_windows, expected",
+ [
+ (-11, False, True),
+ (-6, False, True),
+ # Something else killed the probe; that says nothing about the device. The repo
+ # makes the same exclusion in LlamaCppBackend._is_signal_crash.
+ (-9, False, False),
+ (-15, False, False),
+ (-2, False, False),
+ (0, False, False),
+ (1, False, False),
+ (3221225477, True, True),
+ (3221226505, True, True),
+ (1, True, False),
+ (3221225477, False, False),
+ ],
+)
+def test_died_by_signal(monkeypatch, returncode, on_windows, expected):
+ monkeypatch.setattr(torch_device_probe.os, "name", "nt" if on_windows else "posix")
+ assert torch_device_probe._died_by_signal(returncode) is expected
+
+
[email protected]("killer", [9, 15, 1])
+def test_a_killed_probe_is_not_a_pass_for_an_accelerator(monkeypatch, killer):
+ # Not a hard fault, so it is no evidence against the device, but it is not the clean
+ # run that earns a pass either. Importing torch and building its device context is
+ # enough to trip a cgroup OOM on its own, and reading that as a pass sends the caller
+ # on to a much larger load in this process.
+ monkeypatch.setattr(torch_device_probe.os, "name", "posix")
+ _patch_popen(monkeypatch, _FakeProcess(returncode = -killer))
+ assert torch_device_probe.device_can_allocate("cuda") is False
+
+
+def test_a_killed_probe_still_leaves_cpu_available(monkeypatch):
+ # Same no-verdict trade as a probe that never ran: CPU cannot fault a GPU driver, and
+ # condemning it would push the caller past its CPU fallback to a different backend.
+ monkeypatch.setattr(torch_device_probe.os, "name", "posix")
+ _patch_popen(monkeypatch, _FakeProcess(returncode = -9))
+ assert torch_device_probe.device_can_allocate("cpu") is True
+
+
+def test_a_clean_child_is_still_a_pass(monkeypatch):
+ monkeypatch.setattr(torch_device_probe.os, "name", "posix")
+ _patch_popen(monkeypatch, _FakeProcess(returncode = 0))
+ assert torch_device_probe.device_can_allocate("cuda") is True
+
+
+def test_real_torch_allocates_on_cpu():
+ pytest.importorskip("torch")
+ probe = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ torch_device_probe._PROBE_SCRIPT,
+ "cpu",
+ str(torch_device_probe._CHILD_SELF_LIMIT_SECONDS),
+ ],
+ capture_output = True,
+ timeout = torch_device_probe.PROBE_TIMEOUT_SECONDS,
+ )
+ assert probe.returncode == 0, probe.stderr
diff --git a/studio/backend/utils/torch_device_probe.py b/studio/backend/utils/torch_device_probe.py
new file mode 100644
index 00000000000..3a4b285c67e
--- /dev/null
+++ b/studio/backend/utils/torch_device_probe.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
+
+"""Probe torch allocation in a child so driver crashes do not kill the backend.
+
+Only a child that ran cleanly to the end marks an accelerator usable. A crash, a hang, a
+kill and a probe that could not run or be read all leave it unusable, since the allocation
+this stands in front of ends the process rather than raising. Ordinary Python errors are
+the exception: the child ran and reported, so the in-process loader raises the same error
+and describes it better. CPU takes the opposite default, because it cannot fault a driver
+and condemning it would change the embedding backend. Set
+``UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE=1`` to skip the probe.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import sys
+import threading
+from functools import lru_cache
+
+from utils.child_stdio import utf8_child_env
+from utils.native_path_leases import child_env_without_native_path_secret
+from utils.subprocess_compat import windows_hidden_subprocess_kwargs
+
+logger = logging.getLogger(__name__)
+
+DISABLE_ENV_VAR = "UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE"
+ROCM_DLL_DIRS_ENV_VAR = "UNSLOTH_STUDIO_PROBE_ROCM_DLL_DIRS"
+
+# Allow for a cold torch import and driver initialization on a busy host.
+PROBE_TIMEOUT_SECONDS = 120.0
+# The child bounds its own lifetime if the parent disappears during the probe.
+_CHILD_SELF_LIMIT_SECONDS = 300.0
+_TERMINATE_GRACE_SECONDS = 5.0
+_STDERR_TAIL_CHARS = 600
+# SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV. Deliberately not SIGKILL or SIGTERM, which
+# say something killed the probe, not that the device cannot be used.
+_FATAL_SIGNALS = frozenset({4, 6, 7, 8, 11})
+# How a child reports that it stopped itself for running too long: the reserved exit status
+# it uses on Windows, and SIGALRM from the kernel-enforced deadline everywhere else.
+_WATCHDOG_EXIT_STATUS = 70
+_SIGALRM_NUMBER = 14
+# What the MSVC CRT abort() leaves behind on Windows. It is a plain exit status rather than
+# an NTSTATUS, so nothing else here would recognise it. Same value LlamaCppBackend
+# ._is_abort_exit already matches for GGML_ASSERT deaths.
+_WINDOWS_ABORT_EXIT_STATUS = 3
+
+# Anything that changes which physical device a device string names, or which kernels the
+# runtime emits for it. A change invalidates a cached verdict, since the same "cuda" or
+# "xpu" would then be a different piece of silicon: a stale pass could skip the probe on an
+# untested device, and a stale failure could pin a working one to CPU. The XPU selectors
+# matter because _TORCH_DEVICE maps DeviceType.XPU to "xpu", so this probe runs there too.
+_DEVICE_IDENTITY_ENV_VARS = (
+ "CUDA_VISIBLE_DEVICES",
+ "HIP_VISIBLE_DEVICES",
+ "ROCR_VISIBLE_DEVICES",
+ "GPU_DEVICE_ORDINAL",
+ "HSA_OVERRIDE_GFX_VERSION",
+ "ZE_AFFINITY_MASK",
+ "ONEAPI_DEVICE_SELECTOR",
+)
+
+# The matmul tests allocation and vendor BLAS initialization. item() synchronizes
+# the result so an asynchronous driver fault cannot escape after the child exits.
+# Windows DLL directories must be registered before importing torch because those
+# registrations are process-local and are not inherited by this interpreter.
+_PROBE_SCRIPT = """
+import os
+import signal
+import sys
+import threading
+
+# The deadline has to hold even when torch hangs inside a native call, which is the case
+# it exists for. A threading.Timer cannot: its callback needs the GIL, and a long C call
+# never returns to the interpreter loop to release it. SIGALRM with NO handler installed is
+# enforced by the kernel instead, so it does not run Python and does not need the GIL.
+# Windows has no alarm, so the timer stays as the fallback there.
+#
+# The disposition is restored first because exec keeps an inherited SIG_IGN and an inherited
+# blocked mask, so a supervisor that ignores or blocks SIGALRM would otherwise leave this
+# deadline unenforceable and an orphaned probe running against a hung driver forever.
+_deadline = float(sys.argv[2])
+if hasattr(signal, "alarm"):
+ signal.signal(signal.SIGALRM, signal.SIG_DFL)
+ if hasattr(signal, "pthread_sigmask"):
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGALRM})
+ signal.alarm(int(_deadline) or 1)
+else:
+ _watchdog = threading.Timer(_deadline, lambda: os._exit(70)) # _WATCHDOG_EXIT_STATUS
+ _watchdog.daemon = True
+ _watchdog.start()
+
+if sys.platform == "win32":
+ _handles = []
+ for _directory in os.environ.get(
+ "UNSLOTH_STUDIO_PROBE_ROCM_DLL_DIRS", ""
+ ).split(os.pathsep):
+ if _directory and os.path.isdir(_directory):
+ try:
+ _handles.append(os.add_dll_directory(_directory))
+ except (OSError, AttributeError):
+ pass
+
+import torch
+
+device = sys.argv[1]
+tensor = torch.ones((8, 8), dtype = torch.float16, device = device)
+(tensor @ tensor).sum().item()
+"""
+
+
+def _rocm_dll_directories() -> list[str]:
+ """Return Windows ROCm bin directories, newest version first."""
+ if sys.platform != "win32":
+ return []
+
+ candidates: list[str] = []
+ for variable in ("HIP_PATH", "ROCM_PATH"):
+ value = os.environ.get(variable)
+ if value:
+ candidates.append(os.path.join(value, "bin"))
+
+ default_root = os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "AMD", "ROCm")
+
+ def _version_key(name: str) -> tuple:
+ parts = []
+ for chunk in name.split("."):
+ try:
+ parts.append((0, int(chunk)))
+ except ValueError:
+ parts.append((1, chunk))
+ return tuple(parts)
+
+ try:
+ if os.path.isdir(default_root):
+ for version in sorted(os.listdir(default_root), key = _version_key, reverse = True):
+ bin_dir = os.path.join(default_root, version, "bin")
+ if os.path.isdir(bin_dir):
+ candidates.append(bin_dir)
+ except OSError:
+ pass
+
+ return list(dict.fromkeys(path for path in candidates if os.path.isdir(path)))
+
+
+def _died_by_signal(returncode: int) -> bool:
+ """Return whether the code represents a hard fault, not any death by signal.
+
+ SIGKILL and SIGTERM are excluded: the OOM killer, a container stop and an operator
+ all produce them, and they are not evidence the device faulted. Matches the hard-fault
+ set ``LlamaCppBackend._is_signal_crash`` already uses for the same reason. They are not
+ read as a pass either: the caller sends them to ``_unknown_verdict`` instead.
+
+ On Windows a native abort() takes both shapes: an NTSTATUS for an access violation,
+ and the CRT's plain exit status 3 when torch or a ROCm library calls abort() itself.
+ The second reads as an ordinary non-zero exit, so without it a crashing device was
+ reported as usable and the parent went on to repeat the crash in its own process.
+ """
+ if returncode < 0:
+ return -returncode in _FATAL_SIGNALS
+ if os.name != "nt":
+ return False
+ if returncode == _WINDOWS_ABORT_EXIT_STATUS:
+ return True
+ return (returncode & 0xC0000000) == 0xC0000000
+
+
+def _hit_its_own_deadline(returncode: int) -> bool:
+ """Whether the child stopped itself for running too long.
+
+ A child that reached its own deadline hung, and a hang is a device failure, so this
+ has to be read as one. Neither form is otherwise recognised: SIGALRM is not a hard
+ fault and would fall through ``_died_by_signal``, and the Windows status is an ordinary
+ non-zero exit. Both were being reported as a healthy device, which then let the parent
+ make the very allocation the probe stands in front of. It only comes up when the parent
+ did not enforce its own shorter timeout first, such as a suspended backend.
+ """
+ if returncode == _WATCHDOG_EXIT_STATUS:
+ return True
+ return os.name != "nt" and returncode == -_SIGALRM_NUMBER
+
+
+def _unknown_verdict(
+ device: str,
+ what_happened: str,
+ *,
+ exc_info: bool = True,
+) -> bool:
+ """What to answer when the probe produced no verdict at all.
+
+ Unusable for an accelerator: no evidence it is fine, and the two ways of being wrong
+ are not symmetric, since the allocation this stands in front of ends the process.
+
+ Usable for CPU, which is the opposite trade. A CPU load cannot fault a GPU driver, so
+ a probe that never ran says nothing against it, and condemning it here would send the
+ caller past its CPU fallback to the GGUF backend, changing the embedding space and
+ forcing a reindex over what may be a passing failure to fork.
+ """
+ usable = device == "cpu"
+ logger.warning(
+ "torch allocation probe on %s %s; treating the device as %s",
+ device,
+ what_happened,
+ "usable, since CPU cannot fault the driver" if usable else "unusable",
+ exc_info = exc_info,
+ )
+ return usable
+
+
+def _identity_key() -> tuple[str | None, ...]:
+ return tuple(os.environ.get(name) for name in _DEVICE_IDENTITY_ENV_VARS)
+
+
+def device_can_allocate(device: str) -> bool:
+ """Return false unless the device is known to be usable.
+
+ False when the child crashes or times out, and also when it could not be spawned or
+ its result could not be read. Those last two are not evidence the device is fine, only
+ that we do not know, and the two outcomes are not symmetric: guessing wrong towards
+ CPU costs embedding speed, guessing wrong towards the accelerator costs the backend,
+ since the allocation this stands in front of terminates the process rather than raising.
+
+ An ordinary exception from a child that RAN and reported still returns true. The
+ in-process loader will raise the same error and report it better than a silent
+ downgrade to CPU does. Results are cached per device and device-identity environment.
+ """
+ return _device_can_allocate_cached(device, _identity_key())
+
+
+@lru_cache(maxsize = None)
+def _device_can_allocate_cached(device: str, _identity: tuple[str | None, ...]) -> bool:
+ if os.environ.get(DISABLE_ENV_VAR) == "1":
+ return True
+
+ env = child_env_without_native_path_secret()
+ dll_directories = _rocm_dll_directories()
+ if dll_directories:
+ env[ROCM_DLL_DIRS_ENV_VAR] = os.pathsep.join(dll_directories)
+
+ try:
+ process = subprocess.Popen(
+ [sys.executable, "-c", _PROBE_SCRIPT, device, str(_CHILD_SELF_LIMIT_SECONDS)],
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.PIPE,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ env = utf8_child_env(env),
+ # No child_popen_kwargs() here. Its Linux preexec_fn can deadlock when
+ # this multithreaded backend forks and executes Python before exec.
+ **windows_hidden_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001 - no child ran, so nothing was proven
+ return _unknown_verdict(device, "could not run")
+
+ from utils.process_lifetime import adopt_pid, forget_pid
+
+ adopt_pid(process.pid)
+ try:
+ try:
+ _, stderr = process.communicate(timeout = PROBE_TIMEOUT_SECONDS)
+ except subprocess.TimeoutExpired:
+ stderr = _terminate_and_drain(process)
+ tail = (stderr or "").strip()[-_STDERR_TAIL_CHARS:]
+ logger.warning(
+ "torch allocation probe on %s did not finish in %.0fs; treating the "
+ "device as unusable%s",
+ device,
+ PROBE_TIMEOUT_SECONDS,
+ f": {tail}" if tail else "",
+ )
+ return False
+ except Exception: # noqa: BLE001 - no verdict, so the device is not known to work
+ _terminate_and_drain(process)
+ return _unknown_verdict(device, "could not be read")
+
+ if _hit_its_own_deadline(process.returncode):
+ logger.warning(
+ "torch allocation probe on %s ran past its own deadline and stopped "
+ "itself; treating the device as unusable",
+ device,
+ )
+ return False
+
+ if _died_by_signal(process.returncode):
+ tail = (stderr or "").strip()[-_STDERR_TAIL_CHARS:]
+ logger.warning(
+ "torch allocation probe on %s was killed (exit %s); this torch build "
+ "cannot use the device without crashing the process%s",
+ device,
+ process.returncode,
+ f": {tail}" if tail else "",
+ )
+ return False
+
+ if process.returncode < 0:
+ # Killed by something that is not a hard fault: an OOM kill, a container stop,
+ # an operator. That is not evidence against the device, but it is not the clean
+ # run this returns true for either, and importing torch and building its device
+ # context is itself enough to trip a cgroup limit. Reading it as a pass would
+ # send _load_device() on to a much larger load in this process, which is the
+ # death the probe exists to prevent, so it takes the no-verdict path instead.
+ return _unknown_verdict(
+ device,
+ f"was killed by signal {-process.returncode} without faulting",
+ exc_info = False,
+ )
+ return True
+ finally:
+ # A child handed to the asynchronous reaper remains adopted until it exits.
+ if process.returncode is not None:
+ forget_pid(process.pid)
+
+
+def _terminate_and_drain(process: subprocess.Popen) -> str:
+ """Bound cleanup after timeout and retain an unkillable child for reaping.
+
+ Escalates in one loop rather than nesting, so a single pair of handlers covers every
+ attempt. Nested, the post-kill read sat inside the timeout branch, where the trailing
+ ``except OSError`` was a sibling and could not see it: a pipe failure there escaped
+ ``device_can_allocate``, so a device that genuinely timed out raised instead of
+ returning False, the child never reached the reaper, and since ``lru_cache`` does not
+ cache exceptions the next call re-ran the whole probe.
+ """
+ stderr = ""
+ for signal_child in (process.terminate, process.kill):
+ try:
+ signal_child()
+ except OSError:
+ pass
+ try:
+ _, stderr = process.communicate(timeout = _TERMINATE_GRACE_SECONDS)
+ return stderr or ""
+ except subprocess.TimeoutExpired:
+ continue # still alive, escalate
+ except OSError:
+ break # pipes are unusable, so there is nothing left to drain
+
+ # Not confirmed dead, whether it outlived SIGKILL or could not be read. Either way the
+ # last reference must not simply be dropped.
+ _reap_later(process)
+ return stderr or ""
+
+
+def _reap_later(process: subprocess.Popen) -> None:
+ threading.Thread(
+ target = _wait_and_forget,
+ args = (process,),
+ daemon = True,
+ name = f"torch-device-probe-reaper-{process.pid}",
+ ).start()
+
+
+def _wait_and_forget(process: subprocess.Popen) -> None:
+ try:
+ process.wait()
+ except Exception: # noqa: BLE001 - best effort cleanup
+ pass
+ try:
+ from utils.process_lifetime import forget_pid
+ forget_pid(process.pid)
+ except Exception: # noqa: BLE001 - best effort cleanup
+ pass
+
+
+def _clear_probe_cache() -> None:
+ _device_can_allocate_cached.cache_clear()
+
+
+# Preserve the cache-control hook used by existing tests and callers.
+device_can_allocate.cache_clear = _clear_probe_cache # type: ignore[attr-defined]