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 SSM kernels: read the loaded torch build instead of a torch-import child per load (#16996)

Daniel Han59657068f27f
diff --git a/studio/backend/tests/test_ssm_runtime.py b/studio/backend/tests/test_ssm_runtime.py
index cea38ea2abb..fc15cc539d5 100644
--- a/studio/backend/tests/test_ssm_runtime.py
+++ b/studio/backend/tests/test_ssm_runtime.py
@@ -249,7 +249,7 @@ def test_install_kernel_uses_prebuilt_wheel(monkeypatch):
monkeypatch.setattr(
ssm_runtime,
"probe_torch_wheel_env",
- lambda timeout = 30, include_windows = False: {"x": "y", "cuda_version": "12.8"},
+ lambda timeout = 30, include_windows = False, **_: {"x": "y", "cuda_version": "12.8"},
)
seen = {}
monkeypatch.setattr(
@@ -292,7 +292,7 @@ def test_install_kernel_heartbeats_during_prebuilt_wheel(monkeypatch):
monkeypatch.setattr(
ssm_runtime,
"probe_torch_wheel_env",
- lambda timeout = 30, include_windows = False: {"cuda_version": "12.8"},
+ lambda timeout = 30, include_windows = False, **_: {"cuda_version": "12.8"},
)
monkeypatch.setattr(
ssm_runtime,
@@ -349,7 +349,7 @@ def test_install_kernel_heartbeats_through_the_import_check(monkeypatch):
monkeypatch.setattr(
ssm_runtime,
"probe_torch_wheel_env",
- lambda timeout = 30, include_windows = False: {"cuda_version": "12.8"},
+ lambda timeout = 30, include_windows = False, **_: {"cuda_version": "12.8"},
)
monkeypatch.setattr(
ssm_runtime,
@@ -420,7 +420,7 @@ def test_install_kernel_falls_back_to_source(monkeypatch):
monkeypatch.setattr(
ssm_runtime,
"probe_torch_wheel_env",
- lambda timeout = 30, include_windows = False: {"cuda_version": "12.8"},
+ lambda timeout = 30, include_windows = False, **_: {"cuda_version": "12.8"},
)
monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: None)
pip_cmds = []
@@ -596,7 +596,7 @@ def test_wheel_installed_but_not_importable_falls_back_to_source(monkeypatch):
monkeypatch.setattr(
ssm_runtime,
"probe_torch_wheel_env",
- lambda timeout = 30, include_windows = False: {"cuda_version": "12.8"},
+ lambda timeout = 30, include_windows = False, **_: {"cuda_version": "12.8"},
)
monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: "https://x/w.whl")
monkeypatch.setattr(ssm_runtime, "url_exists", lambda u: True)
@@ -623,7 +623,7 @@ def test_hip_source_build_requires_hipcc(monkeypatch):
monkeypatch.setattr(
ssm_runtime,
"probe_torch_wheel_env",
- lambda timeout = 30, include_windows = False: {"hip_version": "6.2"},
+ lambda timeout = 30, include_windows = False, **_: {"hip_version": "6.2"},
)
monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: None)
monkeypatch.setattr(ssm_runtime.shutil, "which", lambda name: None)
@@ -650,7 +650,7 @@ def test_source_build_reinstalls_to_replace_broken_wheel(monkeypatch):
monkeypatch.setattr(
ssm_runtime,
"probe_torch_wheel_env",
- lambda timeout = 30, include_windows = False: {"cuda_version": "12.8"},
+ lambda timeout = 30, include_windows = False, **_: {"cuda_version": "12.8"},
)
monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: None)
cmds = []
@@ -674,7 +674,7 @@ def test_hip_uv_source_build_uses_no_cache(monkeypatch):
monkeypatch.setattr(
ssm_runtime,
"probe_torch_wheel_env",
- lambda timeout = 30, include_windows = False: {"hip_version": "6.2"},
+ lambda timeout = 30, include_windows = False, **_: {"hip_version": "6.2"},
)
monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: None)
monkeypatch.setattr(ssm_runtime.shutil, "which", lambda name: "/usr/bin/" + name)
diff --git a/studio/backend/tests/test_torch_wheel_env_reuse.py b/studio/backend/tests/test_torch_wheel_env_reuse.py
new file mode 100644
index 00000000000..cccddd30a42
--- /dev/null
+++ b/studio/backend/tests/test_torch_wheel_env_reuse.py
@@ -0,0 +1,95 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""An SSM load reads the torch build from the torch it already imported instead of a 1-3 s child probe."""
+
+import json
+import subprocess
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from utils import ssm_runtime, wheel_utils
+
+
+def test_loaded_torch_matches_the_child_probe():
+ pytest.importorskip("torch")
+ if wheel_utils.wheel_platform_tag() is None:
+ pytest.skip("no wheel platform tag on this host")
+ child = wheel_utils.probe_torch_wheel_env(timeout = 120, include_windows = True)
+ reused = wheel_utils.probe_torch_wheel_env(
+ timeout = 120, include_windows = True, reuse_loaded_torch = True
+ )
+ assert child is not None
+ assert reused == child
+ assert list(reused) == list(child)
+
+
+ "version, cuda, hip",
+ [
+ ("2.10.0+cu128", "12.8", None),
+ ("2.9.1+rocm6.4", None, "6.4.43482"),
+ ("2.10.0+cpu", None, None),
+ ("2.11.0.dev20260101+cu130", "13.0", None),
+ ("2.10", "12.6.3", None),
+ ],
+)
+def test_loaded_stub_build_matches_the_child_probe(monkeypatch, tmp_path, version, cuda, hip):
+ monkeypatch.setattr(wheel_utils, "wheel_platform_tag", lambda: "linux_x86_64")
+ (tmp_path / "torch").mkdir()
+ (tmp_path / "torch" / "__init__.py").write_text(
+ f"__version__ = {version!r}\n"
+ f"class version:\n cuda = {cuda!r}\n hip = {hip!r}\n"
+ "class _C:\n _GLIBCXX_USE_CXX11_ABI = True\n",
+ encoding = "utf-8",
+ )
+ monkeypatch.setenv("PYTHONPATH", str(tmp_path))
+ monkeypatch.delitem(sys.modules, "torch", raising = False)
+ child = wheel_utils.probe_torch_wheel_env(timeout = 60)
+ stub = SimpleNamespace(
+ __version__ = version,
+ version = SimpleNamespace(cuda = cuda, hip = hip),
+ _C = SimpleNamespace(_GLIBCXX_USE_CXX11_ABI = True),
+ )
+ monkeypatch.setitem(sys.modules, "torch", stub)
+ reused = wheel_utils.probe_torch_wheel_env(timeout = 60, reuse_loaded_torch = True)
+ assert child is not None and child["torch_version"] == version
+ assert reused == child
+ assert list(reused) == list(child)
+
+
+def test_no_loaded_torch_falls_back_to_the_child(monkeypatch):
+ monkeypatch.setattr(wheel_utils, "wheel_platform_tag", lambda: "linux_x86_64")
+ monkeypatch.delitem(sys.modules, "torch", raising = False)
+ calls = []
+
+ def _run(cmd, **kwargs):
+ calls.append(cmd)
+ return SimpleNamespace(returncode = 0, stdout = json.dumps({"cuda_version": "12.8"}))
+
+ monkeypatch.setattr(subprocess, "run", _run)
+ env = wheel_utils.probe_torch_wheel_env(timeout = 5, reuse_loaded_torch = True)
+ assert env == {"cuda_version": "12.8", "platform_tag": "linux_x86_64"}
+ assert len(calls) == 1
+
+
+def test_windows_gate_still_applies_before_reuse(monkeypatch):
+ monkeypatch.setattr(wheel_utils, "wheel_platform_tag", lambda: "win_amd64")
+ monkeypatch.setitem(sys.modules, "torch", SimpleNamespace())
+ assert wheel_utils.probe_torch_wheel_env(reuse_loaded_torch = True) is None
+
+
+def test_ssm_torch_env_asks_for_the_loaded_torch(monkeypatch):
+ seen = []
+
+ def _probe(**kwargs):
+ seen.append(kwargs)
+ return {"cuda_version": "13.0", "cuda_major": "13"}
+
+ monkeypatch.setattr(ssm_runtime, "_TORCH_ENV", {})
+ monkeypatch.setattr(ssm_runtime, "probe_torch_wheel_env", _probe)
+ assert ssm_runtime._torch_env() == {"cuda_version": "13.0", "cuda_major": "13"}
+ assert ssm_runtime._torch_env() == {"cuda_version": "13.0", "cuda_major": "13"}
+ assert seen == [{"timeout": 30, "include_windows": True, "reuse_loaded_torch": True}]
diff --git a/studio/backend/utils/ssm_runtime.py b/studio/backend/utils/ssm_runtime.py
index 341780d06b6..69c4bc1b377 100644
--- a/studio/backend/utils/ssm_runtime.py
+++ b/studio/backend/utils/ssm_runtime.py
@@ -874,7 +874,7 @@ def _run_with_heartbeat(run, cmd, status_cb, display_name, **kwargs):
return run(cmd, **kwargs)
-# The torch build this process installs kernels for, probed once (one torch import in a child).
+# The torch build this process installs kernels for, read once (the loaded torch, else one torch import in a child).
_TORCH_ENV: dict = {}
# Kernels whose install already failed in this process, keyed by kernel, torch and toolchain, so a
# later load stage (or the next load in the same worker) does not download or compile them again.
@@ -884,7 +884,9 @@ _FAILED_INSTALLS: set = set()
def _torch_env() -> dict[str, str] | None:
key = probe_torch_wheel_env
if key not in _TORCH_ENV:
- _TORCH_ENV[key] = probe_torch_wheel_env(timeout = 30, include_windows = True)
+ _TORCH_ENV[key] = probe_torch_wheel_env(
+ timeout = 30, include_windows = True, reuse_loaded_torch = True
+ )
return _TORCH_ENV[key]
diff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.py
index 8441d4c90ba..198adeeb255 100644
--- a/studio/backend/utils/wheel_utils.py
+++ b/studio/backend/utils/wheel_utils.py
@@ -52,15 +52,51 @@ def wheel_platform_tag() -> str | None:
return None
+def _loaded_torch_wheel_env() -> dict[str, str] | None:
+ """The probe child's fields from the already imported torch, or None. Keep in step with the child below."""
+ torch = sys.modules.get("torch")
+ if torch is None:
+ return None
+ try:
+ import re
+ import sysconfig
+
+ parts = torch.__version__.split("+", 1)[0].split(".")[:2]
+ minor = re.sub(r"[^0-9].*", "", parts[1]) if len(parts) > 1 else "0"
+ cuda = torch.version.cuda
+ hip = getattr(torch.version, "hip", None)
+ py_tag = f"cp{sys.version_info.major}{sys.version_info.minor}"
+ return {
+ "python_tag": py_tag,
+ "abi_tag": py_tag + ("t" if sysconfig.get_config_var("Py_GIL_DISABLED") else ""),
+ "torch_mm": parts[0] + "." + minor,
+ "torch_version": str(torch.__version__),
+ "cuda_version": str(cuda) if cuda else "",
+ "cuda_major": str(int(str(cuda).split(".", 1)[0])) if cuda else "",
+ "hip_version": str(hip) if hip else "",
+ "cxx11abi": str(torch._C._GLIBCXX_USE_CXX11_ABI).upper(),
+ }
+ except Exception:
+ return None
+
+
def probe_torch_wheel_env(
- *, timeout: int | None = None, include_windows: bool = False
+ *,
+ timeout: int | None = None,
+ include_windows: bool = False,
+ reuse_loaded_torch: bool = False,
) -> dict[str, str] | None:
- """Describe the resident torch build for wheel-URL resolution, or None. Windows is opt-in via ``include_windows``, for callers whose every Windows URL names a published asset."""
+ """Describe the resident torch build for wheel-URL resolution, or None. Windows is opt-in via ``include_windows``, for callers whose every Windows URL names a published asset. ``reuse_loaded_torch`` reads an already imported torch instead of a 1-3 s child import."""
platform_tag = wheel_platform_tag()
if platform_tag is None:
return None
if platform_tag.startswith("win_") and not include_windows:
return None
+ if reuse_loaded_torch:
+ env = _loaded_torch_wheel_env()
+ if env is not None:
+ env["platform_tag"] = platform_tag
+ return env
try:
probe = subprocess.run(