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.

Unsloth Studio / Desktop (AMD, Windows): stop amd-smi from popping UAC/DiskPart prompts on the System page (#14041)

Leo Borcherding5ff4b8739091
diff --git a/studio/backend/tests/manual/windows_rocm_vram_check.py b/studio/backend/tests/manual/windows_rocm_vram_check.py
index 3f09c407a79..f30c0f96d63 100644
--- a/studio/backend/tests/manual/windows_rocm_vram_check.py
+++ b/studio/backend/tests/manual/windows_rocm_vram_check.py
@@ -13,9 +13,7 @@ This answers three questions on a real Windows ROCm box:
1. Does ``free_gb`` move when ANOTHER process holds VRAM? That is the PR's
entire claim, and it is the one that could silently be a no-op here:
hipMemGetInfo is system-wide on Linux but process-local on Windows WDDM.
- 2. Does reading the summary ever spawn amd-smi? On Windows without a HIP SDK
- it elevates a child and pops a UAC/DiskPart prompt, so the answer must be
- no spawns.
+ 2. Does reading the summary ever spawn amd-smi? Unless UNSLOTH_ENABLE_AMD_SMI=1, no.
3. What do the Windows-only gates actually evaluate to?
Run from ``studio/backend`` with the Unsloth venv's python::
@@ -263,8 +261,8 @@ def main() -> int:
# idle backend is in.
#
# Two calls, because "0 spawns" means different things on different boxes.
- # With a HIP SDK present amd-smi is ALLOWED and a spawn is correct, so the
- # as-configured run cannot by itself exercise the guard. The forced run
+ # With UNSLOTH_ENABLE_AMD_SMI=1 amd-smi is ALLOWED and a spawn is correct, so
+ # the as-configured run cannot by itself exercise the guard. The forced run
# drives _amd_smi_allowed() to False explicitly, which every new call site
# must honour whatever the host looks like.
import shutil
@@ -385,8 +383,7 @@ def main() -> int:
f"free_gb moved {new_drop:.2f} GiB, more than {held:.2f} GiB held plus "
f"2.00 GiB of process overhead: free is being under-reported"
)
- # A spawn is only a fault where the guard said no. With a HIP SDK present
- # amd-smi is allowed and calling it is the intended behaviour.
+ # A spawn is only a fault where the guard said no.
if allowed is False and spawns:
problems.append(
f"amd-smi was spawned {len(spawns)}x despite _amd_smi_allowed() being "
@@ -418,9 +415,9 @@ def main() -> int:
print("\n Note: amd-smi is not on PATH, so zero spawns is trivially true.")
print(" The refusal path is confirmed, the real no-SDK case is not.")
elif allowed is True:
- print("\n Note: a HIP SDK is present, so amd-smi is legitimately allowed")
- print(" here. The forced-refusal leg passed, but the genuine")
- print(" Windows-without-a-HIP-SDK case needs a box without one.")
+ print("\n Note: UNSLOTH_ENABLE_AMD_SMI opts in, so amd-smi is legitimately")
+ print(" allowed here. The forced-refusal leg passed; rerun without the")
+ print(" flag to check the default.")
return 0
diff --git a/studio/backend/tests/test_amd_smi_windows_silent_exit.py b/studio/backend/tests/test_amd_smi_windows_silent_exit.py
new file mode 100644
index 00000000000..eb2cd39c8d4
--- /dev/null
+++ b/studio/backend/tests/test_amd_smi_windows_silent_exit.py
@@ -0,0 +1,69 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""amd-smi on Windows that exits 0 with no stdout must be spawned once, not on every poll."""
+
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from utils.hardware import amd
+
+
+def spawns(monkeypatch):
+ calls = []
+
+ def _fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ return subprocess.CompletedProcess(cmd, 0, stdout = "", stderr = "Invalid platform\n")
+
+ monkeypatch.setattr(amd, "_amd_smi_disabled", False)
+ monkeypatch.setattr(amd, "_amd_smi_consecutive_failures", 0)
+ monkeypatch.setattr(amd, "_amd_smi_allowed", lambda: True)
+ monkeypatch.setattr(amd.shutil, "which", lambda name: "C:/Windows/System32/amd-smi.exe")
+ monkeypatch.setattr(amd.subprocess, "run", _fake_run)
+ return calls
+
+
+def test_windows_silent_exit_disables_after_one_spawn(spawns, monkeypatch):
+ monkeypatch.setattr(amd.platform, "system", lambda: "Windows")
+ for _ in range(5):
+ assert amd._run_amd_smi("metric") is None
+ assert len(spawns) == 1
+ assert amd._amd_smi_disabled is True
+
+
+def test_linux_silent_exit_keeps_polling(spawns, monkeypatch):
+ monkeypatch.setattr(amd.platform, "system", lambda: "Linux")
+ for _ in range(3):
+ assert amd._run_amd_smi("metric") is None
+ assert len(spawns) == 3
+ assert amd._amd_smi_disabled is False
+
+
+ "flag, allowed",
+ [(None, False), ("0", False), ("1", True), ("true", True)],
+)
+def test_windows_needs_explicit_opt_in_even_with_a_hip_sdk(monkeypatch, tmp_path, flag, allowed):
+ real_isfile, real_exists = amd.os.path.isfile, amd.os.path.exists
+ is_hipinfo = lambda p: str(p).lower().endswith("hipinfo.exe")
+ monkeypatch.setattr(amd.os.path, "isfile", lambda p: is_hipinfo(p) or real_isfile(p))
+ monkeypatch.setattr(amd.os.path, "exists", lambda p: is_hipinfo(p) or real_exists(p))
+ monkeypatch.setenv("PATH", str(tmp_path))
+ monkeypatch.setenv("HIP_PATH", str(tmp_path))
+ if flag is None:
+ monkeypatch.delenv("UNSLOTH_ENABLE_AMD_SMI", raising = False)
+ else:
+ monkeypatch.setenv("UNSLOTH_ENABLE_AMD_SMI", flag)
+ monkeypatch.setattr(amd.platform, "system", lambda: "Windows")
+ assert amd._amd_smi_allowed() is allowed
+
+
+def test_linux_always_allowed(monkeypatch):
+ monkeypatch.setattr(amd.platform, "system", lambda: "Linux")
+ monkeypatch.setenv("UNSLOTH_ENABLE_AMD_SMI", "0")
+ assert amd._amd_smi_allowed() is True
diff --git a/studio/backend/tests/test_system_poll_no_cuda_context.py b/studio/backend/tests/test_system_poll_no_cuda_context.py
index 2fa91b128a1..e9231eaa133 100644
--- a/studio/backend/tests/test_system_poll_no_cuda_context.py
+++ b/studio/backend/tests/test_system_poll_no_cuda_context.py
@@ -851,7 +851,6 @@ def test_context_free_never_spawns_amd_smi_on_windows_without_a_hip_sdk(monkeypa
raise FileNotFoundError("no amd-smi should be spawned here")
monkeypatch.setattr(amd, "platform", types.SimpleNamespace(system = lambda: "Windows"))
- monkeypatch.setattr(amd, "_hip_sdk_present", lambda: False)
monkeypatch.setattr(amd.shutil, "which", lambda _n: r"C:\rocm\bin\amd-smi.exe")
monkeypatch.setattr(amd.subprocess, "run", _spy)
monkeypatch.delenv("UNSLOTH_ENABLE_AMD_SMI", raising = False)
@@ -880,12 +879,14 @@ def test_context_free_never_spawns_amd_smi_on_windows_without_a_hip_sdk(monkeypa
@pytest.mark.skipif(sys.platform != "win32", reason = "the guard is Windows-only")
-def test_amd_smi_is_refused_on_a_real_windows_host_without_a_hip_sdk():
+def test_amd_smi_is_refused_on_a_real_windows_host_unless_opted_in():
# The test above fakes the platform. This one runs the same predicate against
# the real OS, PATH and environment, so the guard is pinned where it applies.
from utils.hardware import amd
- if amd._hip_sdk_present() or os.environ.get("UNSLOTH_ENABLE_AMD_SMI"):
- pytest.skip("this host may legitimately run amd-smi un-elevated")
+ if os.environ.get("UNSLOTH_ENABLE_AMD_SMI", "").strip().lower() in ("1", "true", "yes", "on"):
+ pytest.skip(
+ reason = "UNSLOTH_ENABLE_AMD_SMI opts this host in, so amd-smi is allowed by design"
+ )
assert amd._amd_smi_allowed() is False
diff --git a/studio/backend/utils/hardware/amd.py b/studio/backend/utils/hardware/amd.py
index 9249032a057..c01fea84da7 100644
--- a/studio/backend/utils/hardware/amd.py
+++ b/studio/backend/utils/hardware/amd.py
@@ -13,7 +13,6 @@ import shlex
import shutil
import stat
import subprocess
-import sys
import threading
import time
from pathlib import PurePath
@@ -34,56 +33,12 @@ _amd_smi_consecutive_failures = 0
_amd_smi_disabled = False
-def _path_inside_venv(path: str) -> bool:
- """True if ``path`` is inside the active venv (sys.prefix). The venv hipInfo.exe (AMD wheel, put on PATH by main.py/worker.py for bitsandbytes) is NOT a HIP SDK (see _hip_sdk_present)."""
- try:
- # realpath (not abspath): resolve symlinks/8.3 names so an aliased venv matches.
- root = os.path.normcase(os.path.realpath(sys.prefix))
- # Guard a root-dir prefix (C:\ or /): commonpath would match every path on it. A venv is never at root, so treat that as outside.
- if os.path.dirname(root) == root:
- return False
- return os.path.normcase(os.path.commonpath([os.path.realpath(path), root])) == root
- except (ValueError, OSError):
- # Different drive / unresolvable -> treat as outside the venv.
- return False
-
-
-def _external_hipinfo_on_path() -> bool:
- """True if a hipinfo OUTSIDE the venv is on PATH. shutil.which returns only the first hit, so the venv hipInfo could shadow a real HIP SDK's; scan every PATH entry and skip the venv copy."""
- for directory in os.environ.get("PATH", "").split(os.pathsep):
- directory = directory.strip('"') # PATH entries can be quoted on Windows
- if not directory:
- continue
- candidate = os.path.join(directory, "hipinfo.exe")
- if os.path.isfile(candidate) and not _path_inside_venv(candidate):
- return True
- return False
-
-
-def _hip_sdk_present() -> bool:
- """True if a HIP SDK is detectable (hipinfo on PATH or under HIP_PATH/ROCM_PATH), so amd-smi has a runtime and runs un-elevated. Ignores the venv hipInfo.exe (AMD wheel via the bnb fix): not a HIP SDK, and does not stop amd-smi's DiskPart UAC."""
- if _external_hipinfo_on_path():
- return True
- for var in ("HIP_PATH", "HIP_PATH_57", "ROCM_PATH"):
- root = os.environ.get(var)
- if not root:
- continue
- candidate = os.path.join(root, "bin", "hipinfo.exe")
- if os.path.exists(candidate) and not _path_inside_venv(candidate):
- return True
- return False
-
-
def _amd_smi_allowed() -> bool:
- """Whether it is safe to spawn amd-smi here. On Windows without a working HIP runtime, amd-smi elevates a child at runtime, popping a UAC/DiskPart prompt that RunAsInvoker cannot suppress (its manifest is asInvoker), so only call it on Windows with a HIP SDK present or UNSLOTH_ENABLE_AMD_SMI=1. Linux amd-smi never elevates."""
+ """Windows is opt-in only (UNSLOTH_ENABLE_AMD_SMI=1): amd-smi.exe pops a UAC/DiskPart prompt RunAsInvoker cannot suppress, even with a HIP SDK."""
if platform.system() != "Windows":
return True
flag = os.environ.get("UNSLOTH_ENABLE_AMD_SMI", "").strip().lower()
- if flag in ("1", "true", "yes", "on"):
- return True
- if flag in ("0", "false", "no", "off"):
- return False
- return _hip_sdk_present()
+ return flag in ("1", "true", "yes", "on")
def _run_amd_smi(
@@ -96,11 +51,10 @@ def _run_amd_smi(
if _amd_smi_disabled:
return None
if not _amd_smi_allowed():
- # Permanently skip amd-smi on Windows without a HIP SDK: every call pops a UAC/DiskPart prompt. VRAM polling is then unavailable, which beats the prompt (UNSLOTH_ENABLE_AMD_SMI=1 opts back in).
if not _amd_smi_disabled:
logger.info(
- "amd-smi disabled on Windows (no HIP SDK detected) to avoid a "
- "UAC/DiskPart elevation prompt; GPU VRAM polling unavailable. "
+ "amd-smi disabled on Windows to avoid a UAC/DiskPart elevation "
+ "prompt; VRAM comes from the adapter perf counters. "
"Set UNSLOTH_ENABLE_AMD_SMI=1 to force amd-smi."
)
_amd_smi_disabled = True
@@ -158,7 +112,17 @@ def _run_amd_smi(
_amd_smi_disabled = True
return None
if not result.stdout.strip():
- logger.debug("amd-smi exited 0 but returned no output")
+ if platform.system() == "Windows":
+ # System32 amd-smi.exe exits 0 with no stdout when it can't run, prompting each spawn.
+ logger.info(
+ "amd-smi exited 0 with no output (%s); GPU utilization polling via amd-smi disabled",
+ (result.stderr or "").strip().splitlines()[-1]
+ if (result.stderr or "").strip()
+ else "no stderr",
+ )
+ _amd_smi_disabled = True
+ else:
+ logger.debug("amd-smi exited 0 but returned no output")
return None
_amd_smi_consecutive_failures = 0
try:
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index bc4cb32f0ec..e1d4ac592ca 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -286,7 +286,7 @@ def _probe_physical_gpu_inventory() -> Dict[str, Any]:
devices.extend(nvidia_devices)
sources.append(result.get("source") or "nvidia-smi")
- # Windows AMD has no vendor CLI guaranteed present (amd-smi elevates a child without a HIP SDK), but the DirectX registry records every adapter with its dedicated memory.
+ # Windows AMD: amd-smi is opt-in, but the DirectX registry records every adapter's dedicated memory.
if platform.system() == "Windows":
# The registry outlives the hardware, so a record only RE-LABELS an adapter the live WMI scan also returned, never adds one (setup.ps1 has the same rule).
_live = _windows_live_adapter_names()
diff --git a/tests/studio/install/test_pr5940_followups.py b/tests/studio/install/test_pr5940_followups.py
index 800b62e7fcc..6d62959c85b 100644
--- a/tests/studio/install/test_pr5940_followups.py
+++ b/tests/studio/install/test_pr5940_followups.py
@@ -31,7 +31,6 @@ _SPEC.loader.exec_module(prebuilt)
_INSTALL_PS1 = PACKAGE_ROOT / "install.ps1"
_SETUP_PS1 = PACKAGE_ROOT / "studio" / "setup.ps1"
_INSTALL_SH = PACKAGE_ROOT / "install.sh"
-_AMD_PY = PACKAGE_ROOT / "studio" / "backend" / "utils" / "hardware" / "amd.py"
_PYSTACK_PY = PACKAGE_ROOT / "studio" / "install_python_stack.py"
@@ -334,7 +333,7 @@ def test_external_hipinfo_on_path_skips_venv_only(tmp_path):
def test_python_hipinfo_gates_scan_all_path_entries():
- for src in (_PREBUILT_PATH, _AMD_PY, _PYSTACK_PY):
+ for src in (_PREBUILT_PATH, _PYSTACK_PY):
text = src.read_text(encoding = "utf-8")
assert (
"_external_hipinfo_on_path" in text
@@ -543,14 +542,14 @@ def test_external_hipinfo_strips_quoted_path_entries(tmp_path):
def test_python_hipinfo_strips_quotes_in_all_copies():
- for src in (_PREBUILT_PATH, _AMD_PY, _PYSTACK_PY):
+ for src in (_PREBUILT_PATH, _PYSTACK_PY):
text = src.read_text(encoding = "utf-8")
assert "strip('\"')" in text, f"{src.name} must strip quotes from PATH entries"
def test_python_path_inside_venv_guards_root_prefix_in_all_copies():
# A bare-root sys.prefix makes commonpath match every path, disabling amd-smi.
- for src in (_PREBUILT_PATH, _AMD_PY, _PYSTACK_PY):
+ for src in (_PREBUILT_PATH, _PYSTACK_PY):
text = src.read_text(encoding = "utf-8")
assert (
"os.path.dirname(" in text and ") == " in text and "return False" in text