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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
# 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 HSA_OVERRIDE_GFX_VERSION spoof made Strix Halo probe as gfx1100 and the installer trusted it."""
from __future__ import annotations
import importlib.util
import os
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
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_install_python_stack_7331", _STACK_PATH
)
assert _STACK_SPEC is not None and _STACK_SPEC.loader is not None
stack_mod = importlib.util.module_from_spec(_STACK_SPEC)
sys.modules[_STACK_SPEC.name] = stack_mod
_STACK_SPEC.loader.exec_module(stack_mod)
_INSTALL_SH = PACKAGE_ROOT / "install.sh"
# torch probe stdout: "<version>|<hip>|<cuda>". An empty HIP field = CPU/CUDA torch.
_CPU_TORCH = "2.10.0+cpu||\n"
_ROCM63_TORCH = "2.9.1+rocm6.3|6.3.42134|\n"
@pytest.fixture(autouse = True)
def _reset_torch_runtime_probe():
"""The torch classification is memoized for the life of an install run, so one
test's mocked probe must not leak into the next."""
stack_mod._invalidate_torch_runtime_probe()
stack_mod._invalidate_rocm_version_probe()
yield
stack_mod._invalidate_torch_runtime_probe()
stack_mod._invalidate_rocm_version_probe()
def _run_install(
*,
torch_probe_stdout = _CPU_TORCH,
gfx_devices = ("gfx1100",),
inferred = "gfx1151",
rocm_version = (6, 3),
env = None,
reprobe_devices = None,
kfd_targets = (),
env_probe = None,
):
"""Runs _ensure_rocm_torch() on a mocked host; env_probe reads the override while torch installs."""
probe = MagicMock()
probe.returncode = 0
probe.stdout = torch_probe_stdout
def _fake_detect(
dedup = True,
ignore_hsa_override = False,
ignore_visible_masks = False,
):
if ignore_hsa_override and reprobe_devices is not None:
codes = list(reprobe_devices)
else:
codes = list(gfx_devices)
return list(dict.fromkeys(codes)) if dedup else codes
_env = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0"} if env is None else env
# The real function returns UNSLOTH_ROCM_GFX_ARCH first; a stub ignoring it asserts nothing.
if _env.get("UNSLOTH_ROCM_GFX_ARCH"):
inferred = _env["UNSLOTH_ROCM_GFX_ARCH"]
def _record_env(*a, **kw):
if env_probe is not None and "HSA_OVERRIDE_GFX_VERSION" not in env_probe:
env_probe["HSA_OVERRIDE_GFX_VERSION"] = os.environ.get("HSA_OVERRIDE_GFX_VERSION")
return True
with (
patch.object(stack_mod, "IS_WINDOWS", False),
patch.object(stack_mod, "pip_install_try", side_effect = _record_env) as pip_try,
patch.object(stack_mod, "pip_install") as pip,
patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = False),
patch.object(stack_mod, "_has_rocm_gpu", return_value = True),
patch.object(stack_mod, "_infer_linux_amd_gfx_arch", return_value = inferred),
patch.object(stack_mod, "_detect_amd_gfx_codes", side_effect = _fake_detect),
patch.object(stack_mod, "_detect_rocm_version", return_value = rocm_version),
# create=True so a pre-fix tree fails on the assertion, not on AttributeError.
patch.object(stack_mod, "_kfd_gfx_targets", return_value = list(kfd_targets), create = True),
patch.dict(os.environ, _env, clear = False),
):
# patch.dict cannot remove outer keys, and each of these silently decides the outcome.
for _stale in (
"UNSLOTH_ROCM_GFX_ARCH",
"UNSLOTH_AMD_ROCM_MIRROR",
"HSA_OVERRIDE_GFX_VERSION",
"HIP_VISIBLE_DEVICES",
"ROCR_VISIBLE_DEVICES",
"CUDA_VISIBLE_DEVICES",
):
if _stale not in _env:
os.environ.pop(_stale, None)
with patch("os.path.isdir", return_value = True):
with patch("subprocess.run", return_value = probe):
stack_mod._ensure_rocm_torch()
return str(pip.call_args_list) + str(pip_try.call_args_list)
class TestSpoofedStrixHaloRouting:
"""gfx1151 spoofed to gfx1100 by HSA_OVERRIDE_GFX_VERSION must still get AMD's
per-gfx1151 wheels, on a fresh install and on a repair."""
def test_kernel_settles_it(self):
"""The strongest path: amdkfd wrote gfx_target_version 110501 long before ROCr
read the env var, so the kernel naming gfx1151 ends the argument."""
calls = _run_install(kfd_targets = ["gfx1151"], reprobe_devices = None)
assert "repo.amd.com/rocm/whl/gfx1151/" in calls, calls
assert "torch>=2.11.0,<2.12.0" in calls, calls
def test_fresh_install_routes_to_the_gfx1151_index(self):
"""The reported path with no KFD sysfs, so the re-probe corroborates. Before the
fix this produced download.pytorch.org/whl/rocm6.3 with torch>=2.4,<2.11.0, the
2.9.1+rocm6.3 that segfaulted."""
calls = _run_install(reprobe_devices = ["gfx1151"])
assert "repo.amd.com/rocm/whl/gfx1151/" in calls, calls
assert "torch>=2.11.0,<2.12.0" in calls, calls
assert "download.pytorch.org" not in calls, calls
assert "rocm6.3" not in calls, calls
def test_repair_over_the_broken_rocm63_torch(self):
"""studio update on a host with torch 2.9.1+rocm6.3 (has_hip_torch True) must still fire the
Strix reroute, or the repair is a no-op and the segfault survives."""
calls = _run_install(torch_probe_stdout = _ROCM63_TORCH, reprobe_devices = ["gfx1151"])
assert "repo.amd.com/rocm/whl/gfx1151/" in calls, calls
assert "torch>=2.11.0,<2.12.0" in calls, calls
def test_uncorroborated_spoof_is_left_alone(self):
"""Without kernel evidence a real gfx1100 dGPU looks like the spoof, so routing is kept."""
calls = _run_install(reprobe_devices = None, rocm_version = (7, 1))
assert "repo.amd.com" not in calls, calls
assert "rocm7.1" in calls, calls
def test_gfx1150_strix_point_spoofed_the_same_way(self):
"""11.0.0 is the circulated workaround for every RDNA 3.5 part, so Strix Point
(gfx1150) takes the same correction."""
calls = _run_install(inferred = "gfx1150", reprobe_devices = ["gfx1150"])
assert "repo.amd.com/rocm/whl/gfx1150/" in calls, calls
class TestPrecedenceStillHolds:
"""The runtime-visible arch keeps winning outside the one narrow spoof shape.
These are the cases the #7305 precedence exists for."""
def test_no_override_set_keeps_todays_behaviour(self):
"""Without the override there is no spoof evidence, so the probe is taken at face value."""
calls = _run_install(env = {}, rocm_version = (7, 1))
assert "gfx1151" not in calls, calls
assert "rocm7.1" in calls, calls
def test_kernel_showing_a_second_gpu_vetoes_the_correction(self):
"""The spoofed probe collapses a Strix APU and a gfx1100 dGPU into one apparent gfx1100; KFD
sysfs sees both and withdraws the single-device premise, so the correction must decline."""
calls = _run_install(
kfd_targets = ["gfx1151", "gfx1100"],
rocm_version = (7, 1),
)
assert "repo.amd.com" not in calls, calls
assert "rocm7.1" in calls, calls
def test_mixed_host_with_two_devices_is_never_corrected(self):
"""Two visible devices must decline the correction, so today's visible-mask selection decides."""
calls = _run_install(
gfx_devices = ("gfx1100", "gfx1100"),
reprobe_devices = ["gfx1151", "gfx1100"],
rocm_version = (7, 1),
)
assert "repo.amd.com" not in calls, calls
assert "rocm7.1" in calls, calls
def test_probe_unrelated_to_the_inferred_arch_is_not_a_spoof(self):
"""11.0.0 cannot make a part report gfx1030, so a gfx1030 probe on a box whose
name says gfx1151 is a real second GPU, not the spoof. Left alone."""
calls = _run_install(gfx_devices = ("gfx1030",), rocm_version = (7, 1))
assert "repo.amd.com" not in calls, calls
assert "rocm7.1" in calls, calls
def test_override_matching_the_physical_arch_is_not_a_spoof(self):
"""11.5.1 on a real gfx1151 names the arch the hardware already is: nothing is
masked, so the ordinary gfx1151 reroute handles it."""
calls = _run_install(
gfx_devices = ("gfx1151",),
env = {"HSA_OVERRIDE_GFX_VERSION": "11.5.1"},
)
assert "repo.amd.com/rocm/whl/gfx1151/" in calls, calls
def test_real_gfx1100_dgpu_in_a_ryzen_ai_max_chassis(self):
"""A real gfx1100 dGPU in a Ryzen AI Max chassis looks like the spoof; the kernel tells them
apart."""
calls = _run_install(
kfd_targets = ["gfx1100"],
reprobe_devices = ["gfx1100"],
rocm_version = (7, 1),
)
assert "repo.amd.com" not in calls, calls
assert "gfx1151" not in calls, calls
assert "rocm7.1" in calls, calls
def test_real_gfx1100_dgpu_with_no_kfd_sysfs(self):
"""With no KFD sysfs, the re-probe alone decides; its gfx1100 answer is evidence for the
real card."""
calls = _run_install(kfd_targets = (), reprobe_devices = ["gfx1100"], rocm_version = (7, 1))
assert "repo.amd.com" not in calls, calls
assert "gfx1151" not in calls, calls
assert "rocm7.1" in calls, calls
def test_deliberate_rdna2_override_is_not_a_strix_spoof(self):
"""10.3.0 is the documented correct override for an RX 6800; even in a Ryzen AI Max chassis
that name-infers gfx1151, gfx1030 is not a spoof."""
calls = _run_install(
gfx_devices = ("gfx1030",),
reprobe_devices = ["gfx1030"],
env = {"HSA_OVERRIDE_GFX_VERSION": "10.3.0"},
rocm_version = (7, 1),
)
assert "repo.amd.com" not in calls, calls
assert "gfx1151" not in calls, calls
def test_override_naming_a_third_arch_is_never_a_spoof(self):
"""ROCr only renames an agent to the target the variable names, so 10.3.0 beside a gfx1100
reading came from the silicon, so no spoof to undo even if the kernel is silent."""
calls = _run_install(
env = {"HSA_OVERRIDE_GFX_VERSION": "10.3.0"},
reprobe_devices = ["gfx1151"],
rocm_version = (7, 1),
)
assert "repo.amd.com" not in calls, calls
def test_masked_mixed_host_reprobes_the_whole_machine(self):
"""The re-probe must clear ROCR_VISIBLE_DEVICES too, or a masked second GPU stays hidden."""
calls = _run_install(
env = {
"HSA_OVERRIDE_GFX_VERSION": "11.0.0",
"ROCR_VISIBLE_DEVICES": "1",
},
reprobe_devices = ["gfx1151", "gfx1100"],
rocm_version = (7, 1),
)
assert "repo.amd.com" not in calls, calls
def test_explicit_gfx_arch_override_still_wins(self):
"""UNSLOTH_ROCM_GFX_ARCH is the documented escape hatch and outranks every
inference: a gfx906 host also carrying a stale override still gets the gfx906
legacy routing, never Strix wheels."""
calls = _run_install(
gfx_devices = ("gfx1100",),
kfd_targets = ["gfx1151"],
env = {
"HSA_OVERRIDE_GFX_VERSION": "11.0.0",
"UNSLOTH_ROCM_GFX_ARCH": "gfx906",
},
rocm_version = (7, 1),
)
assert "gfx1151" not in calls, calls
assert "rocm6.3" in calls, calls # the gfx906 legacy index
class TestHsaOverrideArch:
"""ROCr builds the target name from the version triple as
gfx<major><minor><hex(stepping)>, which is why 9.0.10 is gfx90a."""
@pytest.mark.parametrize(
"value,expected",
[
("11.0.0", "gfx1100"),
("11.5.1", "gfx1151"),
("10.3.0", "gfx1030"),
("9.0.10", "gfx90a"),
("9.4.2", "gfx942"),
(" 11.0.0 ", "gfx1100"),
("11.0", None), # not a triple
("", None),
("garbage", None),
("11.0.x", None),
],
)
def test_reading(self, value, expected):
assert stack_mod._hsa_override_gfx_arch(value) == expected
class TestKfdGfxTargets:
"""amdkfd encodes gfx_target_version as major*10000 + minor*100 + hex stepping; gfx1151 is
110501 and the circulating 110511 decodes to no real part."""
def _nodes(self, tmp_path, monkeypatch, nodes):
root = tmp_path / "nodes"
for i, body in enumerate(nodes):
node = root / f"{i}"
node.mkdir(parents = True)
(node / "properties").write_text(body, encoding = "utf-8")
monkeypatch.setattr(stack_mod.sys, "platform", "linux")
real_listdir, real_open = os.listdir, open
def _listdir(path):
return real_listdir(str(root) if path.endswith("topology/nodes") else path)
def _open(path, *a, **kw):
path = str(path)
if "topology/nodes" in path:
path = str(root / path.split("topology/nodes/", 1)[1])
return real_open(path, *a, **kw)
monkeypatch.setattr(stack_mod.os, "listdir", _listdir)
monkeypatch.setattr("builtins.open", _open)
def test_decodes_the_reporter_gpu(self, tmp_path, monkeypatch):
self._nodes(
tmp_path,
monkeypatch,
[
"cpu_cores_count 16\nvendor_id 0\ngfx_target_version 0\n", # CPU node
"simd_count 640\nvendor_id 4098\ngfx_target_version 110501\n",
],
)
assert stack_mod._kfd_gfx_targets() == ["gfx1151"]
def test_hex_stepping_and_non_amd_nodes(self, tmp_path, monkeypatch):
self._nodes(
tmp_path,
monkeypatch,
[
"vendor_id 4098\ngfx_target_version 90010\n", # gfx90a
"vendor_id 4318\ngfx_target_version 110000\n", # NVIDIA KFD node
"vendor_id 4098\ngfx_target_version 110000\n", # gfx1100
],
)
assert stack_mod._kfd_gfx_targets() == ["gfx90a", "gfx1100"]
def _sh_func(name: str) -> str:
"""Extract one top-level POSIX function definition out of install.sh."""
source = _INSTALL_SH.read_text(encoding = "utf-8")
start = source.find(f"\n{name}() {{\n")
assert start != -1, f"{name}() not found in install.sh"
end = source.find("\n}\n", start)
assert end != -1, f"{name}() has no closing brace"
return source[start + 1 : end + 3]
def _run_sh(script: str, env = None) -> str:
"""Run a /bin/sh snippet with the install.sh helpers sourced."""
import subprocess as _sp
preamble = (
_sh_func("_hsa_override_gfx_arch")
+ _sh_func("_hsa_spoofed_physical_gfx")
# CI has no /sys/class/kfd; node parsing is unit-tested on the Python side.
+ "\n_kfd_gfx_targets() { printf '%s\\n' \"${FAKE_KFD:-}\" | awk 'NF'; }\n"
)
_env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin")}
_env.update(env or {})
proc = _sp.run(
["/bin/sh", "-c", preamble + script],
capture_output = True,
text = True,
timeout = 60,
env = _env,
)
assert proc.returncode == 0, proc.stderr
return proc.stdout.strip()
class TestInstallShParity:
"""install.sh must match install_python_stack.py's verdict; these tests execute its shell helpers."""
@pytest.mark.parametrize(
"value,expected",
[
("11.0.0", "gfx1100"),
("11.5.1", "gfx1151"),
("10.3.0", "gfx1030"),
("9.0.10", "gfx90a"),
("9.4.2", "gfx942"),
(" 11.0.0 ", "gfx1100"),
("11.0", ""),
("", ""),
("garbage", ""),
("11.0.x", ""),
],
)
def test_override_reading_matches_python(self, value, expected):
got = _run_sh(f'_hsa_override_gfx_arch "{value}"')
assert got == expected
assert got == (stack_mod._hsa_override_gfx_arch(value) or "")
@pytest.mark.parametrize(
"inferred,probed,kfd,override,expected,why",
[
("gfx1151", "gfx1100", "gfx1151", "11.0.0", "gfx1151", "kernel settles it"),
("gfx1151", "gfx1100", "", "11.0.0", "", "uncorroborated, no rocminfo"),
("gfx1151", "gfx1100", "gfx1100", "11.0.0", "", "real 7900 XTX per the kernel"),
("gfx1151", "gfx1100", "gfx1151\ngfx1100", "11.0.0", "", "mixed host via kernel"),
("gfx1151", "gfx1100", "gfx1151", "", "", "no override set"),
("gfx1151", "gfx1100\ngfx1100", "gfx1151", "11.0.0", "gfx1151", "one arch, repeated"),
("gfx1151", "gfx1100\ngfx1030", "gfx1151", "11.0.0", "", "two arches probed"),
("gfx1151", "gfx1030", "", "11.0.0", "", "probe unrelated to the name"),
("gfx1151", "gfx1030", "gfx1151", "11.0.0", "", "override names no such probe"),
("gfx1151", "gfx1151", "gfx1151", "11.5.1", "", "override is a no-op remap"),
("gfx1030", "gfx1100", "gfx1030", "11.0.0", "", "not a spoofable arch"),
],
)
def test_decision_matches_python(self, inferred, probed, kfd, override, expected, why):
"""The same named shapes on both paths. `why` names the rule each pins."""
env = {"FAKE_KFD": kfd}
if override:
env["HSA_OVERRIDE_GFX_VERSION"] = override
got = _run_sh(f'_hsa_spoofed_physical_gfx "{inferred}" "{probed}" 2>/dev/null', env = env)
assert got == expected, why
with (
patch.dict(os.environ, env, clear = False),
patch.object(
stack_mod, "_kfd_gfx_targets", return_value = [c for c in kfd.split("\n") if c]
),
patch.object(stack_mod, "_detect_amd_gfx_codes", return_value = []),
):
if not override:
os.environ.pop("HSA_OVERRIDE_GFX_VERSION", None)
py = stack_mod._hsa_spoofed_physical_gfx(inferred, probed.split("\n"))
assert (py or "") == expected, f"{why}: shell said {got!r}, python said {py!r}"
def test_reroute_consults_the_correction(self):
"""The helper existing is not enough; the Strix reroute has to call it."""
source = _INSTALL_SH.read_text(encoding = "utf-8")
# rfind: an earlier case on the same variable sets UNSLOTH_TORCH_BACKEND.
idx = source.rfind('case "$_torch_index_leaf" in')
assert idx != -1
assert "_hsa_spoofed_physical_gfx" in source[idx : idx + 6000], (
"install.sh's Strix reroute must correct the spoofed probe before it "
"matches gfx1150/1151/1152"
)
@pytest.mark.parametrize(
"nodes,expected",
[
(
[
"cpu_cores_count 16\nvendor_id 0\ngfx_target_version 0\n",
"simd_count 640\nvendor_id 4098\ngfx_target_version 110501\n",
],
["gfx1151"],
),
(
[
"vendor_id 4098\ngfx_target_version 90010\n",
"vendor_id 4318\ngfx_target_version 110000\n",
"vendor_id 4098\ngfx_target_version 110000\n",
],
["gfx90a", "gfx1100"],
),
(["vendor_id 4098\n"], []),
(["vendor_id 4098\ngfx_target_version notanumber\n"], []),
([""], []),
([], []),
],
)
def test_kfd_reader_matches_python(self, tmp_path, nodes, expected):
"""The KFD parser must match Python's gfx_target_version decoding, or every Strix host is
misrouted."""
root = tmp_path / "nodes"
root.mkdir()
for i, body in enumerate(nodes):
(root / str(i)).mkdir()
(root / str(i) / "properties").write_text(body, encoding = "utf-8")
body = _sh_func("_kfd_gfx_targets").replace("/sys/class/kfd/kfd/topology/nodes", str(root))
assert str(root) in body, "the sysfs root substitution must have applied"
got = _run_sh(body + "\n_kfd_gfx_targets\n")
assert [c for c in got.split("\n") if c] == expected
def test_reprobe_falls_through_to_amd_smi_like_python_does(self, tmp_path):
"""rocminfo fails on older ROCm once the override is stripped; install.sh must fall back to
amd-smi."""
_bin = tmp_path / "bin"
_bin.mkdir()
(_bin / "rocminfo").write_text(
"#!/bin/sh\n"
'if [ -z "${HSA_OVERRIDE_GFX_VERSION:-}" ]; then exit 1; fi\n'
'echo " Name: gfx1100"\n'
'echo " Name: amdgcn-amd-amdhsa--gfx1100"\n',
encoding = "utf-8",
)
(_bin / "amd-smi").write_text(
'#!/bin/sh\necho " TARGET_GRAPHICS_VERSION: gfx1151"\n', encoding = "utf-8"
)
for _f in ("rocminfo", "amd-smi"):
(_bin / _f).chmod(0o755)
env = {
"FAKE_KFD": "", # no /sys/class/kfd, so the re-probe is the only witness
"HSA_OVERRIDE_GFX_VERSION": "11.0.0",
"PATH": str(_bin) + ":" + os.environ.get("PATH", "/usr/bin:/bin"),
}
got = _run_sh('_hsa_spoofed_physical_gfx "gfx1151" "gfx1100\ngfx1100" 2>/dev/null', env = env)
assert got == "gfx1151", got
with (
patch.dict(os.environ, env, clear = False),
patch.object(stack_mod, "_kfd_gfx_targets", return_value = []),
patch.object(stack_mod, "_amd_smi_allowed", return_value = True),
patch.object(stack_mod, "_safe_print"),
):
os.environ.pop("ROCR_VISIBLE_DEVICES", None)
os.environ.pop("HIP_VISIBLE_DEVICES", None)
py = stack_mod._hsa_spoofed_physical_gfx("gfx1151", ["gfx1100", "gfx1100"])
assert py == got, (py, got)
def test_reprobe_clears_the_visible_masks_too(self):
"""install.sh's re-probe runs `unset HSA_OVERRIDE_GFX_VERSION
ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES`, so the Python one must drop all three
too: a mask left in place hides the second GPU that vetoes the correction."""
_unset = [
ln for ln in _sh_func("_hsa_spoofed_physical_gfx").splitlines() if "(unset " in ln
]
# One per re-probe tool; fewer would re-probe a masked or spoofed machine.
assert _unset, _unset
for _line in _unset:
for _var in (
"HSA_OVERRIDE_GFX_VERSION",
"ROCR_VISIBLE_DEVICES",
"HIP_VISIBLE_DEVICES",
):
assert _var in _line, (_var, _line)
seen = {}
def _fake_run(cmd, **kw):
seen["env"] = kw.get("env")
out = MagicMock()
out.returncode = 0
out.stdout = "Agent 1\n Name: gfx1151\n"
return out
env = {
"HSA_OVERRIDE_GFX_VERSION": "11.0.0",
"ROCR_VISIBLE_DEVICES": "1",
"HIP_VISIBLE_DEVICES": "1",
}
with (
patch.dict(os.environ, env, clear = False),
patch.object(
stack_mod.shutil,
"which",
side_effect = lambda c: "/usr/bin/rocminfo" if c == "rocminfo" else None,
),
patch.object(stack_mod.subprocess, "run", side_effect = _fake_run),
):
stack_mod._detect_amd_gfx_codes(
dedup = False, ignore_hsa_override = True, ignore_visible_masks = True
)
assert seen["env"] is not None, "the probe must not inherit the environment"
for _var in env:
assert _var not in seen["env"], _var
# Shared fake rocminfo: ROCr renames agents to HSA_OVERRIDE_GFX_VERSION's target and repeats
# the token per Name/ISA line, so the shell's raw grep yields several lines per GPU.
_FAKE_ROCMINFO = r"""#!/bin/sh
_phys="${FAKE_PHYSICAL:-}"
_spoof=$(printf '%s' "${HSA_OVERRIDE_GFX_VERSION:-}" | awk '
{ if ($0 !~ /^[0-9]+\.[0-9]+\.[0-9]+$/) exit
split($0, p, "."); maj = p[1] + 0; min = p[2] + 0; st = p[3] + 0
if (maj <= 0 || min > 9 || st > 15) exit
printf "gfx%d%d%x", maj, min, st }')
_sel="${ROCR_VISIBLE_DEVICES:-}"
echo "ROCk module is loaded"
_i=0
for _a in $_phys; do
if [ -n "$_sel" ]; then
case ",$_sel," in *",$_i,"*) : ;; *) _i=$((_i + 1)); continue ;; esac
fi
[ -n "$_spoof" ] && _a="$_spoof"
echo "*******"
echo "Agent $((_i + 2))"
echo "*******"
echo " Name: $_a"
echo " Device Type: GPU"
echo " Name: amdgcn-amd-amdhsa--$_a"
_i=$((_i + 1))
done
echo "*** Done ***"
"""
@pytest.fixture(scope = "module")
def fake_rocminfo(tmp_path_factory):
_bin = tmp_path_factory.mktemp("fakebin")
_rocminfo = _bin / "rocminfo"
_rocminfo.write_text(_FAKE_ROCMINFO, encoding = "utf-8")
_rocminfo.chmod(0o755)
return str(_bin)
def _shapes(seed: int, count: int):
"""Randomized host matrix; override values include empty, malformed and absurd strings users produce."""
import random
rng = random.Random(seed)
overrides = [
"",
"11.0.0",
"11.5.1",
"10.3.0",
"9.0.10",
"9.4.2",
"garbage",
"11.0",
"11.0.0.0",
" 11.0.0 ",
"11.0.x",
"-1.0.0",
"999999.0.0",
"11.0.16",
"0.0.0",
"11.10.0",
" ",
"11..0",
]
arches = ["gfx1151", "gfx1150", "gfx1152", "gfx1100", "gfx1030", "gfx906", "gfx942"]
inferreds = arches + [""]
for _ in range(count):
physical = [rng.choice(arches) for _ in range(rng.choice([0, 1, 1, 1, 2, 2, 3]))]
probed = []
for _a in physical:
probed.extend([_a] * rng.choice([1, 2, 2, 3]))
yield {
"inferred": rng.choice(inferreds),
"probed": probed,
"kfd": [rng.choice(arches) for _ in range(rng.choice([0, 0, 1, 1, 2]))],
"override": rng.choice(overrides),
"physical": physical,
"mask": rng.choice(["", "", "", "0", "1", "-1"]),
}
class TestRandomizedParity:
"""install.sh and install_python_stack.py must agree on every host shape, including the re-probe."""
@pytest.mark.parametrize("seed", [0, 1])
def test_verdicts_agree(self, seed, fake_rocminfo):
divergences = []
for shape in _shapes(seed, 100):
env = {
"FAKE_KFD": "\n".join(shape["kfd"]),
"FAKE_PHYSICAL": " ".join(shape["physical"]),
"PATH": fake_rocminfo + ":" + os.environ.get("PATH", "/usr/bin:/bin"),
}
if shape["override"]:
env["HSA_OVERRIDE_GFX_VERSION"] = shape["override"]
if shape["mask"]:
env["ROCR_VISIBLE_DEVICES"] = shape["mask"]
sh = _run_sh(
'_hsa_spoofed_physical_gfx "$SHAPE_INFERRED" "$SHAPE_PROBED" 2>/dev/null',
env = dict(
env,
SHAPE_INFERRED = shape["inferred"],
SHAPE_PROBED = "\n".join(shape["probed"]),
),
)
with (
patch.dict(os.environ, env, clear = False),
patch.object(stack_mod, "_kfd_gfx_targets", return_value = list(shape["kfd"])),
patch.object(stack_mod, "_amd_smi_allowed", return_value = False),
patch.object(stack_mod, "_safe_print"),
):
for _stale in ("HSA_OVERRIDE_GFX_VERSION", "ROCR_VISIBLE_DEVICES"):
if _stale not in env:
os.environ.pop(_stale, None)
os.environ.pop("HIP_VISIBLE_DEVICES", None)
py = stack_mod._hsa_spoofed_physical_gfx(
shape["inferred"] or None, list(shape["probed"])
)
if (py or "") != sh:
divergences.append((shape, sh, py))
assert not divergences, divergences[:5]
@pytest.mark.parametrize("seed", [0])
def test_never_corrects_without_corroboration(self, seed, fake_rocminfo):
"""Safety invariant over the random matrix: a verdict is returned only when the kernel, or
rocminfo re-probed without the override, named that exact arch and nothing else."""
for shape in _shapes(seed, 100):
env = {
"FAKE_KFD": "\n".join(shape["kfd"]),
"FAKE_PHYSICAL": " ".join(shape["physical"]),
"PATH": fake_rocminfo + ":" + os.environ.get("PATH", "/usr/bin:/bin"),
}
if shape["override"]:
env["HSA_OVERRIDE_GFX_VERSION"] = shape["override"]
if shape["mask"]:
env["ROCR_VISIBLE_DEVICES"] = shape["mask"]
with (
patch.dict(os.environ, env, clear = False),
patch.object(stack_mod, "_kfd_gfx_targets", return_value = list(shape["kfd"])),
patch.object(stack_mod, "_amd_smi_allowed", return_value = False),
patch.object(stack_mod, "_safe_print"),
):
for _stale in ("HSA_OVERRIDE_GFX_VERSION", "ROCR_VISIBLE_DEVICES"):
if _stale not in env:
os.environ.pop(_stale, None)
os.environ.pop("HIP_VISIBLE_DEVICES", None)
py = stack_mod._hsa_spoofed_physical_gfx(
shape["inferred"] or None, list(shape["probed"])
)
if py is None:
continue
# Corroborated by the kernel or the unspoofed re-probe, never by the variable alone.
assert shape["kfd"] == [py] or list(dict.fromkeys(shape["physical"])) == [py], (
shape,
py,
)
assert py == shape["inferred"], (shape, py)
class TestCallSiteParity:
"""install.sh's grep yields repeated tokens per GPU, so input must come from each call site."""
@pytest.mark.parametrize(
"override", ["", "11.0.0", "11.5.1", "10.3.0", "garbage", "999999.0.0"]
)
def test_verdicts_agree_end_to_end(self, override, fake_rocminfo):
import itertools
import subprocess as _sp
inferreds = ["gfx1151", "gfx1150", "gfx1100", "gfx1030", ""]
physicals = [
[],
["gfx1151"],
["gfx1100"],
["gfx1030"],
["gfx1151", "gfx1100"],
["gfx1100", "gfx1100"],
["gfx1151", "gfx1151"],
]
kfds = [[], ["gfx1151"], ["gfx1100"], ["gfx1151", "gfx1100"]]
masks = ["", "0", "1"]
_path = fake_rocminfo + ":" + os.environ.get("PATH", "/usr/bin:/bin")
divergences, corrections, shapes = [], 0, 0
for inferred, physical, kfd, mask in itertools.product(inferreds, physicals, kfds, masks):
env = {
"FAKE_KFD": "\n".join(kfd),
"FAKE_PHYSICAL": " ".join(physical),
"PATH": _path,
}
if override:
env["HSA_OVERRIDE_GFX_VERSION"] = override
if mask:
env["ROCR_VISIBLE_DEVICES"] = mask
sh_probe = _sp.run(
[
"/bin/sh",
"-c",
"rocminfo 2>/dev/null | grep -oE 'gfx[1-9][0-9a-z]{2,3}' || true",
],
capture_output = True,
text = True,
env = env,
timeout = 60,
).stdout.strip()
sh = (
_run_sh(
'_hsa_spoofed_physical_gfx "$SI" "$SP" 2>/dev/null',
env = dict(env, SI = inferred, SP = sh_probe),
)
if sh_probe
else ""
)
with (
patch.dict(os.environ, env, clear = False),
patch.object(stack_mod, "_kfd_gfx_targets", return_value = list(kfd)),
patch.object(stack_mod, "_amd_smi_allowed", return_value = False),
patch.object(stack_mod, "_safe_print"),
):
for _stale in ("HSA_OVERRIDE_GFX_VERSION", "ROCR_VISIBLE_DEVICES"):
if _stale not in env:
os.environ.pop(_stale, None)
os.environ.pop("HIP_VISIBLE_DEVICES", None)
py_probe = stack_mod._detect_amd_gfx_codes(dedup = False)
py = (
stack_mod._hsa_spoofed_physical_gfx(inferred or None, list(py_probe))
if py_probe
else None
)
shapes += 1
corrections += bool(py)
if (py or "") != sh:
divergences.append(
{
"override": override,
"inferred": inferred,
"physical": physical,
"kfd": kfd,
"mask": mask,
"sh_probe": sh_probe.split("\n"),
"py_probe": py_probe,
"shell_said": sh,
"python_said": py,
}
)
assert not divergences, divergences[:5]
if override == "11.0.0":
# 11.0.0 on a gfx1151 chassis is the reported case and must correct somewhere.
assert corrections, f"no shape corrected across {shapes} shapes"
class TestConfirmedSpoofIsClearedBeforeLaunch:
"""ROCr rebuilds the agent from HSA_OVERRIDE_GFX_VERSION in later processes; clear a disproved one."""
def test_reroute_clears_the_variable_it_disproved(self):
probe = {}
calls = _run_install(kfd_targets = ["gfx1151"], env_probe = probe)
assert "repo.amd.com/rocm/whl/gfx1151/" in calls, calls
assert probe["HSA_OVERRIDE_GFX_VERSION"] is None, probe
def test_declined_spoof_keeps_the_users_override(self):
"""A real gfx1100 dGPU in a Ryzen AI Max chassis keeps generic wheels and the user's own HSA
override, since nothing was disproved and nothing is removed."""
probe = {}
calls = _run_install(
kfd_targets = ["gfx1100"],
reprobe_devices = ["gfx1100"],
rocm_version = (7, 1),
env_probe = probe,
)
assert "repo.amd.com" not in calls, calls
assert probe["HSA_OVERRIDE_GFX_VERSION"] == "11.0.0", probe
def test_unspoofed_strix_reroute_leaves_the_environment_alone(self):
"""A gfx1151 host reporting itself honestly reroutes for the ordinary reason.
No confirmed spoof, so the clear must not fire."""
probe = {}
calls = _run_install(
gfx_devices = ("gfx1151",),
env = {"HSA_OVERRIDE_GFX_VERSION": "11.5.1"},
env_probe = probe,
)
assert "repo.amd.com/rocm/whl/gfx1151/" in calls, calls
assert probe["HSA_OVERRIDE_GFX_VERSION"] == "11.5.1", probe
def test_install_sh_clears_it_on_the_same_branch(self):
"""The shell path is what matters for the reported flow: install.sh execs Unsloth
from this very shell and install_python_stack.py runs as a grandchild, so a pop
there cannot reach the launch."""
source = _INSTALL_SH.read_text(encoding = "utf-8")
start = source.find('if [ -n "$_strix_gfx" ] && _rocm_leaf_below')
assert start != -1, "install.sh's Strix reroute branch moved"
block = source[start : source.find("\n fi\n", start)]
assert "unset HSA_OVERRIDE_GFX_VERSION" in block, (
"the Strix reroute must clear a corroborated spoof before this shell "
"execs Unsloth, or the new wheels meet a runtime still claiming gfx1100"
)
assert '[ -n "$_spoof_physical" ]' in block, (
"the clear must be guarded by the corroborated-spoof verdict, never "
"applied to a host whose override was not disproved"
)
# One clear per native per-arch branch, each under a corroborated-spoof guard; other branches
# keep the override, which generic wheels need.
_lasting = [
i
for i, ln in enumerate(source.splitlines())
if ln.strip().startswith("unset HSA_OVERRIDE_GFX_VERSION")
]
assert len(_lasting) == 2, _lasting
_lines = source.splitlines()
for _at in _lasting:
_guard = "\n".join(_lines[max(0, _at - 6) : _at])
assert "_spoof_physical" in _guard, (
f"the clear at line {_at + 1} is not guarded by a corroborated-spoof "
f"verdict; every clear must be, or a host whose override was not "
f"disproved loses the only thing making its GPU usable"
)
def _spoof_clear_guard() -> str:
"""The real `if` condition guarding the HSA_OVERRIDE_GFX_VERSION unset, out of install.sh."""
source = _INSTALL_SH.read_text(encoding = "utf-8")
marker = "\n unset HSA_OVERRIDE_GFX_VERSION\n"
at = source.find(marker)
assert at != -1, "the spoof-clearing unset is no longer in install.sh"
line_start = source.rfind("\n if ", 0, at)
assert line_start != -1, "no guarding if for the spoof-clearing unset"
return source[line_start + 1 : at].strip()
def test_no_torch_keeps_the_override_because_no_per_gfx_wheels_are_installed():
"""Clearing the spoof is sound only when per-gfx wheels are installed; with --no-torch it must stay."""
guard = _spoof_clear_guard()
assert "SKIP_TORCH" in guard, guard
for skip_torch, expected in (("false", "<cleared>"), ("true", "11.0.0")):
out = _run_sh(
f"{guard}\n"
" unset HSA_OVERRIDE_GFX_VERSION\n"
"fi\n"
'printf "%s\\n" "${HSA_OVERRIDE_GFX_VERSION:-<cleared>}"\n',
env = {
"SKIP_TORCH": skip_torch,
"_spoof_physical": "gfx1151",
"HSA_OVERRIDE_GFX_VERSION": "11.0.0",
},
)
assert out.strip() == expected, f"SKIP_TORCH={skip_torch}: {out!r}"