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: escape the dependency fast path when AMD torch is the wrong wheel (#9499)

oobabooga47670fa9345c
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 9863b5025e7..0cd7a8b7de1 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -29,9 +29,12 @@ import textwrap
import urllib.request
from pathlib import Path
-_BACKEND_DIR = Path(__file__).resolve().parent / "backend"
-if str(_BACKEND_DIR) not in sys.path:
- sys.path.insert(1, str(_BACKEND_DIR))
+_STUDIO_DIR = Path(__file__).resolve().parent
+_BACKEND_DIR = _STUDIO_DIR / "backend"
+for _dir in (_BACKEND_DIR, _STUDIO_DIR):
+ # -P / PYTHONSAFEPATH drops the script directory, so do not rely on sys.path[0].
+ if str(_dir) not in sys.path:
+ sys.path.insert(1, str(_dir))
# setup.sh/setup.ps1 invoke this by path, so its directory is sys.path[0].
import install_manifest # noqa: E402
@@ -1906,9 +1909,13 @@ def _clear_confirmed_hsa_spoof(physical_gfx: str) -> None:
)
+# First-set-wins order, as _pick_visible_index documents below.
+_VISIBLE_DEVICE_MASKS = ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")
+
+
def _first_set_visible_mask() -> "str | None":
"""Name of the visible-device variable in force, first-set-wins, or None."""
- for _env in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ for _env in _VISIBLE_DEVICE_MASKS:
if os.environ.get(_env) is not None:
return _env
return None
@@ -2845,6 +2852,66 @@ def _ensure_cpu_torch() -> None:
)
+def _amd_torch_needs_dependency_pass() -> bool:
+ """Return True when setup must run the dependency pass to repair non-ROCm torch.
+
+ Scope is the wheel family, not the ROCm family: any ROCm marker keeps the fast path
+ even when the repair would reroute it. Fails closed on an uncertain host or torch,
+ and never installs.
+ """
+ if NO_TORCH or not IS_LINUX:
+ return False
+ # ROCm wheels are published for Linux x86_64 only.
+ if platform.machine().lower() not in {"x86_64", "amd64"}:
+ return False
+ # install.sh's resolved backend is authoritative, exactly as it is for the repair.
+ if _TORCH_BACKEND in ("cuda", "cpu", "xpu"):
+ return False
+ # A ROCm pin bypasses hardware detection; any other pin owns its repair path.
+ if _explicit_rocm_torch_index_url() is None:
+ if _explicit_torch_index_url() is not None:
+ return False
+ if _has_usable_nvidia_gpu():
+ return False
+ # ROCr filters beneath HIP, so a hidden layer either side leaves no target to
+ # classify. CUDA_VISIBLE_DEVICES is the HIP alias, read only when HIP is unset.
+ _hip_mask = (
+ "HIP_VISIBLE_DEVICES" if "HIP_VISIBLE_DEVICES" in os.environ else "CUDA_VISIBLE_DEVICES"
+ )
+ if any(
+ (os.environ.get(_mask) or "").strip() in ("", "-1")
+ for _mask in ("ROCR_VISIBLE_DEVICES", _hip_mask)
+ if _mask in os.environ
+ ):
+ return False
+ # Match the repair's two host signals: a visible GPU or an inferred/named arch.
+ _inferred_gfx = _infer_linux_amd_gfx_arch()
+ _rocm_visible = _has_rocm_gpu()
+ if not _rocm_visible and not _inferred_gfx:
+ return False
+ # Probe and runtime mask indexing can disagree on mixed-arch hosts.
+ if len(set(_detect_amd_gfx_codes())) > 1:
+ return False
+ # The inferred per-arch repair can run without a readable ROCm version.
+ _inferred_arm = (
+ bool(_inferred_gfx)
+ and bool((os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip() or not _rocm_visible)
+ and _amd_arch_index_url(_inferred_gfx) is not None
+ )
+ if not _inferred_arm:
+ # Other repair arms need a readable version with a published wheel family.
+ _ver = _detect_rocm_version()
+ if _ver is None or _generic_pytorch_rocm_tag(_ver) is None:
+ return False
+
+ _ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
+ # An unreadable torch is not evidence that its wheel family is wrong.
+ if not (_ran and _importable) or not _version:
+ return False
+ # The +rocm tag covers builds that omit torch.version.hip.
+ return not (_hip or "rocm" in _version.lower())
+
+
def _ensure_rocm_torch() -> None:
"""Reinstall torch with ROCm wheels when the venv received CPU-only torch.
@@ -3206,14 +3273,7 @@ def _ensure_rocm_torch() -> None:
index_url = _override_idx
tag = _torch_index_leaf(index_url)
else:
- tag = next(
- (
- t
- for (maj, mn), t in sorted(_ROCM_TORCH_INDEX.items(), reverse = True)
- if ver >= (maj, mn)
- ),
- None,
- )
+ tag = _generic_pytorch_rocm_tag(ver)
if tag is None:
_safe_print(
f" No PyTorch wheel for ROCm {ver[0]}.{ver[1]} -- skipping torch reinstall"
@@ -5626,4 +5686,11 @@ def install_python_stack() -> int:
if __name__ == "__main__":
+ if sys.argv[1:] == ["--amd-torch-needs-dependency-pass"]:
+ # Exit 0 forces the dependency pass; exit 1 keeps the fast path.
+ sys.exit(0 if _amd_torch_needs_dependency_pass() else 1)
+ if any(_arg.startswith("-") for _arg in sys.argv[1:]):
+ # Never let a malformed probe call fall through into a multi-gigabyte install.
+ _safe_print(f"Unknown argument: {' '.join(sys.argv[1:])}")
+ sys.exit(2)
sys.exit(install_python_stack())
diff --git a/studio/setup.sh b/studio/setup.sh
index f6dfea89920..89c74bb0a77 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -1964,6 +1964,25 @@ sys.exit(0 if installed is not None and required is not None and installed >= re
fi
fi
+# A current package can still have CPU/CUDA torch because the fast path skips ROCm repair.
+# Exit 0 forces the dependency pass; failures and timeouts keep the fast path.
+if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -x "$VENV_DIR/bin/python" ]; then
+ _setup_amd_torch_stale=false
+ if command -v timeout >/dev/null 2>&1; then
+ timeout -k 5 180 "$VENV_DIR/bin/python" \
+ "$SCRIPT_DIR/install_python_stack.py" --amd-torch-needs-dependency-pass \
+ >/dev/null 2>&1 && _setup_amd_torch_stale=true
+ elif "$VENV_DIR/bin/python" "$SCRIPT_DIR/install_python_stack.py" \
+ --amd-torch-needs-dependency-pass >/dev/null 2>&1; then
+ _setup_amd_torch_stale=true
+ fi
+ if [ "$_setup_amd_torch_stale" = true ]; then
+ substep "installed PyTorch is not a ROCm build on this AMD host -- forcing dependency pass to repair..."
+ substep " (set UNSLOTH_TORCH_BACKEND=cpu to keep a deliberate CPU install)"
+ _SKIP_PYTHON_DEPS=false
+ fi
+fi
+
if [ "$_SKIP_PYTHON_DEPS" = false ]; then
install_python_stack
else
diff --git a/tests/sh/test_setup_amd_fastpath_escape.sh b/tests/sh/test_setup_amd_fastpath_escape.sh
new file mode 100755
index 00000000000..01fb755e06f
--- /dev/null
+++ b/tests/sh/test_setup_amd_fastpath_escape.sh
@@ -0,0 +1,98 @@
+#!/bin/bash
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# Test setup.sh wiring: exit 0 forces the pass and all other statuses keep it.
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"
+WORK=$(mktemp -d)
+trap 'rm -rf "$WORK"' EXIT
+PASS=0
+FAIL=0
+
+# The escape block, from its guard to the first dedented `fi`.
+awk '/^if \[ "\$_SKIP_PYTHON_DEPS" = true \] && \[ -x "\$VENV_DIR\/bin\/python" \]; then/ {on=1}
+ on {print}
+ on && /^fi$/ {exit}' "$SETUP_SH" > "$WORK/escape.sh"
+grep -q -- "--amd-torch-needs-dependency-pass" "$WORK/escape.sh" || {
+ echo "FATAL: AMD escape block not found in $SETUP_SH" >&2; exit 1; }
+
+assert_eq() {
+ _label="$1"; _expected="$2"; _actual="$3"
+ if [ "$_actual" = "$_expected" ]; then
+ echo " PASS: $_label"; PASS=$((PASS + 1))
+ else
+ echo " FAIL: $_label (expected '$_expected', got '$_actual')"; FAIL=$((FAIL + 1))
+ fi
+}
+
+VENV_DIR="$WORK/venv"
+mkdir -p "$VENV_DIR/bin"
+: > "$WORK/install_python_stack.py"
+
+# A stand-in interpreter that records its arguments and exits with $PROBE_RC.
+cat > "$VENV_DIR/bin/python" <<'STUB'
+#!/bin/sh
+printf '%s\n' "$*" >> "$PROBE_LOG"
+exit "$PROBE_RC"
+STUB
+chmod +x "$VENV_DIR/bin/python"
+
+run_escape() {
+ (
+ PROBE_RC="$1"
+ _SKIP_PYTHON_DEPS="${2:-true}"
+ export PROBE_RC PROBE_LOG
+ SCRIPT_DIR="$WORK"
+ substep() { :; }
+ # shellcheck disable=SC1090
+ . "$WORK/escape.sh"
+ echo "$_SKIP_PYTHON_DEPS"
+ )
+}
+
+PROBE_LOG="$WORK/calls.txt"
+: > "$PROBE_LOG"
+export PROBE_LOG
+
+echo "=== only a conclusive answer forces the pass ==="
+assert_eq "exit 0 forces the dependency pass" "false" "$(run_escape 0)"
+assert_eq "exit 1 keeps the fast path" "true" "$(run_escape 1)"
+
+echo "=== every probe failure keeps the fast path ==="
+# Probe errors keep the fast path, including the deadline: 124 on GNU, 143 on BusyBox.
+for rc in 2 124 125 126 127 137 143; do
+ assert_eq "exit $rc keeps the fast path" "true" "$(run_escape "$rc")"
+done
+
+echo "=== the fallback branch, on hosts without timeout ==="
+# PATH holds only the stub bin, so `command -v timeout` fails and the elif runs.
+run_no_timeout() { (PATH="$VENV_DIR/bin"; run_escape "$1"); }
+assert_eq "exit 0 forces the pass without timeout" "false" "$(run_no_timeout 0)"
+assert_eq "exit 1 keeps the fast path without timeout" "true" "$(run_no_timeout 1)"
+: > "$PROBE_LOG"
+run_no_timeout 0 >/dev/null
+assert_eq "and still probes exactly once" "1" "$(wc -l < "$PROBE_LOG" | tr -d ' ')"
+
+echo "=== the block does nothing it was not asked to ==="
+assert_eq "a pass already forced is left forced" "false" "$(run_escape 1 false)"
+assert_eq "and the probe is not run at all in that case" \
+ "0" "$(: > "$PROBE_LOG"; run_escape 1 false >/dev/null; wc -l < "$PROBE_LOG" | tr -d ' ')"
+: > "$PROBE_LOG"
+run_escape 0 >/dev/null
+assert_eq "the probe is asked exactly once" "1" "$(wc -l < "$PROBE_LOG" | tr -d ' ')"
+assert_eq "with the module and the flag, and nothing else" \
+ "$WORK/install_python_stack.py --amd-torch-needs-dependency-pass" \
+ "$(cat "$PROBE_LOG")"
+
+echo "=== a missing interpreter is not probed ==="
+mv "$VENV_DIR/bin/python" "$WORK/python.away"
+: > "$PROBE_LOG"
+assert_eq "no venv python keeps the fast path" "true" "$(run_escape 0)"
+assert_eq "and spawns nothing" "0" "$(wc -l < "$PROBE_LOG" | tr -d ' ')"
+mv "$WORK/python.away" "$VENV_DIR/bin/python"
+
+echo ""
+echo "Results: $PASS passed, $FAIL failed"
+[ "$FAIL" -eq 0 ]
diff --git a/tests/studio/install/test_amd_fastpath_probe.py b/tests/studio/install/test_amd_fastpath_probe.py
new file mode 100644
index 00000000000..4700a8f6dfc
--- /dev/null
+++ b/tests/studio/install/test_amd_fastpath_probe.py
@@ -0,0 +1,433 @@
+# 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 setup.sh's AMD torch fast-path escape."""
+
+import importlib.util
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+PACKAGE_ROOT = Path(__file__).resolve().parents[3]
+_STACK_PATH = PACKAGE_ROOT / "studio" / "install_python_stack.py"
+_STACK_SPEC = importlib.util.spec_from_file_location("studio_ips_amd_fastpath", _STACK_PATH)
+assert _STACK_SPEC is not None and _STACK_SPEC.loader is not None
+stack = importlib.util.module_from_spec(_STACK_SPEC)
+sys.modules[_STACK_SPEC.name] = stack
+_STACK_SPEC.loader.exec_module(stack)
+
+_ROUTING_ENV = (
+ "UNSLOTH_TORCH_INDEX_URL",
+ "UNSLOTH_TORCH_INDEX_FAMILY",
+ "UNSLOTH_TORCH_BACKEND",
+ "UNSLOTH_NO_TORCH",
+ "UNSLOTH_ROCM_GFX_ARCH",
+ "HIP_VISIBLE_DEVICES",
+ "ROCR_VISIBLE_DEVICES",
+ "CUDA_VISIBLE_DEVICES",
+)
+
+
+def _host(
+ monkeypatch,
+ *,
+ torch = ("2.9.0", ""),
+ ran = True,
+ importable = True,
+ gfx = ("gfx1151",),
+ rocm_gpu = True,
+ rocm_ver = (6, 4),
+ inferred = None,
+ nvidia = False,
+ backend = "",
+ machine = "x86_64",
+ linux = True,
+ no_torch = False,
+ env = None,
+):
+ """A ROCm host with a CPU wheel by default; each argument moves one thing."""
+ for name in _ROUTING_ENV:
+ monkeypatch.delenv(name, raising = False)
+ for name, value in (env or {}).items():
+ monkeypatch.setenv(name, value)
+ monkeypatch.setattr(stack, "IS_LINUX", linux)
+ monkeypatch.setattr(stack, "NO_TORCH", no_torch)
+ monkeypatch.setattr(stack, "_TORCH_BACKEND", backend)
+ monkeypatch.setattr(stack.platform, "machine", lambda: machine)
+ monkeypatch.setattr(stack, "_has_usable_nvidia_gpu", lambda: nvidia)
+ monkeypatch.setattr(stack, "_has_rocm_gpu", lambda: rocm_gpu and not nvidia)
+ monkeypatch.setattr(stack, "_detect_amd_gfx_codes", lambda dedup = True: list(gfx))
+ monkeypatch.setattr(stack, "_detect_rocm_version", lambda: rocm_ver)
+ monkeypatch.setattr(stack, "_infer_linux_amd_gfx_arch", lambda: inferred)
+ version, hip = torch
+ monkeypatch.setattr(stack, "_probe_torch_runtime", lambda: (ran, importable, version, hip, ""))
+
+ # Nothing here may install: the dependency pass it unlocks owns that.
+ def _no_installs(*_a, **_k):
+ raise AssertionError("the fast-path probe must not install anything")
+
+ monkeypatch.setattr(stack, "pip_install", _no_installs)
+ monkeypatch.setattr(stack, "pip_install_try", _no_installs)
+
+
+def _needs_pass():
+ return stack._amd_torch_needs_dependency_pass()
+
+
+# Wrong wheel
+
+
+ "version",
+ ["2.9.0+cpu", "2.9.0+cu128", "2.9.0", "2.8.0a0+34c6371d24.nv25.08"],
+)
+def test_a_non_rocm_wheel_on_a_rocm_host_forces_the_pass(monkeypatch, version):
+ _host(monkeypatch, torch = (version, ""))
+ assert _needs_pass() is True
+
+
+def test_an_explicit_rocm_pin_answers_without_a_hardware_probe(monkeypatch):
+ """The pin commits to ROCm wheels headless, as _ensure_rocm_torch already does."""
+ _host(
+ monkeypatch,
+ torch = ("2.9.0+cpu", ""),
+ rocm_gpu = False,
+ gfx = (),
+ env = {"UNSLOTH_TORCH_INDEX_URL": "https://download.pytorch.org/whl/rocm6.4"},
+ )
+ assert _needs_pass() is True
+
+
+def test_a_real_device_selection_is_not_a_hidden_host(monkeypatch):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), env = {"HIP_VISIBLE_DEVICES": "1"})
+ assert _needs_pass() is True
+
+
+# Correct wheel
+
+
+ "torch",
+ [
+ ("2.9.0+rocm6.4", "6.4"),
+ ("2.9.0+rocm6.4", ""),
+ ("2.11.0+rocm7.13.0", "7.13"),
+ # AMD and source builds carry torch.version.hip with no +rocm local version.
+ ("2.5.0a0+git1234567", "6.2.41134"),
+ ],
+)
+def test_a_rocm_wheel_keeps_the_fast_path(monkeypatch, torch):
+ _host(monkeypatch, torch = torch)
+ assert _needs_pass() is False
+
+
+# Uncertain classification
+
+
+ "kwargs",
+ [
+ pytest.param({"ran": False}, id = "probe-did-not-run"),
+ pytest.param({"importable": False}, id = "torch-does-not-import"),
+ pytest.param({"torch": (None, "")}, id = "no-version-reported"),
+ pytest.param({"torch": ("", "")}, id = "empty-version-reported"),
+ ],
+)
+def test_an_unreadable_torch_keeps_the_fast_path(monkeypatch, kwargs):
+ _host(monkeypatch, **kwargs)
+ assert _needs_pass() is False
+
+
+def test_a_mixed_arch_host_keeps_the_fast_path(monkeypatch):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), gfx = ("gfx1151", "gfx1100"))
+ assert _needs_pass() is False
+
+
+def test_two_cards_of_one_arch_are_not_ambiguous(monkeypatch):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), gfx = ("gfx1100", "gfx1100"))
+ assert _needs_pass() is True
+
+
+ "mask", ["HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"]
+)
[email protected]("value", ["", "-1", " "])
+def test_a_mask_that_hides_every_device_keeps_the_fast_path(monkeypatch, mask, value):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), env = {mask: value})
+ assert _needs_pass() is False
+
+
+ "env",
+ [
+ # ROCr hides everything, then HIP names a device out of the empty set.
+ {"HIP_VISIBLE_DEVICES": "0", "ROCR_VISIBLE_DEVICES": "-1"},
+ {"HIP_VISIBLE_DEVICES": "0", "ROCR_VISIBLE_DEVICES": ""},
+ {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": ""},
+ ],
+)
+def test_stacked_masks_with_a_hidden_layer_keep_the_fast_path(monkeypatch, env):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), env = env)
+ assert _needs_pass() is False
+
+
+def test_stacked_masks_that_all_select_are_not_a_hidden_host(monkeypatch):
+ _host(
+ monkeypatch,
+ torch = ("2.9.0+cpu", ""),
+ env = {"HIP_VISIBLE_DEVICES": "0", "ROCR_VISIBLE_DEVICES": "0"},
+ )
+ assert _needs_pass() is True
+
+
[email protected]("cuda", ["", "-1"])
+def test_a_set_hip_mask_shadows_the_cuda_alias(monkeypatch, cuda):
+ """CUDA_VISIBLE_DEVICES is HIP's alias, not a layer under it (_pick_visible_index).
+
+ Hiding NVIDIA with CUDA_VISIBLE_DEVICES=-1 while pinning HIP is a real mixed-host
+ pattern; the HIP mask wins, so the GPU is visible and the wheel is repairable.
+ """
+ _host(
+ monkeypatch,
+ torch = ("2.9.0+cpu", ""),
+ env = {"HIP_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": cuda},
+ )
+ assert _needs_pass() is True
+
+
+def test_a_hidden_hip_mask_wins_over_a_selecting_cuda_alias(monkeypatch):
+ _host(
+ monkeypatch,
+ torch = ("2.9.0+cpu", ""),
+ env = {"HIP_VISIBLE_DEVICES": "-1", "CUDA_VISIBLE_DEVICES": "0"},
+ )
+ assert _needs_pass() is False
+
+
+def test_an_nvidia_host_keeps_the_fast_path(monkeypatch):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), nvidia = True)
+ assert _needs_pass() is False
+
+
+def test_an_nvidia_host_with_an_inferable_amd_arch_keeps_the_fast_path(monkeypatch):
+ """_infer_linux_amd_gfx_arch never checks NVIDIA, so this gate carries the host.
+
+ Without it the preflight forces a pass that _ensure_rocm_torch then refuses.
+ """
+ _host(
+ monkeypatch,
+ torch = ("2.9.0+cpu", ""),
+ nvidia = True,
+ rocm_gpu = False,
+ gfx = (),
+ inferred = "gfx1151",
+ )
+ assert _needs_pass() is False
+
+
+def test_a_host_with_no_amd_gpu_keeps_the_fast_path(monkeypatch):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), rocm_gpu = False, gfx = ())
+ assert _needs_pass() is False
+
+
[email protected]("backend", ["cpu", "cuda", "xpu"])
+def test_a_resolved_non_rocm_backend_keeps_the_fast_path(monkeypatch, backend):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), backend = backend)
+ assert _needs_pass() is False
+
+
+ "pin",
+ [
+ "https://download.pytorch.org/whl/cpu",
+ "https://download.pytorch.org/whl/cu128",
+ "https://download.pytorch.org/whl/xpu",
+ "https://mirror.internal.example/simple",
+ ],
+)
+def test_a_non_rocm_pin_keeps_the_fast_path(monkeypatch, pin):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), env = {"UNSLOTH_TORCH_INDEX_URL": pin})
+ assert _needs_pass() is False
+
+
+ "kwargs",
+ [
+ pytest.param({"no_torch": True}, id = "gguf-only-install"),
+ pytest.param({"linux": False}, id = "not-linux"),
+ pytest.param({"machine": "aarch64"}, id = "no-rocm-wheels-for-this-arch"),
+ ],
+)
+def test_a_host_without_rocm_wheels_keeps_the_fast_path(monkeypatch, kwargs):
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), **kwargs)
+ assert _needs_pass() is False
+
+
+# CLI
+
+
+def _run_cli(
+ *args,
+ env = None,
+ safe_path = False,
+):
+ child = {"PATH": "/usr/bin:/bin", "HOME": "/nonexistent", **(env or {})}
+ if safe_path:
+ child["PYTHONSAFEPATH"] = "1"
+ return subprocess.run(
+ [sys.executable, str(_STACK_PATH), *args],
+ env = child,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ timeout = 180,
+ )
+
+
[email protected]("env_name", ["UNSLOTH_NO_TORCH", "UNSLOTH_TORCH_BACKEND"])
[email protected]("safe_path", [False, True])
+def test_the_cli_reports_keep_the_fast_path_as_a_non_zero_exit(env_name, safe_path):
+ env = {"UNSLOTH_NO_TORCH": "1", "UNSLOTH_TORCH_BACKEND": "cpu"}
+ result = _run_cli(
+ "--amd-torch-needs-dependency-pass",
+ env = {env_name: env[env_name]},
+ safe_path = safe_path,
+ )
+ stderr = result.stderr.decode(errors = "replace")
+ # An import failure also exits 1, so exit 1 alone does not prove the gate ran.
+ assert not stderr, stderr
+ assert result.returncode == 1, stderr
+
+
+ "version,hip,expected",
+ [("2.9.0+cpu", None, 0), ("2.9.0+rocm6.4", "6.4.43483", 1)],
+)
+def test_the_cli_answers_end_to_end_over_a_stub_torch(tmp_path, version, hip, expected):
+ """Exit 0 is the only side that moves setup.sh, so drive it for real.
+
+ A ROCm pin skips the hardware gates, leaving the wheel family as the only input.
+ """
+ (tmp_path / "torch.py").write_text(
+ "import types\n"
+ f"__version__ = {version!r}\n"
+ f"version = types.SimpleNamespace(hip = {hip!r}, cuda = None)\n"
+ )
+ result = _run_cli(
+ "--amd-torch-needs-dependency-pass",
+ env = {
+ "UNSLOTH_TORCH_INDEX_URL": "https://download.pytorch.org/whl/rocm6.4",
+ "PYTHONPATH": str(tmp_path),
+ },
+ )
+ stderr = result.stderr.decode(errors = "replace")
+ assert not stderr, stderr
+ assert result.returncode == expected, stderr
+
+
+ "argv",
+ [
+ ["--amd-torch-needs-dependency-pass", "--amd-torch-needs-dependency-pass"],
+ ["--amd-torch-needs-dependency-passs"],
+ ["--amd-torch-needs-dependency-pass", "extra"],
+ ],
+)
+def test_a_malformed_probe_call_never_falls_through_to_the_installer(argv):
+ result = _run_cli(*argv)
+ assert result.returncode == 2, result.stdout.decode(errors = "replace")
+
+
+# Repair parity
+# Both directions are asserted, so every row must be one the two sides agree on. The
+# conservative divergences (unreadable torch, hidden mask, mixed arch, wrong ROCm
+# family) are covered above and do not belong here.
+
+
+def _repair_installs(monkeypatch):
+ """Torch index URLs _ensure_rocm_torch installs, under the same stubs."""
+ installed = []
+
+ def _record(_label, *args, **_kw):
+ if "--index-url" in args:
+ installed.append(args[args.index("--index-url") + 1])
+
+ monkeypatch.setattr(stack, "pip_install", _record)
+ monkeypatch.setattr(stack, "pip_install_try", lambda *a, **k: True)
+ monkeypatch.setattr(stack, "_clear_confirmed_hsa_spoof", lambda _g: None)
+ monkeypatch.setattr(stack, "_bnb_rocm_prerelease_url", lambda: None)
+ monkeypatch.setattr(stack, "_bitsandbytes_installed", lambda: False)
+ monkeypatch.setattr(stack, "_install_bnb_windows_rocm", lambda: True)
+ stack._ensure_rocm_torch()
+ return installed
+
+
+ "label,host,expected",
+ [
+ ("a visible GPU with a readable ROCm version", dict(rocm_ver = (6, 4), inferred = None), True),
+ (
+ "a Strix host below the per-arch floor",
+ dict(rocm_ver = (7, 0), inferred = None, gfx = ("gfx1151",)),
+ True,
+ ),
+ (
+ "a gfx906 host on a newer ROCm",
+ dict(rocm_ver = (6, 4), inferred = None, gfx = ("gfx906",)),
+ True,
+ ),
+ # #7301: no runtime enumerates anything, but the arch is known.
+ (
+ "UNSLOTH_ROCM_GFX_ARCH naming the arch with no runtime",
+ dict(rocm_ver = None, inferred = "gfx1151", rocm_gpu = False, gfx = ()),
+ True,
+ ),
+ (
+ "an arch inferred from the CPU model with no runtime",
+ dict(rocm_ver = None, inferred = "gfx1151", rocm_gpu = False, gfx = ()),
+ True,
+ ),
+ # Only UNSLOTH_ROCM_GFX_ARCH carries this: a visible GPU defeats the row
+ # above's "no runtime" disjunct.
+ (
+ "UNSLOTH_ROCM_GFX_ARCH rescuing a visible GPU with an unreadable ROCm",
+ dict(rocm_ver = None, inferred = "gfx1151", gfx = ("gfx1151",)),
+ True,
+ ),
+ # The generic download.pytorch.org arm, the one _generic_pytorch_rocm_tag feeds.
+ (
+ "a non-Strix GPU on a ROCm with a published wheel family",
+ dict(rocm_ver = (6, 4), inferred = None, gfx = ("gfx1030",)),
+ True,
+ ),
+ # The repair prints "skipping torch reinstall" and returns for all three.
+ (
+ "a visible GPU whose ROCm version cannot be read",
+ dict(rocm_ver = None, inferred = None),
+ False,
+ ),
+ (
+ "a ROCm older than any published wheel family",
+ dict(rocm_ver = (5, 0), inferred = None, gfx = ("gfx1030",)),
+ False,
+ ),
+ (
+ "an inferred arch AMD publishes no per-arch index for",
+ dict(rocm_ver = None, inferred = "gfx900", rocm_gpu = False, gfx = ()),
+ False,
+ ),
+ ],
+)
+def test_the_preflight_and_the_repair_agree(monkeypatch, label, host, expected):
+ env = {"UNSLOTH_ROCM_GFX_ARCH": host["inferred"]} if "GFX_ARCH" in label else None
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), env = env, **host)
+ preflight = stack._amd_torch_needs_dependency_pass()
+ assert preflight is expected, label
+
+ _host(monkeypatch, torch = ("2.9.0+cpu", ""), env = env, **host)
+ installs = _repair_installs(monkeypatch)
+ if preflight:
+ assert installs, f"{label}: preflight forced a pass the repair declined"
+ else:
+ assert not installs, f"{label}: the repair acts but the preflight kept the fast path"