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
Route spoofed Strix Halo GPUs to the AMD per-gfx index (#8480)
Daniel Han5714530f277f
diff --git a/install.sh b/install.shindex 45d1ed83062..a00a7b552ad 100755--- a/install.sh+++ b/install.sh@@ -2941,6 +2941,142 @@ EOFreturn 1}+# gfx arch named by an HSA_OVERRIDE_GFX_VERSION value ($1), or nothing if it is not a+# readable major.minor.stepping triple. ROCr builds gfx<major><minor><stepping in hex>,+# which is why 9.0.10 is gfx90a: 11.0.0 -> gfx1100, 11.5.1 -> gfx1151, 10.3.0 -> gfx1030.+# Kept in sync with _hsa_override_gfx_arch in studio/install_python_stack.py.+_hsa_override_gfx_arch() {+ printf '%s' "${1:-}" | awk '+ {+ gsub(/^[[:space:]]+|[[:space:]]+$/, "")+ if ($0 !~ /^[0-9]+\.[0-9]+\.[0-9]+$/) exit+ split($0, p, ".")+ maj = p[1] + 0; min = p[2] + 0; step = p[3] + 0+ # Steppings are a single hex nibble; wider is not a real target.+ if (maj <= 0 || min > 9 || step > 15) exit+ printf "gfx%d%d%x", maj, min, step+ }'+}++# gfx arches the KERNEL sees, one line per AMD GPU node, from KFD topology sysfs.+# amdkfd writes gfx_target_version itself, so it is immune to HSA_OVERRIDE_GFX_VERSION+# (which ROCr applies in userland) -- the ground truth for unslothai#7331. Encoding is+# major*10000 + minor*100 + stepping in hex: 110000 -> gfx1100, 110501 -> gfx1151,+# 90010 -> gfx90a. CPU nodes carry no gfx_target_version and drop out; vendor_id 4098+# (0x1002) keeps NVIDIA's open-driver KFD nodes out, mirroring _has_amd_rocm_gpu.+# Kept in sync with _kfd_gfx_targets in studio/install_python_stack.py.+_kfd_gfx_targets() {+ [ -d /sys/class/kfd/kfd/topology/nodes ] || return 0+ for _kfd_node in /sys/class/kfd/kfd/topology/nodes/*/properties; do+ [ -r "$_kfd_node" ] || continue+ awk '+ /^[[:space:]]*vendor_id[[:space:]]/ { vendor = $2 }+ /^[[:space:]]*gfx_target_version[[:space:]]/ { gtv = $2 + 0 }+ END {+ if (vendor != 4098 || gtv <= 0) exit+ maj = int(gtv / 10000) % 100+ min = int(gtv / 100) % 100+ step = gtv % 100+ if (maj <= 0 || min > 9 || step > 15) exit+ printf "gfx%d%d%x\n", maj, min, step+ }' "$_kfd_node" 2>/dev/null || true+ done+ return 0+}++# Physical gfx arch when the ISA probe is an HSA_OVERRIDE_GFX_VERSION spoof+# (unslothai#7331): $1 = the arch inferred from the product name, $2 = the probed gfx+# token list. Prints the physical arch, or nothing to mean "believe the probe" (default).+#+# Requires ALL of the following, which keeps a mixed Strix APU + discrete AMD GPU host+# (the reason the probe outranks the product name at all) out of reach:+# * HSA_OVERRIDE_GFX_VERSION is set -- with no override there is nothing to doubt;+# * the product name inferred a spoofable RDNA 3.5 APU arch and the probe reported+# a DIFFERENT one;+# * the probe saw exactly ONE arch (rocminfo repeats the token per agent, so this+# counts DISTINCT tokens -- a pre-filter, not the safety property);+# * the variable names EXACTLY the arch that was reported: ROCr can only spoof to+# the target the variable names, so any other reading is real silicon;+# * a source the override cannot reach agrees with the product name: KFD sysfs+# first (the kernel), then rocminfo re-run with the variable unset.+# Corroboration is REQUIRED, with deliberately no "the variable names the reported arch,+# so assume a spoof" fallback: that shape is identical on a host telling the truth (a real+# gfx1100 dGPU in a Ryzen AI Max chassis whose owner set the override for unrelated+# reasons), and rerouting a working machine to the wrong wheels is worse than+# unslothai#7331 itself.+# Kept in sync with _hsa_spoofed_physical_gfx in studio/install_python_stack.py.+_hsa_spoofed_physical_gfx() {+ _hsp_inferred="${1:-}"+ _hsp_probed_all="${2:-}"+ [ -n "${HSA_OVERRIDE_GFX_VERSION:-}" ] || return 0+ case "$_hsp_inferred" in+ gfx1151|gfx1150|gfx1152) : ;;+ *) return 0 ;;+ esac+ # Exactly one DISTINCT arch, else the single-arch premise fails. Deduplicated because+ # the caller passes raw `rocminfo | grep -oE gfx...`, which repeats the token per+ # Name/ISA line -- counting lines would never fire on #7331's own host.+ _hsp_n=$(printf '%s\n' "$_hsp_probed_all" | awk 'NF && !seen[$0]++ { n++ } END { print n + 0 }')+ [ "${_hsp_n:-0}" -ne 1 ] && return 0+ _hsp_probed=$(printf '%s\n' "$_hsp_probed_all" | awk 'NF { print; exit }')+ [ -n "$_hsp_probed" ] || return 0+ [ "$_hsp_probed" = "$_hsp_inferred" ] && return 0+ # Only the arch the variable names can be a spoof of that variable's doing.+ [ "$(_hsa_override_gfx_arch "$HSA_OVERRIDE_GFX_VERSION")" = "$_hsp_probed" ] || return 0++ echo " [WARN] HSA_OVERRIDE_GFX_VERSION=$HSA_OVERRIDE_GFX_VERSION is set; ROCm reports" >&2+ echo " [WARN] $_hsp_probed but this host's product name is $_hsp_inferred. Checking for a spoof." >&2++ # 1. The kernel, which the override cannot reach. Decisive either way: if it answers+ # at all, no weaker source gets to overrule it.+ _hsp_kfd=$(_kfd_gfx_targets | awk 'NF')+ if [ -n "$_hsp_kfd" ]; then+ if [ "$_hsp_kfd" = "$_hsp_inferred" ]; then+ echo " [WARN] KFD topology sysfs reports $_hsp_inferred -- $_hsp_probed is a spoof." >&2+ printf '%s\n' "$_hsp_inferred"+ else+ # On a real gfx1100 card in a Ryzen AI Max chassis this is the CORRECT outcome.+ echo " [WARN] The kernel does not corroborate a spoof; keeping $_hsp_probed." >&2+ fi+ # Several GPU nodes: the single-arch premise was wrong (the spoof collapsed a+ # mixed host into one apparent arch). Decline.+ return 0+ fi++ # 2. The runtime, asked again without the override (ROCr getenv()s it while building+ # agent names, so stripping it retracts the spoofed name) and without the visible+ # masks, so a mask cannot hide the second GPU that would veto the correction. A+ # re-probe that still answers $_hsp_probed is evidence FOR the probe: the name did+ # not move, so it is real silicon. That is what keeps a genuine gfx1100 dGPU in a+ # Ryzen AI Max chassis on its own wheels.+ _hsp_re=""+ if command -v rocminfo >/dev/null 2>&1; then+ _hsp_re=$( (unset HSA_OVERRIDE_GFX_VERSION ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; \+ rocminfo 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' | awk 'NF && !seen[$0]++' || true)+ fi+ # rocminfo FAILS on the very host this exists for: strip the override on a ROCm stack+ # predating the physical arch and ROCr has no ISA entry for it, so hsa_init errors and+ # no agent is listed. amd-smi reads the driver and is override-immune, and+ # _detect_amd_gfx_codes falls through to it, so mirror that here.+ if [ -z "$_hsp_re" ] && command -v amd-smi >/dev/null 2>&1; then+ _hsp_re=$( (unset HSA_OVERRIDE_GFX_VERSION ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; \+ amd-smi list 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' | awk 'NF && !seen[$0]++' || true)+ if [ -z "$_hsp_re" ]; then+ _hsp_re=$( (unset HSA_OVERRIDE_GFX_VERSION ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; \+ amd-smi static --asic 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' | awk 'NF && !seen[$0]++' || true)+ fi+ fi+ if [ -z "$_hsp_re" ]; then+ echo " [WARN] Nothing left to re-probe and no KFD sysfs; keeping $_hsp_probed." >&2+ elif [ "$_hsp_re" = "$_hsp_inferred" ]; then+ echo " [WARN] $_hsp_inferred reported with HSA_OVERRIDE_GFX_VERSION unset -- spoof confirmed." >&2+ printf '%s\n' "$_hsp_inferred"+ else+ echo " [WARN] the re-probe does not corroborate a spoof; keeping $_hsp_probed." >&2+ fi+ return 0+}+# Reads the AMD gfx arch for wheel-index decisions: a user-set# UNSLOTH_ROCM_GFX_ARCH is authoritative (lowercased), else rocminfo, then# amd-smi. rocminfo/amd-smi honor ROCR/HIP_VISIBLE_DEVICES, so a container mask@@ -4007,6 +4143,16 @@ case "$_torch_index_leaf" in_gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; amd-smi static --asic 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' || true)fifi+ # HSA_OVERRIDE_GFX_VERSION=11.0.0 (the circulated Strix workaround) makes ROCr+ # hand rocminfo the SPOOFED ISA, so a gfx1151 host reports gfx1100 and the Strix+ # case below never matches (unslothai#7331). Correct the reading back to the+ # physical arch first, only in the narrow shape that cannot be a real mixed host.+ _spoof_physical=""+ if [ -n "${HSA_OVERRIDE_GFX_VERSION:-}" ] && [ -n "$_gfx_all" ]; then+ _spoof_inferred=$(_infer_linux_amd_gfx_arch 2>/dev/null || true)+ _spoof_physical=$(_hsa_spoofed_physical_gfx "$_spoof_inferred" "$_gfx_all")+ [ -n "$_spoof_physical" ] && _gfx_all="$_spoof_physical"+ fi_runtime_gfx=""if [ -n "$_gfx_all" ]; then_vis="${HIP_VISIBLE_DEVICES:-${ROCR_VISIBLE_DEVICES:-}}"@@ -4065,6 +4211,23 @@ case "$_torch_index_leaf" inTORCHVISION_CONSTRAINT="torchvision>=0.26.0,<0.27.0"TORCHAUDIO_CONSTRAINT="torchaudio>=2.11.0,<2.12.0"_amd_gpu_radeon=false+ # Routing the wheels is only half of unslothai#7331: ROCr rebuilds the agent+ # from HSA_OVERRIDE_GFX_VERSION in every LATER process (and this shell execs+ # Studio further down), so leaving it set hands the freshly installed per-gfx+ # wheels a device whose reported ISA matches none of their code. Only on this+ # branch, where the spoof was corroborated and native $_strix_gfx wheels are+ # going in; paths that keep generic wheels need the override as their only+ # source of kernels. SKIP_TORCH is the other half of "the wheels are going in":+ # --no-torch reaches this branch and installs nothing, so clearing the override+ # there would strand the host with generic wheels AND no override.+ # Mirrors _clear_confirmed_hsa_spoof in studio/install_python_stack.py.+ if [ -n "$_spoof_physical" ] && [ "$SKIP_TORCH" = false ]; then+ unset HSA_OVERRIDE_GFX_VERSION+ echo " [WARN] Clearing HSA_OVERRIDE_GFX_VERSION for the rest of this install:" >&2+ echo " [WARN] the $_strix_gfx wheels carry $_strix_gfx kernels, so the runtime has" >&2+ echo " [WARN] to report the real arch. Remove the export from your shell profile" >&2+ echo " [WARN] (~/.bashrc, ~/.profile) as well, or the next terminal restores it." >&2+ fifi# ── MI50 / Radeon VII (gfx906, Vega 20): legacy community-supported path ──# Newer rocm wheel families bundle ROCm libraries whose Tensile kernelsdiff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex ca4ab062267..8c63f67bf76 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -1457,7 +1457,11 @@ def _has_usable_nvidia_gpu() -> bool:_LAST_AMD_GFX_PROBE: "str | None" = None-def _detect_amd_gfx_codes(dedup: bool = True) -> list[str]:+def _detect_amd_gfx_codes(+ dedup: bool = True,+ ignore_hsa_override: bool = False,+ ignore_visible_masks: bool = False,+) -> list[str]:"""Return the AMD gfx ISA strings visible to ROCm (e.g. ['gfx1151']).Probes rocminfo, then falls back to ``amd-smi list`` and ``amd-smi@@ -1474,6 +1478,16 @@ def _detect_amd_gfx_codes(dedup: bool = True) -> list[str]:Records the answering probe in _LAST_AMD_GFX_PROBE, since only rocminfo isfiltered by a visible-device mask (and only by ROCR_VISIBLE_DEVICES).++ ignore_hsa_override=True strips HSA_OVERRIDE_GFX_VERSION from the probe's+ environment. ROCr applies it in userland, so rocminfo reports the SPOOFED ISA+ while it is set (unslothai#7331); re-probing without it is the one way to see+ the physical arch. amd-smi reads the driver, so stripping it there is a no-op.++ ignore_visible_masks=True additionally strips ROCR_VISIBLE_DEVICES and+ HIP_VISIBLE_DEVICES so the re-probe sees the WHOLE machine: a mask would+ otherwise hide the very second GPU whose presence is the reason to decline the+ correction. install.sh's re-probe unsets all three together."""global _LAST_AMD_GFX_PROBE_LAST_AMD_GFX_PROBE = None@@ -1506,6 +1520,19 @@ def _detect_amd_gfx_codes(dedup: bool = True) -> list[str]:probes.append(["amd-smi", "list"])probes.append(["amd-smi", "static", "--asic"])for cmd in probes:+ _env = _amd_smi_env() if cmd[0] == "amd-smi" else None+ _strip = set()+ if ignore_hsa_override:+ _strip.add("HSA_OVERRIDE_GFX_VERSION")+ if ignore_visible_masks:+ _strip.update(("ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES"))+ if _strip & set(os.environ):+ # env=None means "inherit", so drop the variables from an explicit copy.+ _env = {+ k: v+ for k, v in (_env if _env is not None else os.environ).items()+ if k not in _strip+ }try:result = subprocess.run(cmd,@@ -1513,7 +1540,7 @@ def _detect_amd_gfx_codes(dedup: bool = True) -> list[str]:stderr = subprocess.DEVNULL,text = True,timeout = 15,- env = _amd_smi_env() if cmd[0] == "amd-smi" else None,+ env = _env,)except Exception:continue@@ -1526,6 +1553,202 @@ def _detect_amd_gfx_codes(dedup: bool = True) -> list[str]:return []+# Arches the product name can establish on Linux whose wheels differ from the arch+# people spoof them to: exactly what _linux_amd_gfx_from_cpuinfo() returns, RDNA 3.5+# APUs ROCm did not support natively, so HSA_OVERRIDE_GFX_VERSION=11.0.0 became the+# circulated workaround. The correction below only ever fires for these.+_HSA_SPOOFABLE_PHYSICAL_GFX: frozenset[str] = frozenset({"gfx1151", "gfx1150", "gfx1152"})+++def _hsa_override_gfx_arch(value: "str | None") -> "str | None":+ """gfx arch named by an HSA_OVERRIDE_GFX_VERSION value, or None if unreadable.++ ROCr reads the variable as a major.minor.stepping triple and builds the target+ name as gfx<major><minor><stepping in hex>, which is why 9.0.10 is gfx90a:+ 11.0.0 -> gfx1100, 11.5.1 -> gfx1151, 10.3.0 -> gfx1030.+ """+ if not value:+ return None+ # [0-9] rather than str.isdigit()/\d, both of which accept non-ASCII digits+ # ("١١.0.0" would read as 11.0.0 here and be rejected by install.sh's awk).+ if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", value.strip()):+ return None+ major, minor, step = (int(p) for p in value.strip().split("."))+ # Steppings are a single hex nibble; anything wider is not a real target.+ if not (0 <= step <= 15) or major <= 0 or minor > 9:+ return None+ return f"gfx{major}{minor}{step:x}"+++def _kfd_gfx_targets() -> list[str]:+ """gfx arches of the AMD GPUs the KERNEL sees, from KFD topology sysfs.++ /sys/class/kfd/kfd/topology/nodes/<n>/properties carries gfx_target_version,+ written by amdkfd itself, so it is immune to HSA_OVERRIDE_GFX_VERSION (which+ ROCr applies in userland) and is the ground truth for #7331. Encoding is+ major * 10000 + minor * 100 + stepping, the stepping in hex: 110000 -> gfx1100,+ 110501 -> gfx1151, 90010 -> gfx90a.++ CPU nodes carry no gfx_target_version (or 0) and drop out; the vendor_id 4098+ (0x1002) guard mirrors _has_rocm_gpu() and keeps NVIDIA's open-driver KFD nodes+ out. Returns one entry per GPU node, in node order.+ """+ if sys.platform == "win32":+ return []+ nodes_dir = "/sys/class/kfd/kfd/topology/nodes"+ targets: list[str] = []+ try:+ entries = sorted(os.listdir(nodes_dir), key = lambda e: (len(e), e))+ except OSError:+ return []+ for entry in entries:+ try:+ with open(os.path.join(nodes_dir, entry, "properties"), encoding = "utf-8") as fh:+ props = fh.read()+ except (OSError, UnicodeDecodeError):+ continue+ if not re.search(r"\bvendor_id\s+4098\b", props):+ continue+ _m = re.search(r"\bgfx_target_version\s+(\d+)\b", props)+ if not _m:+ continue+ raw = int(_m.group(1))+ if raw <= 0:+ continue+ major, minor, step = (raw // 10000) % 100, (raw // 100) % 100, raw % 100+ if major <= 0 or minor > 9 or step > 15:+ continue # not a shape the gfx name concatenation can represent+ targets.append(f"gfx{major}{minor}{step:x}")+ return targets+++def _hsa_spoofed_physical_gfx(+ inferred_gfx: "str | None", gfx_devices: "list[str] | None" = None+) -> "str | None":+ """Physical arch when the ISA probe is an HSA_OVERRIDE_GFX_VERSION spoof (#7331).++ Returns None -- "believe the probe", today's behaviour -- unless all of:++ * HSA_OVERRIDE_GFX_VERSION is set. Without it there is nothing to doubt, so+ the deliberate #7305 precedence (a mixed Strix APU + dGPU host with the+ dGPU selected must not get APU wheels) is untouched.+ * The product name inferred an arch that people spoof and the probe reports+ a DIFFERENT one. An override naming the arch the hardware already is masks+ nothing.+ * The probe saw exactly one arch. A pre-filter, not the safety property:+ install.sh can only count DISTINCT tokens (its probe greps rocminfo, which+ repeats the token per agent), so counting arches here keeps the two+ implementations at the same verdict.+ * The variable names EXACTLY the reported arch. ROCr can only spoof to the+ target the variable names, so any other reading is real silicon.+ * A source the override cannot reach corroborates it, strongest first:++ 1. KFD topology sysfs (_kfd_gfx_targets). amdkfd writes gfx_target_version+ from the kernel's own IP-version table and ROCr, which applies the+ override in userland, never touches it. If the kernel names the+ inferred arch, the matter is settled.+ 2. Re-probing rocminfo with HSA_OVERRIDE_GFX_VERSION stripped (and the+ visible masks with it, so the re-probe sees the whole machine): ROCr+ getenv()s the override while building agent names, so without it the+ runtime itself retracts the spoofed name.++ Corroboration is REQUIRED, with deliberately no "the variable names the+ reported arch, so assume a spoof" fallback: that shape is indistinguishable+ from a truthful host (a real gfx1100 dGPU in a Ryzen AI Max chassis whose owner+ set the override for unrelated reasons), and rerouting a working machine to the+ wrong wheels is worse than #7331 itself. Two independent readings have to agree+ against the one spoofed reading before anything is overridden.+ """+ global _LAST_AMD_GFX_PROBE++ raw = os.environ.get("HSA_OVERRIDE_GFX_VERSION")+ if not raw or not inferred_gfx or inferred_gfx not in _HSA_SPOOFABLE_PHYSICAL_GFX:+ return None+ if gfx_devices is None:+ gfx_devices = _detect_amd_gfx_codes(dedup = False)+ if len(set(gfx_devices)) != 1:+ return None+ probed = gfx_devices[0]+ if probed == inferred_gfx:+ return None+ # Only the arch the variable names can be a spoof of that variable's doing.+ if _hsa_override_gfx_arch(raw) != probed:+ return None++ _safe_print(+ f" HSA_OVERRIDE_GFX_VERSION={raw} is set; ROCm reports {probed} but this host's\n"+ f" product name is {inferred_gfx}. Checking whether the ISA is being spoofed.\n"+ )++ def _confirm(physical: "list[str]", source: str) -> "str | None":+ """Decisive only when the source names the product arch and nothing else: a+ second arch means the single-arch premise was wrong (a mixed host whose+ second GPU the spoofed probe collapsed away), so decline. install.sh+ compares the same two strings, hence the verbatim KFD list and deduplicated+ re-probe."""+ if physical == [inferred_gfx]:+ _safe_print(+ f" {source} reports {inferred_gfx} -- {probed} is a spoof of the "+ f"physical arch.\n"+ )+ return inferred_gfx+ # Say so rather than leaving "Checking whether..." hanging: on a real gfx1100+ # card in a Ryzen AI Max chassis this is the CORRECT outcome.+ _safe_print(+ f" {source} does not corroborate a spoof "+ f"({physical or 'no answer'}); keeping {probed}.\n"+ )+ return None++ # 1. The kernel, which the override cannot reach. Decisive either way: if it+ # answers at all, no weaker source overrules it.+ kfd = _kfd_gfx_targets()+ if kfd:+ return _confirm(kfd, "KFD topology sysfs")++ # 2. The runtime, asked again without the override and without the visible+ # masks, so a mask cannot hide the second GPU that would veto the correction.+ _saved_probe = _LAST_AMD_GFX_PROBE+ try:+ reprobed = _detect_amd_gfx_codes(+ dedup = False, ignore_hsa_override = True, ignore_visible_masks = True+ )+ except Exception:+ reprobed = []+ finally:+ _LAST_AMD_GFX_PROBE = _saved_probe+ # A re-probe that still answers `probed` is evidence FOR the probe: the override+ # went away and the name did not move, so it is real silicon. Declining here is+ # why a genuine gfx1100 dGPU in a Ryzen AI Max chassis keeps its own wheels.+ return _confirm(list(dict.fromkeys(reprobed)), "rocminfo with HSA_OVERRIDE_GFX_VERSION unset")+++def _clear_confirmed_hsa_spoof(physical_gfx: str) -> None:+ """Drop a CONFIRMED HSA_OVERRIDE_GFX_VERSION spoof from this process's env.++ Routing the wheels is only half of #7331. ROCr reads the variable afresh in+ every LATER process -- libhsakmt writes props->EngineId straight from it while+ building the agent, so the agent's ISA name becomes the spoofed arch -- while+ AMD's per-gfx index ships code objects for the physical arch alone. Leave it set+ and the new wheel is handed a device whose name matches none of its code, so the+ first allocation fails exactly as before.++ Only ever called after corroboration and only on the branch installing native+ wheels for ``physical_gfx``, so the variable is provably lying about this host's+ only GPU and nothing on this path still needs it. A shell profile that exports+ it will set it again next login, which no installer can undo from here, so name+ the variable and say to remove it.+ """+ if os.environ.pop("HSA_OVERRIDE_GFX_VERSION", None) is None:+ return+ _safe_print(+ f" Clearing HSA_OVERRIDE_GFX_VERSION for the rest of this install: the\n"+ f" {physical_gfx} wheels carry {physical_gfx} kernels, so the runtime has to\n"+ f" report the real arch. Remove the export from your shell profile\n"+ f" (~/.bashrc, ~/.profile) as well, or the next terminal restores it.\n"+ )++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"):@@ -2801,6 +3024,13 @@ def _ensure_rocm_torch() -> None:# picks the wrong card when two GPUs share an arch (gfx1100,gfx1100,gfx1151# would read index 1 as the Strix).gfx_devices = _detect_amd_gfx_codes(dedup = False)+ # HSA_OVERRIDE_GFX_VERSION=11.0.0 (the circulated Strix workaround) makes ROCr+ # hand rocminfo the SPOOFED ISA, so a gfx1151 host reports gfx1100 and every+ # check below misses it (unslothai#7331). Correct the reading back to the+ # physical arch first, only in the narrow shape that cannot be a real mixed host.+ _physical_gfx = _hsa_spoofed_physical_gfx(_inferred_linux_gfx, gfx_devices)+ if _physical_gfx is not None:+ gfx_devices = [_physical_gfx]gfx_codes = list(dict.fromkeys(gfx_devices))_strix_gfx = {"gfx1151", "gfx1150", "gfx1152"}_detected_strix = _strix_gfx.intersection(gfx_codes)@@ -2841,6 +3071,12 @@ def _ensure_rocm_torch() -> None:f" with AMD's gfx1150/gfx1151 fixes (more reliable than the generic\n"f" pytorch.org rocm7.2 index on ROCm 7.3+ hosts).\n")+ # Only on this branch: these wheels carry _selected_gfx kernels, so+ # the runtime must stop reporting the spoofed arch or they have no+ # code for the device (#7331). Never on the paths that keep generic+ # wheels, where the override is the only source of usable kernels.+ if _physical_gfx is not None:+ _clear_confirmed_hsa_spoof(_selected_gfx)else:_gfx_str = ", ".join(sorted(_detected_strix))_safe_print(diff --git a/tests/studio/install/test_rocm_gfx_spoof_7331.py b/tests/studio/install/test_rocm_gfx_spoof_7331.pynew file mode 100644index 00000000000..f60fe6a47dd--- /dev/null+++ b/tests/studio/install/test_rocm_gfx_spoof_7331.py@@ -0,0 +1,1041 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Regression tests for issue #7331 -- Studio segfaults at startup on Strix Halo.++Reporter: Ryzen AI MAX+ 395 with Radeon 8060S (Strix Halo, physically gfx1151),+Linux Mint, ROCm 6.3.42134, single GPU. Their rocminfo reported **gfx1100** because+HSA_OVERRIDE_GFX_VERSION=11.0.0 -- the circulated Strix Halo workaround -- makes ROCr+hand the spoofed ISA to every consumer. The installer believed it, routed torch to+download.pytorch.org/whl/rocm6.3 (torch>=2.4,<2.11.0 -> 2.9.1+rocm6.3), and the first+allocation ran gfx1100 kernels on gfx1151 silicon and died with SIGSEGV. The reporter+later self-corrected the hardware to "gfx1151 / Strix Halo" and pointed at+pytorch/pytorch#173367.++Unsloth already infers gfx1151 from the product name in /proc/cpuinfo and already+routes gfx1151 to repo.amd.com/rocm/whl/gfx1151/ with torch>=2.11.0. The spoof+defeated it: the ISA probe answered, so the correct inference was discarded and the+Strix reroute intersected {gfx1151, gfx1150, gfx1152} against ["gfx1100"].++The mocks are shaped as the reporter's host, and deliberately not more:++ * ``_infer_linux_amd_gfx_arch -> "gfx1151"`` the cpuinfo product-name path,+ which is right and was being thrown away.+ * ``_detect_amd_gfx_codes -> ["gfx1100"]`` one device, the spoofed ISA. ONE+ arch matters: the correction only fires for a single-arch probe, so the mixed+ Strix-APU-plus-dGPU host the current precedence protects (#7305) is filtered+ out before the evidence ladder is consulted.+ * ``_has_rocm_gpu -> True`` rocminfo enumerates fine; not the+ runtime-less #7301 case.+ * ``_detect_rocm_version -> (6, 3)`` the reporter's ROCm, below the+ (7, 13) AMD per-arch floor, so the reroute gate is open.+ * ``HSA_OVERRIDE_GFX_VERSION = "11.0.0"`` the whole premise. With it unset+ every test here must fall back to today's behaviour.++There is no AMD hardware and no ROCm CI in this repo, so torch, rocminfo and pip+are all mocked; nothing below was validated on real silicon.+"""++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: "<hip marker>|<version>". Empty marker = CPU/CUDA torch.+_CPU_TORCH = b"|2.10.0+cpu\n"+_ROCM63_TORCH = b"6.3.42134|2.9.1+rocm6.3\n" # what the reporter ended up with+++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,+):+ """Drive _ensure_rocm_torch() over the reporter's host and return the pip calls.++ ``env_probe``, when a dict is passed, records os.environ["HSA_OVERRIDE_GFX_VERSION"]+ at the moment torch is installed. That instant is the one that matters: patch.dict+ restores the environment on exit, so an assertion made after the call cannot see a+ pop, and the env the install ends with is what later processes inherit.++ ``reprobe_devices`` is what rocminfo reports once HSA_OVERRIDE_GFX_VERSION is+ stripped; None means the re-probe answers with the same arch and so cannot+ disprove the spoof, the shape with no honest reading that must be declined.++ ``kfd_targets`` is what the kernel reports, defaulting to empty (no KFD sysfs, the+ common CI case) so each test names the evidence source it exercises.+ """+ 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 _infer_linux_amd_gfx_arch() returns UNSLOTH_ROCM_GFX_ARCH before it ever+ # looks at /proc/cpuinfo; a stub ignoring it would make the escape-hatch test assert+ # 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: without it, a tree predating the fix raises AttributeError,+ # which fails for the wrong reason. With it, the old code runs untouched and+ # fails on the assertion instead.+ 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 a key the outer environment sets, and each of these+ # silently decides the outcome: the UNSLOTH_* pair redirects the index, HSA_* is+ # the premise, and a stray visible-device mask re-indexes gfx_devices.+ 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)+++# ── The reported host ────────────────────────────────────────────────────────+++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 the host as the reporter left it: torch is already+ 2.9.1+rocm6.3, so has_hip_torch is True and only the Strix reroute can fire. It+ must, 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):+ """The shape with no honest answer: the kernel is silent and the re-probe still+ says gfx1100 with the override stripped, which is exactly what a real gfx1100+ dGPU looks like. Rerouting a working machine to the wrong wheels is worse than+ #7331 itself, so this host keeps today's routing rather than a coin flip."""+ 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+++# ── Everything the correction must NOT touch ─────────────────────────────────+++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 evidence of a spoof, so a probe that+ disagrees with the product name is taken at face value. This is+ test_rocm_support.py::test_inference_yields_to_runtime_visible_gpu's premise,+ deliberately unchanged."""+ 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 mixed host seen through the kernel: the spoofed probe collapsed a Strix+ APU and a gfx1100 dGPU into one apparent gfx1100, so the single-device premise+ held. KFD sysfs sees both and withdraws it, 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):+ """The mixed Strix APU + discrete AMD GPU host, override set globally so the APU+ spoofs to gfx1100 too. The probe reports two DEVICES, so the correction declines+ and today's visible-mask selection decides. This is what makes the single-device+ requirement load-bearing rather than decorative."""+ 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):+ """The nastiest shape. The product name comes from the CPU model in+ /proc/cpuinfo, so a Ryzen AI Max machine infers gfx1151 whatever card is in the+ slot; drop a real RX 7900 XTX in it (APU off in the BIOS, so one device) and a+ user carrying the override for an unrelated reason presents EXACTLY the+ reporter's fingerprint: inferred gfx1151, probed gfx1100, one device, override+ naming gfx1100.++ Only the kernel tells them apart, and it must be believed: gfx_target_version+ 110000 is a real gfx1100 and the card keeps its own wheels."""+ 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):+ """The same card in a container with no /sys/class/kfd, so only the re-probe can+ arbitrate: it answers gfx1100 with the override stripped, which is evidence FOR+ the probe. This is what the removed "override names the probe, so assume a spoof"+ fallback used to get wrong."""+ 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 on an RX 6800 is the documented and CORRECT setting for that card. The+ chassis is still a Ryzen AI Max, so the name still infers gfx1151 and the probe+ still disagrees, but that does not make gfx1030 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 can only rename an agent to the target the variable names, so 10.3.0+ alongside a gfx1100 reading means gfx1100 came from the silicon. No spoof to+ undo, even if the kernel is silent and the re-probe agrees."""+ 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):+ """ROCR_VISIBLE_DEVICES pinned to the dGPU on a Strix + 7900 XTX box collapses+ the probe to one gfx1100, so the single-arch premise holds and the kernel is+ unavailable in the container. The re-probe must clear the mask as well as the+ override, or the second GPU that vetoes the correction 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+++# ── The HSA_OVERRIDE_GFX_VERSION -> gfx reading ──────────────────────────────+++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 + stepping, the+ stepping in hex. gfx1151 is 110501; the 110511 circulating online decodes to a+ nonexistent part, so it is pinned here. Reads a fabricated sysfs tree."""++ 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"]+++# ── install.sh parity ────────────────────────────────────────────────────────+++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")+ # The kernel source is stubbed: CI has no /sys/class/kfd and the point here is+ # the DECISION; 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 routes the curl | sh install #7331 was reported against, so it must+ reach the same verdict as install_python_stack.py: a host a `studio update` fixes+ and a fresh install re-breaks is the worst outcome. These EXECUTE the shell helpers+ rather than grepping for them."""++ @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"], []), # no gtv line+ (["vendor_id 4098\ngfx_target_version notanumber\n"], []), # malformed+ ([""], []), # empty properties+ ([], []), # no nodes at all+ ],+ )+ def test_kfd_reader_matches_python(self, tmp_path, nodes, expected):+ """The shell KFD parser EXECUTED against a fabricated topology tree.+ gfx_target_version is major*10000 + minor*100 + stepping in hex (110501 ->+ gfx1151); decoding it decimally, or letting a CPU / NVIDIA node through, would+ misroute every Strix host. Only the sysfs root differs from the shipped one."""+ 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 the host this feature exists for: strip the override on a+ ROCm stack older than the physical arch and hsa_init errors with no agents+ listed. amd-smi reads the driver and still answers, and _detect_amd_gfx_codes+ falls through to it, so install.sh must too or a `studio update` fixes a host a+ fresh `curl | sh` install leaves on the segfaulting wheels."""+ _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++ # The Python side, same host, so the parity claim is asserted and not assumed.+ 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 (rocminfo, then the two amd-smi fallbacks); any that+ # dropped fewer would re-probe a masked or still-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+++# ── Randomized shell/Python parity ───────────────────────────────────────────++# A fake rocminfo shared by both implementations, so each executes its OWN re-probe+# (env stripping included) rather than a mock. It models the behaviour under test: ROCr+# renames every agent to HSA_OVERRIDE_GFX_VERSION's target when set, and reports the+# physical arch when not; ROCR_VISIBLE_DEVICES selects agents. The output repeats the+# token per Name / ISA line, which is what makes the shell's raw `grep -oE` produce+# several lines per single 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 ***"+"""++[email protected](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):+ """A randomized host matrix: override x physical arches x probed arches x KFD+ contents x mask. The override values include what users actually produce (empty,+ whitespace, non-numeric, wrong component count, absurd magnitudes), which reach the+ same helper as 11.0.0."""+ 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]))]+ # The probe list as install.sh builds it: raw tokens, repeated per agent.+ 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 reach the SAME verdict on every host+ shape, or a `studio update` fixes a machine a fresh `curl | sh` install re-breaks.+ The named shapes above pin the rules; this pins the whole space, including the+ re-probe, which they cannot reach on a box with no rocminfo."""++ @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):+ """The safety invariant over the same random matrix: a verdict is only returned+ when a source the override cannot reach (the kernel, or rocminfo re-probed+ without it) 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 by the unspoofed physical truth the+ # re-probe reads back. 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:+ """The parity a helper-level comparison cannot see: each side builds its OWN probe+ input from the same rocminfo the way its call site does. install.sh feeds+ `rocminfo | grep -oE 'gfx...'` STRAIGHT in, so one GPU arrives as two or three+ repeated tokens, while install_python_stack.py splits on agent headers and gets one+ entry per device. A pre-shaped list hides that difference, and it is exactly what+ decides whether the correction fires on the host #7331 was reported from."""++ @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++ # install.sh's call site, verbatim: raw grep output, duplicates and all.+ 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 ""+ )++ # install_python_stack.py's call site: one entry per agent.+ 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":+ # Guards against the sweep passing because neither side ever fires: 11.0.0+ # on a gfx1151 chassis is the reported case and MUST correct somewhere.+ assert corrections, f"no shape corrected across {shapes} shapes"+++# ── Clearing the confirmed spoof from the launched runtime ───────────────────+++class TestConfirmedSpoofIsClearedBeforeLaunch:+ """Routing the wheels is only half of #7331. ROCr rebuilds the agent from+ HSA_OVERRIDE_GFX_VERSION in every later process (libhsakmt's topology.c writes+ props->EngineId straight from the variable) and AMD's per-gfx index ships code+ objects for one arch only, so a runtime still reporting gfx1100 gets a gfx1151 wheel+ with no code for the device it sees and fails at the first allocation."""++ 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, where the+ override is the user's own business. Nothing was disproved, so nothing is taken+ away."""+ 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 Studio+ 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 Studio, 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"+ )+ # Exactly one clear of the caller's own environment; the only other unset scopes+ # three variables inside the re-probe's subshell. Every other branch keeps the+ # override, which on generic wheels is what makes the GPU usable at all.+ _lasting = [+ ln.strip()+ for ln in source.splitlines()+ if ln.strip().startswith("unset HSA_OVERRIDE_GFX_VERSION")+ ]+ assert _lasting == ["unset HSA_OVERRIDE_GFX_VERSION"], _lasting+++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():+ """--no-torch must not clear the spoof, since it installs nothing to replace it.++ Clearing is only sound because native per-gfx wheels are going in on that branch.+ `--no-torch` (and the Intel Mac auto-detection, which sets the same SKIP_TORCH)+ reaches the reroute and installs no torch, so clearing there strands the host with+ the generic wheels it already had AND no override, its only source of usable kernels.++ Executes the guard as written rather than matching its text, so a rewrite that keeps+ the words and loses the behaviour still fails.+ """+ 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}"diff --git a/tests/studio/test_cli_hsa_spoof_launch_7331.py b/tests/studio/test_cli_hsa_spoof_launch_7331.pynew file mode 100644index 00000000000..166b5f68660--- /dev/null+++ b/tests/studio/test_cli_hsa_spoof_launch_7331.py@@ -0,0 +1,344 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Regression tests for the launch half of issue #7331.++Routing the wheels is only half the fix. libhsakmt (topology.c) writes+HSA_OVERRIDE_GFX_VERSION's major.minor.stepping straight into the KFD node's EngineId+and ROCr names the agent from that, so the variable decides the ISA every later+process reports. AMD's per-gfx index ships single-arch wheels (the distribution beside+torch is named rocm_sdk_libraries_gfx1151), so an override naming a different arch+leaves the runtime asking for kernels the install does not contain.++install.sh clears the variable for the one launch it performs itself, but that unset+dies with the installer: `unsloth studio update` runs install_python_stack.py as a+child (studio/setup.sh:1444), so the repair path, the generated launch-studio.sh and a+hand-typed `unsloth studio` (issue #7331's own repro) all still start with the spoof+in place. The CLI is the chokepoint all of them pass through.++There is no AMD hardware and no ROCm CI in this repo; the venv layouts below are+fixtures and nothing here was validated on real silicon.+"""++from __future__ import annotations++import os+import re+from pathlib import Path++import pytest++import unsloth_cli.commands.studio as studio_cli+++def _make_venv(+ tmp_path: Path,+ dist: "str | None",+ layout: str = "posix",+ orphans: "tuple[str, ...]" = (),+ torch_needs_rocm: bool = True,+) -> Path:+ """A venv tree shaped like a real AMD per-gfx install.++ ``dist`` is the ACTIVE runtime, so it gets both its own distribution and the+ ``rocm`` meta-package whose Requires-Dist names it -- the real layout, verified+ against repo.amd.com/rocm/whl/gfx1151, where rocm 7.13.0 carries+ ``Requires-Dist: rocm-sdk-libraries-gfx1151==7.13.0; extra == "libraries"``.+ ``None`` is a generic multi-arch index, which installs neither.++ ``orphans`` are superseded runtimes left behind by a family switch: pip has no+ autoremove and the old distribution keeps its own name, so they accumulate.++ ``torch_needs_rocm`` is the dependency edge that makes the meta-package+ authoritative. AMD's per-gfx torch resolves through ``rocm``; the generic+ pytorch.org ROCm wheels vendor their runtime and require nothing, so False with a+ ``dist`` present is the "switched to generic, meta-package orphaned" shape.+ """+ venv = tmp_path / "unsloth_studio"+ sp = (+ venv / "lib" / "python3.12" / "site-packages"+ if layout == "posix"+ else venv / "Lib" / "site-packages"+ )+ sp.mkdir(parents = True)+ _torch = sp / "torch-2.11.0.dist-info"+ _torch.mkdir()+ (_torch / "METADATA").write_text(+ "Metadata-Version: 2.1\nName: torch\nVersion: 2.11.0\nRequires-Dist: filelock\n"+ + ("Requires-Dist: rocm[libraries]==7.13.0\n" if torch_needs_rocm else ""),+ encoding = "utf-8",+ )+ for _orphan in orphans:+ (sp / f"rocm_sdk_libraries_{_orphan}-7.12.0.dist-info").mkdir()+ if dist is not None:+ (sp / f"{dist}-7.13.0.dist-info").mkdir()+ _family = dist.replace("rocm_sdk_libraries_", "")+ _meta = sp / "rocm-7.13.0.dist-info"+ _meta.mkdir()+ (_meta / "METADATA").write_text(+ "Metadata-Version: 2.1\nName: rocm\nVersion: 7.13.0\n"+ "Provides-Extra: libraries\n"+ f'Requires-Dist: rocm-sdk-libraries-{_family}==7.13.0; extra == "libraries"\n'+ "Requires-Dist: rocm-sdk-core==7.13.0\n",+ encoding = "utf-8",+ )+ return venv++[email protected](autouse = True)+def _no_inherited_override(monkeypatch):+ """The developer box may export the variable; every assertion is about it."""+ monkeypatch.delenv("HSA_OVERRIDE_GFX_VERSION", raising = False)+++class TestOverrideParsing:+ """The third copy of the parser (install.sh and install_python_stack.py hold the+ others) has to agree with libhsakmt, which reads the value with+ sscanf("%u.%u.%u%c") != 3 and concatenates the stepping in HEX."""++ @pytest.mark.parametrize(+ "value,expected",+ [+ ("11.0.0", "gfx1100"), # the circulated Strix workaround+ ("11.5.1", "gfx1151"), # Strix Halo, naming its own arch+ ("10.3.0", "gfx1030"), # the documented RX 6800 override+ ("9.0.10", "gfx90a"), # stepping 10 renders as 'a', not "gfx9010"+ (" 11.0.0 ", "gfx1100"),+ ("", None),+ ("garbage", None),+ ("11.0", None),+ ("11.0.0.0", None),+ ("-1.0.0", None),+ ("11.0.16", None), # stepping wider than one hex nibble+ ("11.10.0", None),+ ],+ )+ def test_reading(self, value, expected):+ assert studio_cli._hsa_override_gfx_arch(value) == expected++ def test_matches_the_installer_copy(self):+ """A drifted parser would clear the variable on hosts the installer left alone."""+ import importlib.util+ import sys++ path = Path(studio_cli.__file__).resolve().parents[2] / "studio" / "install_python_stack.py"+ # setup.sh invokes it by path, so its own directory is sys.path[0] there.+ if str(path.parent) not in sys.path:+ sys.path.insert(0, str(path.parent))+ spec = importlib.util.spec_from_file_location("_stack_for_7331_cli", path)+ stack = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(stack)+ for value in ("11.0.0", "11.5.1", "10.3.0", "9.0.10", "garbage", "", "11.0.16", "11.10.0"):+ assert studio_cli._hsa_override_gfx_arch(value) == stack._hsa_override_gfx_arch(+ value+ ), value+++class TestInstalledArchReading:+ """The arch comes from the install, not from a hardware probe."""++ @pytest.mark.parametrize("layout", ["posix", "windows"])+ def test_reads_the_per_gfx_distribution(self, tmp_path, layout):+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151", layout)+ assert studio_cli._installed_rocm_single_arch(venv) == "gfx1151"++ def test_generic_index_installs_no_such_distribution(self, tmp_path):+ """Generic pytorch.org wheels are multi-arch and bring no rocm_sdk_libraries_*+ dist, so there is nothing to contradict."""+ venv = _make_venv(tmp_path, None)+ assert studio_cli._installed_rocm_single_arch(venv) is None++ def test_missing_venv_is_not_an_error(self, tmp_path):+ assert studio_cli._installed_rocm_single_arch(tmp_path / "absent") is None+++class TestClearingTheContradictingOverride:+ def test_the_reported_host(self, tmp_path, monkeypatch):+ """gfx1151 wheels installed, HSA_OVERRIDE_GFX_VERSION=11.0.0 still exported.+ Every kernel image is gfx1151, so the agent must stop answering gfx1100 or the+ first allocation fails as before."""+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "11.0.0")+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151")+ assert studio_cli._clear_hsa_override_contradicting_install(venv) == "gfx1151"+ assert "HSA_OVERRIDE_GFX_VERSION" not in os.environ++ def test_override_naming_the_installed_arch_is_left_alone(self, tmp_path, monkeypatch):+ """11.5.1 on a gfx1151 install is a no-op remap, not a contradiction."""+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "11.5.1")+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151")+ assert studio_cli._clear_hsa_override_contradicting_install(venv) is None+ assert os.environ["HSA_OVERRIDE_GFX_VERSION"] == "11.5.1"++ def test_generic_wheels_keep_the_override(self, tmp_path, monkeypatch):+ """The override is often the ONLY thing making an unsupported card usable against+ a generic multi-arch index. Clearing it there breaks a working machine, which is+ worse than #7331."""+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "10.3.0")+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")+ venv = _make_venv(tmp_path, None)+ assert studio_cli._clear_hsa_override_contradicting_install(venv) is None+ assert os.environ["HSA_OVERRIDE_GFX_VERSION"] == "10.3.0"++ def test_unreadable_value_is_not_ours_to_remove(self, tmp_path, monkeypatch):+ """libhsakmt rejects it too (sscanf != 3), so it is not this spoof."""+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "garbage")+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151")+ assert studio_cli._clear_hsa_override_contradicting_install(venv) is None+ assert os.environ["HSA_OVERRIDE_GFX_VERSION"] == "garbage"++ def test_unset_variable_does_nothing(self, tmp_path, monkeypatch):+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151")+ assert studio_cli._clear_hsa_override_contradicting_install(venv) is None++ def test_windows_is_untouched(self, tmp_path, monkeypatch):+ """ROCm on Windows ignores HSA_OVERRIDE_GFX_VERSION, so there is no spoof to undo."""+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "11.0.0")+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Windows")+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151", "windows")+ assert studio_cli._clear_hsa_override_contradicting_install(venv) is None+ assert os.environ["HSA_OVERRIDE_GFX_VERSION"] == "11.0.0"+++class TestTheLaunchPathActuallyCallsIt:+ """The call has to sit ABOVE all three launch paths (os.execvp, the Windows Popen,+ the in-process run_server), or the child inherits the spoof anyway."""++ def test_called_before_every_launch_path(self):+ source = Path(studio_cli.__file__).resolve().read_text(encoding = "utf-8")+ call = source.find("_clear_hsa_override_contradicting_install(")+ # The definition comes first; find the CALL, which follows it.+ call = source.find("_clear_hsa_override_contradicting_install(", call + 1)+ assert call != -1, "the CLI must clear a contradicting override before launching"+ for marker in (+ "os.execvp(str(studio_python), args)",+ "proc = _sp.Popen(",+ "run_server = run_mod.run_server",+ ):+ at = source.find(marker)+ assert at != -1, marker+ assert call < at, f"the clear must precede {marker}"++ def test_it_mutates_the_environment_the_child_inherits(self, tmp_path, monkeypatch):+ """os.execvp and Popen pass os.environ through, so popping the key there is what+ reaches the launched process. A local variable would not."""+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "11.0.0")+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151")+ studio_cli._clear_hsa_override_contradicting_install(venv)+ assert "HSA_OVERRIDE_GFX_VERSION" not in dict(os.environ)+++def test_the_installer_and_the_cli_agree_on_the_spoofable_arches():+ """install.sh, install_python_stack.py and this module all key on the RDNA 3.5 APU+ arches; a per-gfx index for any of them ships the matching rocm_sdk_libraries_*+ distribution the CLI keys on instead."""+ install_sh = (Path(studio_cli.__file__).resolve().parents[2] / "install.sh").read_text(+ encoding = "utf-8"+ )+ assert re.search(r"gfx1151\|gfx1150\|gfx1152", install_sh)+++class TestOrphanedRuntimesFromAFamilySwitch:+ """pip never uninstalls the superseded arch-specific runtime across a family switch:+ `rocm` is upgraded in place, but rocm-sdk-libraries-<old> keeps its own name and+ stays on disk, so globbing for that directory reads whichever the filesystem hands+ back and clearing on a stale reading breaks a working machine. Same hazard as+ install_python_stack.py's _installed_rocm_wheel_family."""++ def test_the_active_family_wins_over_an_orphan(self, tmp_path):+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151", orphans = ("gfx1100",))+ assert studio_cli._installed_rocm_single_arch(venv) == "gfx1151"++ def test_an_orphan_alone_arbitrates_nothing(self, tmp_path):+ """Switched to generic wheels: `rocm` is gone, the old runtime is not, so there+ is no active single-arch install and nothing may be cleared."""+ venv = _make_venv(tmp_path, None, orphans = ("gfx1151",))+ assert studio_cli._installed_rocm_single_arch(venv) is None++ def test_switching_to_generic_wheels_keeps_the_override(self, tmp_path, monkeypatch):+ """The failure the orphan causes end to end: a host that once had gfx1151 wheels+ and now runs generic ones would lose its override to a directory nothing uses."""+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "11.0.0")+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")+ venv = _make_venv(tmp_path, None, orphans = ("gfx1151",))+ assert studio_cli._clear_hsa_override_contradicting_install(venv) is None+ assert os.environ["HSA_OVERRIDE_GFX_VERSION"] == "11.0.0"++ def test_a_multi_arch_family_contradicts_nothing(self, tmp_path):+ """gfx120x-all carries kernels for several ISAs, so an override naming one is+ not asking for code the install lacks."""+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx120X-all")+ assert studio_cli._installed_rocm_single_arch(venv) is None++ def test_two_families_named_by_the_metadata_decline(self, tmp_path):+ """Nothing to arbitrate with; guess and you break one of the two."""+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151")+ _meta = next(venv.rglob("rocm-7.13.0.dist-info")) / "METADATA"+ _meta.write_text(+ _meta.read_text(encoding = "utf-8")+ + 'Requires-Dist: rocm-sdk-libraries-gfx1100==7.13.0; extra == "other"\n',+ encoding = "utf-8",+ )+ assert studio_cli._installed_rocm_single_arch(venv) is None+++class TestEveryLaunchEntryPointClearsIt:+ """`unsloth studio` is not the only way in: the group callback returns as soon as a+ subcommand is named and `unsloth run` is bound straight to studio_run, so the two+ commands people actually use would keep the spoof."""++ def test_run_clears_it_itself(self):+ source = Path(studio_cli.__file__).resolve().read_text(encoding = "utf-8")+ _run_at = source.find("\ndef run(\n")+ assert _run_at != -1, "the run command moved"+ assert "_clear_hsa_override_before_launch(" in source[_run_at:], (+ "`unsloth studio run` and the `unsloth run` alias bypass the group "+ "callback's clear, so run() has to perform it itself"+ )++ def test_the_group_callback_uses_the_same_helper(self):+ source = Path(studio_cli.__file__).resolve().read_text(encoding = "utf-8")+ assert (+ source.count("_clear_hsa_override_before_launch(") >= 3+ ), "one definition plus a call from each entry point"++ def test_the_helper_is_idempotent(self, tmp_path, monkeypatch):+ """studio_default and run can both run in one process; the second call must not+ raise on an already-removed key."""+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "11.0.0")+ monkeypatch.setattr(studio_cli.platform, "system", lambda: "Linux")+ venv = _make_venv(tmp_path, "rocm_sdk_libraries_gfx1151")+ monkeypatch.setattr(studio_cli, "STUDIO_HOME", venv.parent)+ assert studio_cli._clear_hsa_override_before_launch(silent = True) == "gfx1151"+ assert studio_cli._clear_hsa_override_before_launch(silent = True) is None+ assert "HSA_OVERRIDE_GFX_VERSION" not in os.environ++ def test_the_top_level_run_alias_is_the_same_function(self):+ """unsloth_cli/__init__.py binds `unsloth run` to studio_run directly, so the+ group callback is skipped there."""+ import unsloth_cli+ assert unsloth_cli.studio_run is studio_cli.run+++def test_a_rocm_metapackage_orphaned_by_a_switch_to_generic_wheels_arbitrates_nothing(tmp_path):+ """A `rocm` meta-package orphaned by a switch to generic wheels must decide nothing.++ The generic pytorch.org ROCm wheels vendor their own runtime and depend on no+ meta-package, and pip has no autoremove, so `rocm` survives the switch describing the+ family the OLD torch resolved. Trusting it would clear an override the generic wheels+ may be the only reason the GPU works at all. Torch's own requirements are the+ discriminator, so the identical tree with an AMD torch still arbitrates.+ """+ from unsloth_cli.commands.studio import _installed_rocm_single_arch++ live = _make_venv(tmp_path / "live", "rocm_sdk_libraries_gfx1151")+ assert _installed_rocm_single_arch(live) == "gfx1151"++ orphaned = _make_venv(+ tmp_path / "orphaned", "rocm_sdk_libraries_gfx1151", torch_needs_rocm = False+ )+ assert _installed_rocm_single_arch(orphaned) is Nonediff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 098dd2b2c25..97500723397 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -253,6 +253,177 @@ def _studio_venv_python() -> Optional[Path]:return p if p.is_file() else None+def _hsa_override_gfx_arch(value: Optional[str]) -> Optional[str]:+ """gfx arch named by an HSA_OVERRIDE_GFX_VERSION value, or None if unreadable.++ libhsakmt (topology.c) reads it as a major.minor.stepping triple+ (``sscanf(envvar, "%u.%u.%u%c") != 3`` rejects anything else) and the target+ name concatenates the stepping in hex, which is why 9.0.10 is gfx90a:+ 11.0.0 -> gfx1100, 11.5.1 -> gfx1151.++ Kept in sync with _hsa_override_gfx_arch in studio/install_python_stack.py and+ in install.sh.+ """+ if not value:+ return None+ # [0-9] rather than str.isdigit()/\d, both of which accept non-ASCII digits.+ if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", value.strip()):+ return None+ major, minor, step = (int(p) for p in value.strip().split("."))+ # Steppings are a single hex nibble; anything wider is not a real target.+ if not (0 <= step <= 15) or major <= 0 or minor > 9:+ return None+ return f"gfx{major}{minor}{step:x}"+++def _torch_requires_rocm_metapackage(venv_dir: Path) -> bool:+ """Whether the installed torch actually resolves through the ``rocm`` meta-package.++ AMD's per-gfx wheels depend on it; the generic pytorch.org ROCm wheels vendor their+ own runtime and depend on nothing, so after a switch between them the meta-package is+ left behind describing a family with no bearing on what torch loads. Unknown shapes+ answer False: refusing to arbitrate leaves the environment untouched.+ """+ for sp_pattern in ("lib/python*/site-packages", "Lib/site-packages"):+ for sp in venv_dir.glob(sp_pattern):+ for info in sp.glob("torch-*.dist-info"):+ if not re.fullmatch(r"torch-[^-]+\.dist-info", info.name):+ continue+ metadata = info / "METADATA"+ if not metadata.is_file():+ continue+ try:+ text = metadata.read_text(encoding = "utf-8", errors = "replace")+ except OSError:+ return False+ for line in text.splitlines():+ if not line.lower().startswith("requires-dist:"):+ continue+ # `Requires-Dist: rocm[libraries,devel]==7.13.0` and plain `rocm` both+ # count; `rocm-sdk-core` does not, it is a component not the arbiter.+ if re.search(r"requires-dist:\s*rocm(?![-_a-z0-9])", line, re.IGNORECASE):+ return True+ return False+ return False+++def _installed_rocm_single_arch(venv_dir: Path) -> Optional[str]:+ """gfx arch the ROCm runtime in *venv_dir* ACTIVELY carries kernels for, or None.++ AMD's per-gfx index ships one runtime distribution per architecture,+ ``rocm-sdk-libraries-<family>``, and the torch beside it holds code objects for+ that family alone. Which one is live has to come from the ``rocm`` meta-package,+ whose ``Requires-Dist`` names the family AMD's torch resolved (verified on+ repo.amd.com/rocm/whl/gfx1151: ``rocm-sdk-libraries-gfx1151==7.13.0; extra ==+ "libraries"``). Globbing for a ``rocm_sdk_libraries_gfx*`` directory instead+ would read an ORPHAN: ``rocm`` upgrades in place across a family switch while the+ superseded runtime keeps its own distribution name and is never uninstalled, so a+ venv that has changed families holds both. Same reasoning and hazard as+ _installed_rocm_wheel_family in studio/install_python_stack.py.++ None means "do not act": no ``rocm``, unreadable metadata, more than one family+ named, or a MULTI-arch family such as gfx120x-all, whose runtime carries kernels+ for several ISAs and so contradicts no override.+ """+ # The bare `rocm` metadata only describes a LIVE install while torch still resolves+ # through it. Switching from AMD's per-gfx index to a generic pytorch.org one does not+ # uninstall it: the generic wheels vendor their own ROCm libraries and depend on no+ # meta-package, so `rocm` is orphaned and pip never removes it. Reading it then would+ # name the OLD family and clear an override the generic wheels may be the only reason+ # the GPU works at all.+ if not _torch_requires_rocm_metapackage(venv_dir):+ return None+ _metadata: Optional[Path] = None+ for sp_pattern in ("lib/python*/site-packages", "Lib/site-packages"):+ for sp in venv_dir.glob(sp_pattern):+ for info in sp.glob("rocm-*.dist-info"):+ # rocm-sdk-core and rocm-sdk-libraries-* also start "rocm-"; only the+ # bare `rocm` meta-package arbitrates.+ if (+ re.fullmatch(r"rocm-[^-]+\.dist-info", info.name)+ and (info / "METADATA").is_file()+ ):+ _metadata = info / "METADATA"+ break+ if _metadata is None:+ return None+ try:+ _text = _metadata.read_text(encoding = "utf-8", errors = "replace")+ except OSError:+ return None+ _families = set()+ for _line in _text.splitlines():+ if not _line.lower().startswith("requires-dist:"):+ continue+ _m = re.search(r"rocm[-_]sdk[-_]libraries[-_]([0-9a-zA-Z]+)", _line)+ if _m:+ _families.add(_m.group(1).lower())+ if len(_families) != 1:+ return None # nothing to arbitrate with, or two runtimes and no tie-break+ _family = _families.pop()+ # Single ISA only: gfx120x-all style families cover several architectures, so an+ # override naming one of them is contradicted by nothing.+ return _family if re.fullmatch(r"gfx[0-9a-f]+", _family) else None+++def _clear_hsa_override_contradicting_install(venv_dir: Path) -> Optional[str]:+ """Drop an HSA_OVERRIDE_GFX_VERSION no installed kernel can satisfy (#7331).++ libhsakmt (topology.c) writes the variable's major.minor.stepping straight into+ the KFD node's EngineId and ROCr names the agent from that, so the override+ decides the ISA every later process sees. Against per-gfx wheels, which hold code+ objects for one architecture, an override naming a different one leaves the+ runtime asking for kernels the install does not contain and every launch fails on+ the first allocation, exactly as before the routing fix.++ install.sh clears it for the one launch it performs itself, but that unset dies+ with the installer: `unsloth studio update` runs install_python_stack.py as a+ child (studio/setup.sh:1444) and every later launch inherits the user's shell+ instead. This is the chokepoint the exec, the Windows Popen and the in-process+ paths all pass through.++ Keyed on the INSTALL, never on a hardware probe: on a generic multi-arch index+ there is nothing to contradict and the override is often the only thing making+ the GPU usable. Returns the installed arch when the variable was dropped.+ """+ raw = os.environ.get("HSA_OVERRIDE_GFX_VERSION")+ # Windows ROCm ignores the variable entirely, so there is nothing to correct.+ if not raw or platform.system() == "Windows":+ return None+ arch = _installed_rocm_single_arch(venv_dir)+ if arch is None:+ return None+ named = _hsa_override_gfx_arch(raw)+ # Unreadable: libhsakmt rejects it too, so it is not this spoof to undo.+ if named is None or named == arch:+ return None+ os.environ.pop("HSA_OVERRIDE_GFX_VERSION", None)+ return arch+++def _clear_hsa_override_before_launch(silent: bool = False) -> Optional[str]:+ """Run the #7331 spoof clear for whichever entry point is about to launch.++ Every launch needs it, not just plain ``unsloth studio``: the group callback+ returns early once a subcommand is named, and ``unsloth run`` is bound straight+ to ``studio_run``, so both would otherwise reach llama-server and the backend+ with the contradicting override still set. Idempotent, so chained entry points+ are free to call it twice.+ """+ _venv = STUDIO_HOME / "unsloth_studio"+ _arch = _clear_hsa_override_contradicting_install(+ Path(sys.prefix) if sys.prefix.startswith(str(_venv)) else _venv+ )+ if _arch is not None and not silent:+ typer.echo(+ f"Cleared HSA_OVERRIDE_GFX_VERSION: this install carries {_arch} kernels "+ f"only, so the runtime has to report the real arch. Remove the export "+ f"from your shell profile as well, or the next terminal restores it.",+ err = True,+ )+ return _arch++def _find_run_py() -> Optional[Path]:"""Find studio/backend/run.py.@@ -1547,6 +1718,10 @@ def studio_default(# must_change_password=1 with no password to log in.studio_venv_dir = STUDIO_HOME / "unsloth_studio"in_studio_venv = sys.prefix.startswith(str(studio_venv_dir))+ # Before any of the three launch paths below, and before the environment is handed+ # to a child: an override contradicting single-arch wheels makes every kernel launch+ # fail, and the installer's own unset cannot reach a launch it does not perform (#7331).+ _clear_hsa_override_before_launch(silent = silent)studio_python = run_py = Noneresolved_frontend = frontendif not in_studio_venv:@@ -2095,6 +2270,10 @@ def run(inherited_start_api_key_marker = _consume_start_api_key_marker_env()start_api_key_marker = start_api_key_marker or inherited_start_api_key_markerruntime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()+ # The group callback returns before its own clear once a subcommand is named, and+ # `unsloth run` is bound straight here, so this path has to do it itself or+ # llama-server and the backend start with the contradicting override (#7331).+ _clear_hsa_override_before_launch(silent = bool(silent))# Back-compat: --not-secure is a deprecated alias for --no-secure.secure = _resolve_secure(secure, not_secure)