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
Say ROCm does not cover RDNA 1 instead of advising a fix that cannot work (#8577)
Daniel Hand5a2160ef886
diff --git a/README.md b/README.mdindex ca78f126b68..c18d1fb72e4 100644--- a/README.md+++ b/README.md@@ -169,6 +169,10 @@ export UNSLOTH_LLAMA_CPP_BACKEND=vulkan # or cpu, cuda, rocm, autocurl -fsSL https://unsloth.ai/install.sh | sh```+On Linux and WSL this is the path for the AMD GPUs Unsloth has no ROCm PyTorch wheels for: Polaris (RX 470/480/570/580/590) and RDNA 1 (RX 5500/5600/5700). torch stays on CPU there, so training and GPU inference are unavailable, but GGUF chat runs on the GPU through Vulkan. Not every pre-RDNA 2 card is in this group: Vega 20 (Radeon VII, MI50, `gfx906`) keeps a ROCm PyTorch path and the installer routes it there. The older `UNSLOTH_FORCE_VULKAN=1` still works and is read when `UNSLOTH_LLAMA_CPP_BACKEND` is unset.++macOS has no Vulkan llama.cpp bundle and does not need one: the installer always uses the Metal build, which covers Apple Silicon and the AMD GPUs in Intel Macs, and it says so and carries on if the variable is set.+#### Windows:```powershellirm https://unsloth.ai/install.ps1 | iexdiff --git a/install.ps1 b/install.ps1index a54bcd579ea..6bf22983e1b 100644--- a/install.ps1+++ b/install.ps1@@ -3158,6 +3158,9 @@ exit 0$ROCmGpuLabel = $null$ROCmVersion = $null$ROCmGfxArch = $null+ # Declared with its neighbours, not inside the block below: the arms that read+ # it are outside that gate, so an NVIDIA host would leave it undefined.+ $ROCmUnsupportedGfxArch = $nullif (-not $HasNvidiaSmi) {# hipinfo: PATH first, then HIP_PATH/ROCM_PATH bin fallback (mirrors NVIDIA smi path resolution).# AMD HIP SDK sets HIP_PATH but may not add the bin dir to PATH depending on install type.@@ -3309,7 +3312,13 @@ exit 0} catch {}}}- if (-not $HasROCm) {+ # Set outside the scan: only the WMI arm fills it, but the lookup further down reads+ # it on every AMD path, including the amd-smi ones that never enter the block.+ $wmiAmdNames = @()+ # Keyed on the ARCH, not on $HasROCm: amd-smi can report GPUs with no gfx token and+ # only the first market name, which sets $HasROCm and used to skip this scan, leaving+ # the peer guard below blind. A host with an arch never reaches that lookup anyway.+ if (-not $ROCmGfxArch) {try {# ConfigManagerErrorCode 0 is "working properly". Filter on it exactly as# setup.ps1's scan does: taking a card setup discards names an arch for a GPU@@ -3319,14 +3328,39 @@ exit 0# If the filter leaves none, keep the full list: code 45 ("not connected") is# routine on a muxless laptop with a parked dGPU, and there is no healthy peer# to prefer. @() wraps the WHOLE if so a one-element branch stays indexable.- $amdAdapters = @(Get-WmiObject Win32_VideoController -ErrorAction SilentlyContinue |+ # CIM, as everywhere else here: Get-WmiObject is gone from PowerShell 7, where+ # the catch below would swallow it and leave the peer list empty. CIM is 5.1+.+ $amdAdapters = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue |Where-Object { $_.Name -match "AMD|Radeon" })$healthyAdapters = @($amdAdapters | Where-Object {($null -eq $_.ConfigManagerErrorCode) -or ($_.ConfigManagerErrorCode -eq 0) })- $wmiGpu = @(if ($healthyAdapters.Count -gt 0) { $healthyAdapters } else { $amdAdapters })[0]- if ($wmiGpu) { $ROCmGpuLabel = $wmiGpu.Name }+ $wmiAdapters = @(if ($healthyAdapters.Count -gt 0) { $healthyAdapters } else { $amdAdapters })+ $wmiGpu = $wmiAdapters[0]+ if ($wmiGpu) {+ # amd-smi's label wins when it had one; this scan is here for the peers.+ if (-not $HasROCm) { $ROCmGpuLabel = $wmiGpu.Name }+ # Every adapter's name, not just the chosen one: only the peer list tells+ # "this host has no ROCm-capable GPU" apart from "this host's FIRST adapter+ # is not the ROCm-capable one". Read by the unsupported lookup below;+ # nothing here picks an arch, so the choice above is untouched.+ $wmiAmdNames = @($wmiAdapters | ForEach-Object { $_.Name })+ }} catch {}}+ # GPU name -> gfx arch for AMD generations Unsloth's ROCm wheels do NOT cover:+ # RDNA 1 and Polaris 10/20/30 (unslothai#8529). Kept apart from $nameArchTable on+ # purpose: it only WORDS a message, never selects a wheel index. AMD's TheRock+ # ships RDNA 1 wheels, but not on the repo.amd.com indexes routed here, and never+ # gfx803. The (?!0) guards stop "RX 570" swallowing an "RX 5700". Names from+ # LLVM's AMDGPU tables plus libdrm amdgpu.ids/pci.ids for the Navi 10/14+ # professional parts LLVM omits; nothing is guessed, so Polaris 11/12 (RX+ # 460/550/560, a different die) is left out.+ $unsupportedNameArchTable = @(+ @{ P = "Radeon Pro V520|Radeon Pro 5600M"; A = "gfx1011" } # RDNA 1+ @{ P = "RX 5700|RX 5600|Radeon Pro 5600 XT|Radeon Pro 5700|Radeon Pro W5700"; A = "gfx1010" } # RDNA 1 (Navi 10)+ @{ P = "RX 5500|RX 5300|Radeon Pro W5500|Radeon Pro W5300"; A = "gfx1012" } # RDNA 1 (Navi 14)+ @{ P = "RX 4[78]0(?!0)|RX 5[789]0(?!0)|Radeon Pro WX 7100|Radeon Pro WX 5100"; A = "gfx803" } # Polaris 10/20/30+ )# ── Arch resolution: env-var override → name inference ──────────────# Runs even when the probe can't confirm a runtime ($HasROCm false): the# WMI-name gfx arch drives both ROCm llama.cpp and torch. repo.amd.com@@ -3366,6 +3400,32 @@ exit 0break}}+ # 3. Still nothing: the card may be a generation ROCm never covered rather+ # than one we failed to recognise (unslothai#8529). Reporting only --+ # $ROCmGfxArch stays null, so CPU fallback is reached by the same path.+ # Gated on NO adapter being covered: $wmiGpu takes index 0, so on a host+ # pairing an RX 5700 with an RX 7900 the label is the 5700 and the "no+ # SDK or override can help" wording below would be false (masking to the+ # 7900 and setting gfx1100 installs). Such a host keeps the arch-unknown+ # arm, which says exactly that. studio/setup.ps1 already scores every+ # adapter before it reaches its own lookup.+ if (-not $ROCmGfxArch) {+ $coveredPeer = $false+ foreach ($peerName in $wmiAmdNames) {+ foreach ($row in $nameArchTable) {+ if ($peerName -match $row.P) { $coveredPeer = $true; break }+ }+ if ($coveredPeer) { break }+ }+ if (-not $coveredPeer) {+ foreach ($row in $unsupportedNameArchTable) {+ if ($ROCmGpuLabel -match $row.P) {+ $ROCmUnsupportedGfxArch = $row.A+ break+ }+ }+ }+ }}}# Capture ROCm version for wheel selection (hipconfig, then amd-smi).@@ -3647,13 +3707,19 @@ exit 0step "gpu" "Intel GPU detected" "Green"substep "$IntelGpuLabel"# The reroute below prints the index: only it knows the mirror URL and any pin.- } elseif ($HasROCm) {+ } elseif ($HasROCm -and -not $ROCmUnsupportedGfxArch) {+ # Guarded like the HIP SDK arm below: amd-smi can report a GPU with no gfx token+ # and only a market name, setting $HasROCm without an arch. Calling that card+ # "AMD ROCm" contradicts the wheel note this run also prints.step "gpu" $ROCmGpuLabel$hipSdkPath = if ($env:HIP_PATH) { $env:HIP_PATH } elseif ($env:ROCM_PATH) { $env:ROCM_PATH } else { "on system PATH" }substep "HIP SDK: $hipSdkPath"if ($ROCmVersionFull) { substep "hipconfig: $ROCmVersionFull" }- } elseif ($HipSdkInstalled -and $ROCmGpuLabel) {- # HIP SDK is installed but ROCm can't see the device (driver issue, not SDK issue)+ } elseif ($HipSdkInstalled -and $ROCmGpuLabel -and -not $ROCmUnsupportedGfxArch) {+ # HIP SDK installed but ROCm can't see the device (driver issue, not SDK issue).+ # Excludes cards already known to be out of scope: the #8529 reporters installed+ # the HIP SDK BECAUSE this arm said to, so unguarded it hides the arm below from+ # exactly the users it is for.$sdkVer = if ($ROCmVersionFull) { " (HIP $ROCmVersionFull)" } else { "" }step "gpu" "AMD GPU detected -- not ROCm-accessible$sdkVer" "Yellow"substep "Detected: $ROCmGpuLabel" "Yellow"@@ -3667,6 +3733,38 @@ exit 0step "gpu" "AMD ROCm ($ROCmGfxArch)" "Cyan"substep "Detected: $ROCmGpuLabel" "Cyan"substep "GPU PyTorch uses AMD's bundled-runtime ROCm wheels -- HIP SDK not required (optional)." "Cyan"+ } elseif ($ROCmUnsupportedGfxArch) {+ # Detected, identified, out of scope for ROCm PyTorch. Ranks above the "arch+ # unknown" arm below: the arch is known here, and that arm's advice cannot+ # succeed on this GPU (unslothai#8529).+ # Not "training runs on CPU": with no CUDA/XPU visible, unsloth raises+ # NotImplementedError at import (unsloth/device_type.py). The Vulkan setter is+ # single-quoted so PowerShell prints $env:... rather than expanding it; a pasted+ # VAR=value resolves as a command name here and sets nothing.+ # Both claims below are conditional: an explicit index pin reaches the ROCm install+ # path further down even for an arch Unsloth has no wheels for, and studio/setup.ps1+ # THROWS on the Vulkan variable on Windows ARM64, where no bundle is published.+ $unsupPinned = (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_URL)) -or `+ (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_FAMILY))+ $unsupArm64 = (Get-HostMachineArch) -eq "arm64"+ step "gpu" "AMD GPU detected ($ROCmUnsupportedGfxArch) -- no ROCm PyTorch wheels Unsloth installs" "Yellow"+ substep "Detected: $ROCmGpuLabel" "Yellow"+ if ($unsupPinned) {+ substep "Unsloth ships no ROCm PyTorch wheels for $ROCmUnsupportedGfxArch, but the torch index" "Yellow"+ substep "you pinned is used as given, so torch is whatever that index publishes." "Yellow"+ } else {+ substep "Unsloth installs no ROCm PyTorch wheels for $ROCmUnsupportedGfxArch, so torch stays" "Yellow"+ substep "CPU-only: Unsloth training and GPU inference are unavailable. Installing the" "Yellow"+ substep "HIP SDK or setting UNSLOTH_ROCM_GFX_ARCH will not change that for it." "Yellow"+ }+ if ($unsupArm64) {+ substep "GGUF chat would need Vulkan on this GPU, and no Windows ARM64 Vulkan bundle is published: build llama.cpp from source, or run this on x64." "Yellow"+ } else {+ substep "GGUF chat can still use this GPU through Vulkan: set" "Yellow"+ substep '$env:UNSLOTH_LLAMA_CPP_BACKEND = "vulkan" and re-run this installer. It' "Yellow"+ substep "selects the llama.cpp bundle at install time, so setting it afterwards has" "Yellow"+ substep "no effect until you install or update again." "Yellow"+ }} elseif ($ROCmGpuLabel) {step "gpu" "AMD GPU detected -- arch unknown" "Yellow"substep "Detected: $ROCmGpuLabel" "Yellow"@@ -4095,6 +4193,8 @@ exit 0}} elseif ($ROCmGfxArch) {substep "AMD GPU ($ROCmGfxArch) not in supported arch list -- falling back to CPU-only PyTorch" "Yellow"+ } elseif ($ROCmUnsupportedGfxArch) {+ substep "AMD GPU ($ROCmUnsupportedGfxArch) has no ROCm PyTorch wheels Unsloth installs -- falling back to CPU-only PyTorch" "Yellow"} else {substep "AMD GPU detected but arch unknown -- falling back to CPU-only PyTorch" "Yellow"}@@ -4143,8 +4243,24 @@ exit 0substep "Installing CPU PyTorch -- no ROCm PyTorch wheels are available for $ROCmGfxArch." "Yellow"substep "PyTorch (training and Transformers inference) runs on CPU on this GPU." "Yellow"} else {- if ($HipSdkInstalled -and -not $HasROCm) {+ if ($HipSdkInstalled -and -not $HasROCm -and -not $ROCmUnsupportedGfxArch) {+ # Guarded like the gpu step above: an installed HIP SDK is the SYMPTOM on+ # these cards, so it must not outrank the arm saying why it cannot help.substep "Installing CPU-only PyTorch (HIP SDK found but GPU not ROCm-accessible)." "Yellow"+ } elseif ($ROCmUnsupportedGfxArch) {+ # Same words as the $ROCmGfxArch arm above, for a card whose arch we know+ # from its name rather than from a probe (unslothai#8529).+ substep "Installing CPU PyTorch -- Unsloth has no ROCm PyTorch wheels for $ROCmUnsupportedGfxArch." "Yellow"+ substep "Unsloth training and GPU inference are unavailable on CPU torch." "Yellow"+ substep "Neither the HIP SDK nor UNSLOTH_ROCM_GFX_ARCH can give this GPU ROCm." "Yellow"+ if ((Get-HostMachineArch) -eq "arm64") {+ # No Windows ARM64 Vulkan bundle exists, and studio/setup.ps1 throws on the+ # variable, so the usual advice would abort the next update instead of helping.+ substep "GGUF chat would need Vulkan here, and no Windows ARM64 Vulkan bundle is published: build llama.cpp from source, or run this on x64." "Yellow"+ } else {+ substep 'For GPU GGUF chat through Vulkan, set $env:UNSLOTH_LLAMA_CPP_BACKEND = "vulkan"' "Yellow"+ substep "and re-run this installer; the bundle is chosen at install time, not at launch." "Yellow"+ }} elseif ($ROCmGpuLabel) {substep "Installing CPU-only PyTorch (AMD GPU arch unknown -- install the HIP SDK" "Yellow"substep "or set UNSLOTH_ROCM_GFX_ARCH to enable GPU ROCm)." "Yellow"diff --git a/install.sh b/install.shindex da6216a4bbb..a35328b778d 100755--- a/install.sh+++ b/install.sh@@ -2882,6 +2882,43 @@ _infer_amd_gfx_arch_from_gpu_name() {esac}+# GPU name -> gfx arch for AMD generations Unsloth's ROCm wheels do NOT cover: RDNA 1+# and Polaris 10/20/30 (unslothai#8529). SEPARATE from _infer_amd_gfx_arch_from_gpu_name+# on purpose: messaging only, nothing here may route to a wheel index. AMD's TheRock+# ships RDNA 1 wheels, but not on the repo.amd.com indexes routed here, and never gfx803.+# ORDER IS LOAD-BEARING: `case` has no negative lookahead, so a *"RX 570"* arm would+# swallow an "RX 5700 XT" -- RDNA 1 arms come FIRST and Polaris last.+# Names from LLVM's AMDGPU tables plus libdrm amdgpu.ids/pci.ids for the Navi 10/14+# professional parts LLVM omits; nothing is guessed, so Polaris 11/12 (RX 460/550/560,+# a different die) is left out. Case-sensitive, unlike the regex copies: every source+# here (WMI, amd-smi, lspci) spells these names as pci.ids does.+_infer_unsupported_amd_gfx_arch_from_gpu_name() {+ case "$1" in+ *"Radeon Pro V520"*|*"Radeon Pro 5600M"*) echo gfx1011 ;; # RDNA 1+ *"RX 5700"*|*"RX 5600"*|*"Radeon Pro 5600 XT"*|*"Radeon Pro 5700"*|*"Radeon Pro W5700"*) echo gfx1010 ;; # RDNA 1 (Navi 10)+ *"RX 5500"*|*"RX 5300"*|*"Radeon Pro W5500"*|*"Radeon Pro W5300"*) echo gfx1012 ;; # RDNA 1 (Navi 14)+ *"RX 470"*|*"RX 480"*|*"RX 570"*|*"RX 580"*|*"RX 590"*|*"Radeon Pro WX 7100"*|*"Radeon Pro WX 5100"*) echo gfx803 ;; # Polaris 10/20/30+ *) return 1 ;;+ esac+}++# Linux counterpart: first AMD display-class lspci line naming a generation ROCm+# does not cover. Messaging only -- never feed the result into index selection.+_infer_linux_unsupported_amd_gfx_arch() {+ command -v lspci >/dev/null 2>&1 || return 1+ _unsup_disp=$(lspci -nn 2>/dev/null | grep -E 'VGA compatible controller|3D controller|Display controller' | grep -E 'AMD|ATI' || true)+ while IFS= read -r _unsup_ln; do+ [ -n "$_unsup_ln" ] || continue+ if _unsup_gfx=$(_infer_unsupported_amd_gfx_arch_from_gpu_name "$_unsup_ln"); then+ echo "$_unsup_gfx"+ return 0+ fi+ done <<EOF+$_unsup_disp+EOF+ return 1+}+# Best-effort gfx inference when ROCm tools can't see the GPU (unslothai#7301).# Mirrors install.ps1 arch resolution on Windows ($HasROCm false, $ROCmGfxArch set)._infer_linux_amd_gfx_arch() {@@ -3331,6 +3368,18 @@ get_torch_index_url() {echo "[WARN] AMD GPU detected but rocminfo/amd-smi can't read its gfx arch -- inferring $_amd_inferred_gfx from hardware IDs." >&2echo "$_base/cpu"; returnfi+ # Repairing rocminfo cannot help here: the arch would read fine and still+ # have no wheels (unslothai#8529). Advice only, same CPU index either way.+ if _amd_unsup_gfx=$(_infer_linux_unsupported_amd_gfx_arch 2>/dev/null); then+ # Scoped to the card named, never to the host: a second AMD GPU here+ # may well have wheels, and nothing has looked at it yet.+ echo "[WARN] AMD GPU detected ($_amd_unsup_gfx) -- Unsloth has no ROCm PyTorch wheels for that arch, installing CPU PyTorch." >&2+ echo "[WARN] This is expected on this GPU; repairing rocminfo/amd-smi or setting UNSLOTH_ROCM_GFX_ARCH will not give it ROCm PyTorch." >&2+ # Torch ends here, llama.cpp does not. `export` is load-bearing: a bare+ # assignment never reaches the re-run (the unslothai#8458 mistake).+ echo "[INFO] GGUF chat can still use this GPU through Vulkan: export UNSLOTH_LLAMA_CPP_BACKEND=vulkan and re-run this installer (it selects the llama.cpp bundle at install time)." >&2+ echo "$_base/cpu"; return+ fiecho "[WARN] AMD GPU detected but its gfx arch can't be read (rocminfo/amd-smi missing or not enumerating the GPU) -- installing CPU-only PyTorch." >&2echo "[WARN] For GPU PyTorch, install or repair rocminfo/amd-smi (e.g. sudo pacman -S rocm-hip-sdk) and re-run this installer." >&2echo "$_base/cpu"; return@@ -4446,8 +4495,29 @@ case "$TORCH_INDEX_URL" in# skip the SDK guidance (ROCm may be perfectly healthy here).substep "CPU-only PyTorch (index pinned via UNSLOTH_TORCH_INDEX_URL / _FAMILY)."elif _has_amd_rocm_gpu; then- substep "AMD GPU detected, but no usable ROCm/HIP install -- installing CPU-only PyTorch." "$C_WARN"- substep "Install the ROCm/HIP SDK and re-run this installer for GPU PyTorch." "$C_WARN"+ # A generation ROCm never covered is not a missing SDK (unslothai#8529).+ # Unlike the arm in get_torch_index_url, this one runs even when the arch+ # read fine, so it needs its own peer guard: an RX 5700 beside an RX 7900+ # lands here whenever the 7900's ROCm is too old, and blaming the 5700+ # would replace the upgrade advice with advice that is false for the card+ # that caused the fallback. _infer_linux_amd_gfx_arch scans every display+ # adapter, so a covered answer clears this one.+ _covered_disp_gfx=$(_infer_linux_amd_gfx_arch 2>/dev/null) || _covered_disp_gfx=""+ if [ -n "$_covered_disp_gfx" ] && _amd_arch_index_family_for_gfx "$_covered_disp_gfx" >/dev/null 2>&1; then+ _unsup_disp_gfx=""+ else+ _unsup_disp_gfx=$(_infer_linux_unsupported_amd_gfx_arch 2>/dev/null) || _unsup_disp_gfx=""+ fi+ if [ -n "$_unsup_disp_gfx" ]; then+ # Scoped to the card, as above: the SDK may still help another one.+ substep "AMD GPU detected ($_unsup_disp_gfx) -- Unsloth has no ROCm PyTorch wheels for that arch, installing CPU PyTorch." "$C_WARN"+ substep "Installing the ROCm/HIP SDK will not give this GPU ROCm PyTorch." "$C_WARN"+ substep "GGUF chat can still use this GPU through Vulkan: export UNSLOTH_LLAMA_CPP_BACKEND=vulkan and re-run this installer." "$C_WARN"+ substep "That variable selects the llama.cpp bundle at install time, so setting it afterwards has no effect until you install or update again." "$C_WARN"+ else+ substep "AMD GPU detected, but no usable ROCm/HIP install -- installing CPU-only PyTorch." "$C_WARN"+ substep "Install the ROCm/HIP SDK and re-run this installer for GPU PyTorch." "$C_WARN"+ fielsesubstep "No GPU detected -- installing CPU-only PyTorch." "$C_WARN"fidiff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex a80133c1d9c..d37847cdc55 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -63,6 +63,23 @@ PLATFORM_LACKS_TORCHCODEC_WHEEL = (or IS_MAC_INTEL)++def _is_windows_arm64() -> bool:+ """Windows on ARM, machine arch rather than process arch: platform.machine() reports+ AMD64 under an emulated x64 Python, and PROCESSOR_ARCHITEW6432 is ARM64 in exactly+ that case. Mirrors Get-HostMachineArch in install.ps1 / setup.ps1."""+ if not IS_WINDOWS:+ return False+ return any(+ (value or "").strip().lower() in {"arm64", "aarch64"}+ for value in (+ os.environ.get("PROCESSOR_ARCHITEW6432"),+ os.environ.get("PROCESSOR_ARCHITECTURE"),+ platform.machine(),+ )+ )++# ── ROCm / AMD GPU support ─────────────────────────────────────────────────────# Detected ROCm (major, minor) -> best PyTorch wheel tag on# download.pytorch.org. Checked newest-first (>=).@@ -964,11 +981,52 @@ def _detect_windows_gfx_arch() -> str | None:return _pickif _names and not _pick:# No arch means CPU-only torch; name the adapter instead of failing silently.- _safe_print(- f" [WARN] could not map '{_names[_sel]}' to a gfx arch, so torch "- f"will be CPU-only. Set UNSLOTH_ROCM_GFX_ARCH to your GPU's arch "- f"(e.g. gfx1200) to install AMD wheels."- )+ # RDNA 1 / Polaris is not an unknown card: naming an override there+ # sends the user after a fix that does not exist (#8529, #8458).+ _unsupported = _unsupported_gfx_arch_from_gpu_name(_names[_sel])+ if _unsupported:+ # The CPU-only half is false under an explicit index pin, which is+ # honoured for any arch, so a pinned run says what it is doing instead.+ _pinned = bool(+ (os.environ.get("UNSLOTH_TORCH_INDEX_URL") or "").strip()+ or (os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY") or "").strip()+ )+ _tail = (+ "so the torch index you pinned is used as given."+ if _pinned+ else (+ "so torch will be CPU-only. No HIP SDK install and "+ "no UNSLOTH_ROCM_GFX_ARCH value changes that on this GPU."+ )+ )+ _safe_print(+ f" [WARN] '{_names[_sel]}' is {_unsupported}, which Unsloth's ROCm "+ f"PyTorch wheels do not cover, {_tail}"+ )+ # Torch ends here, llama.cpp does not: Vulkan drives these cards+ # (#8458 ran an RX 580 through it). PowerShell syntax because this+ # branch is Windows-only: a pasted VAR=value parses there as a+ # command name and sets nothing. Not on ARM64: setup.ps1 THROWS on+ # that variable there, so this would abort the next update.+ if _is_windows_arm64():+ _safe_print(+ " [INFO] GGUF chat would need Vulkan on this GPU, and no "+ "Windows ARM64 Vulkan bundle is published: build llama.cpp "+ "from source, or run this on x64."+ )+ else:+ _safe_print(+ " [INFO] GGUF chat can still run on this GPU through Vulkan: set "+ '$env:UNSLOTH_LLAMA_CPP_BACKEND = "vulkan" and re-run the installer. '+ "It selects the llama.cpp bundle at install time, so setting it "+ "afterwards has no effect until you install or update again."+ )+ else:+ _safe_print(+ f" [WARN] could not map '{_names[_sel]}' to a gfx arch, so torch "+ f"will be CPU-only. Set UNSLOTH_ROCM_GFX_ARCH to your GPU's arch "+ f"(e.g. gfx1200) to install AMD wheels."+ )except Exception:passreturn None@@ -1012,6 +1070,41 @@ def _gfx_arch_from_gpu_name(name: str) -> "str | None":return None+# GPU name -> gfx arch for AMD generations Unsloth's ROCm wheels do NOT cover: RDNA 1+# and Polaris 10/20/30 (unslothai#8529, #8458). Deliberately SEPARATE from+# _WIN_GPU_NAME_ARCH_TABLE: nothing here may ever route to a wheel index. AMD's TheRock+# ships RDNA 1 wheels, but not on the repo.amd.com indexes routed here, and never gfx803.+# Every (?!0) guard stops "RX 570" swallowing "RX 5700", so each row is correct on its+# own regardless of order. Names from LLVM's AMDGPU tables plus libdrm amdgpu.ids/pci.ids+# for the Navi 10/14 professional parts LLVM omits; nothing is guessed, so Polaris 11/12+# (RX 460/550/560, a different die) is left out.+_UNSUPPORTED_GPU_NAME_ARCH_TABLE: "list[tuple[str, str]]" = [+ (r"Radeon Pro V520|Radeon Pro 5600M", "gfx1011"), # RDNA 1+ (+ r"RX 5700|RX 5600|Radeon Pro 5600 XT|Radeon Pro 5700|Radeon Pro W5700",+ "gfx1010",+ ), # RDNA 1 (Navi 10)+ (r"RX 5500|RX 5300|Radeon Pro W5500|Radeon Pro W5300", "gfx1012"), # RDNA 1 (Navi 14)+ (+ r"RX 4[78]0(?!0)|RX 5[789]0(?!0)|Radeon Pro WX 7100|Radeon Pro WX 5100",+ "gfx803",+ ), # Polaris 10/20/30+]+++def _unsupported_gfx_arch_from_gpu_name(name: str) -> "str | None":+ """Name the gfx arch of a GPU whose generation Unsloth has no ROCm wheels for.++ Messaging only. Callers must not feed the result into index selection.+ """+ if not name:+ return None+ for _pat, _arch in _UNSUPPORTED_GPU_NAME_ARCH_TABLE:+ if re.search(_pat, name, re.IGNORECASE):+ return _arch+ return None++def _linux_amd_gfx_from_cpuinfo() -> "str | None":"""Infer gfx arch from /proc/cpuinfo on integrated AMD APUs (Strix Halo/Point)."""try:diff --git a/studio/setup.ps1 b/studio/setup.ps1index 357a538c3b9..f5609816a8e 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -2085,6 +2085,10 @@ $HipSdkInstalled = $false # HIP SDK binary found (independent of device access$ROCmGpuLabel = $null$script:ROCmGpuLabels = @() # every AMD adapter name WMI reported (shadowing-aware inference)$script:ROCmGfxArch = $null+# Beside ROCmGfxArch, NOT inside the `-not $HasNvidiaSmi` block below: the ROCm summary+# reads this unconditionally, so an NVIDIA host would hit an undefined variable under a+# caller's Set-StrictMode. Assigning here also clears a stale value on a re-invocation.+$script:ROCmUnsupportedGfxArch = $null# APU gfx arches whose board commonly also carries a discrete Radeon. HIP often# enumerates the APU first, so an index-0 pick reads the iGPU's arch and the dGPU never# gets its wheels (#7776: gfx1036 Raphael shadowing a gfx1200 RX 9060 XT). In sync with@@ -2373,7 +2377,10 @@ if (-not $HasNvidiaSmi) {# $HasROCm is intentionally NOT set here — we cannot confirm ROCm runtime# support without hipinfo or amd-smi. The name is saved to $ROCmGpuLabel# so the name-based inference below can still attempt an arch lookup.- if (-not $HasROCm) {+ # Gated on the ARCH, like install.ps1: amd-smi can set $HasROCm with no arch, and gated+ # that way the scan was skipped, so $script:ROCmGpuLabels held one name and the inference+ # below judged a whole multi-GPU host on it. Same condition as that inference.+ if (-not $script:ROCmGfxArch) {try {# Keep every AMD adapter, not just the first: WMI orders controllers as the# driver stack enumerated them, so a shadowing iGPU can lead here exactly as@@ -2397,10 +2404,26 @@ if (-not $HasNvidiaSmi) {$wmiGpus = @(if ($healthyGpus.Count -gt 0) { $healthyGpus } else { $amdGpus })if ($wmiGpus.Count -gt 0) {$script:ROCmGpuLabels = @($wmiGpus | ForEach-Object { $_.Name })- $ROCmGpuLabel = $script:ROCmGpuLabels[0]+ # amd-smi's label wins when it had one; this scan is here for the peers.+ if (-not $HasROCm) { $ROCmGpuLabel = $script:ROCmGpuLabels[0] }}} catch {}}+ # GPU name -> gfx arch for AMD generations Unsloth's ROCm wheels do NOT cover: RDNA 1+ # and Polaris 10/20/30 (unslothai#8529). Kept apart from $nameArchTable on purpose: it+ # only WORDS a message, never selects a wheel index or a prebuilt. AMD's TheRock ships+ # RDNA 1 wheels, but not on the repo.amd.com indexes routed here, and never gfx803.+ # The (?!0) guards stop "RX 570" swallowing an "RX 5700". Names from LLVM's AMDGPU+ # tables plus libdrm amdgpu.ids/pci.ids for the Navi 10/14 professional parts LLVM+ # omits; nothing is guessed, so Polaris 11/12 (RX 460/550/560, a different die) is+ # left out.+ $unsupportedNameArchTable = @(+ @{ P = "Radeon Pro V520|Radeon Pro 5600M"; A = "gfx1011" } # RDNA 1+ @{ P = "RX 5700|RX 5600|Radeon Pro 5600 XT|Radeon Pro 5700|Radeon Pro W5700"; A = "gfx1010" } # RDNA 1 (Navi 10)+ @{ P = "RX 5500|RX 5300|Radeon Pro W5500|Radeon Pro W5300"; A = "gfx1012" } # RDNA 1 (Navi 14)+ @{ P = "RX 4[78]0(?!0)|RX 5[789]0(?!0)|Radeon Pro WX 7100|Radeon Pro WX 5100"; A = "gfx803" } # Polaris 10/20/30+ )+ $script:ROCmUnsupportedGfxArch = $null# ── Arch resolution: env-var override → name inference ──────────────────# Runs after all probes, even when none confirmed a ROCm runtime ($HasROCm false):# the Adrenalin driver alone runs the per-gfx ROCm llama.cpp prebuilt (bundles its@@ -2471,6 +2494,11 @@ if (-not $HasNvidiaSmi) {$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"substep "gfx arch inferred from GPU name: $script:ROCmGfxArch" "Cyan"substep "Tip: set UNSLOTH_ROCM_GFX_ARCH=$script:ROCmGfxArch to skip inference next time" "Cyan"+ } else {+ # Nothing mapped: the card may be a generation ROCm never covered rather+ # than one we failed to recognise (unslothai#8529). $script:ROCmGfxArch+ # stays null either way, so only the wording of the report below moves.+ $script:ROCmUnsupportedGfxArch = Get-GfxArchFromGpuName -Name $gpuNames[$nameIdx] -Table $unsupportedNameArchTable}}}@@ -2615,13 +2643,17 @@ if ($HasNvidiaSmi) {substep "$IntelGpuLabel"substep "PyTorch XPU (SYCL) wheels provide training and GPU inference on this GPU." "Cyan"Write-StudioLine ""-} elseif ($HasROCm) {+} elseif ($HasROCm -and -not $script:ROCmUnsupportedGfxArch) {+ # Guarded like the HIP SDK arm below: amd-smi can report a GPU with no gfx token+ # and only a market name, which sets $HasROCm without an arch.step "gpu" $ROCmGpuLabel$hipSdkPath = if ($env:HIP_PATH) { $env:HIP_PATH } elseif ($env:ROCM_PATH) { $env:ROCM_PATH } else { "on system PATH" }substep "HIP SDK: $hipSdkPath"if ($script:ROCmVersionFull) { substep "hipconfig: $script:ROCmVersionFull" }-} elseif ($HipSdkInstalled -and $ROCmGpuLabel) {- # HIP SDK is installed but ROCm can't see the device (driver issue, not SDK issue)+} elseif ($HipSdkInstalled -and $ROCmGpuLabel -and -not $script:ROCmUnsupportedGfxArch) {+ # HIP SDK installed but ROCm can't see the device (driver issue, not SDK issue).+ # Excludes cards already known to be out of scope: the #8529 reporters installed the+ # HIP SDK BECAUSE this arm said to, so unguarded it hides the arm below from them.$sdkVer = if ($script:ROCmVersionFull) { " (HIP $script:ROCmVersionFull)" } else { "" }Write-StudioLine ""step "gpu" "AMD GPU detected -- not ROCm-accessible$sdkVer" "Yellow"@@ -2638,6 +2670,39 @@ if ($HasNvidiaSmi) {substep "Detected: $ROCmGpuLabel" "Cyan"substep "GPU PyTorch uses AMD's bundled-runtime ROCm wheels -- HIP SDK not required (optional)." "Cyan"Write-StudioLine ""+} elseif ($script:ROCmUnsupportedGfxArch) {+ # Detected, identified, out of scope for ROCm PyTorch. Ranks above the "arch+ # unknown" arm below: the arch is known here, and that arm's advice cannot succeed+ # on this GPU (unslothai#8529).+ Write-StudioLine ""+ step "gpu" "AMD GPU detected ($script:ROCmUnsupportedGfxArch) -- no ROCm PyTorch wheels Unsloth installs" "Yellow"+ substep "Detected: $ROCmGpuLabel" "Yellow"+ # Not "training runs on CPU": with no CUDA/XPU visible, unsloth raises+ # NotImplementedError at import (unsloth/device_type.py). The Vulkan setter is+ # single-quoted so PowerShell prints $env:... rather than expanding it; a pasted+ # VAR=value resolves as a command name here and sets nothing.+ # Both claims are conditional: an explicit index pin is honoured for any arch, and+ # this same script THROWS on the Vulkan variable on Windows ARM64, where no bundle+ # is published, so the usual advice would abort the next update instead of helping.+ $unsupPinned = (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_URL)) -or `+ (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_FAMILY))+ if ($unsupPinned) {+ substep "Unsloth ships no ROCm PyTorch wheels for $script:ROCmUnsupportedGfxArch, but the torch" "Yellow"+ substep "index you pinned is used as given, so torch is whatever it publishes." "Yellow"+ } else {+ substep "Unsloth installs no ROCm PyTorch wheels for $script:ROCmUnsupportedGfxArch, so torch stays" "Yellow"+ substep "CPU-only: Unsloth training and GPU inference are unavailable. Installing the" "Yellow"+ substep "HIP SDK or setting UNSLOTH_ROCM_GFX_ARCH will not change that for it." "Yellow"+ }+ if ((Get-HostMachineArch) -eq "arm64") {+ substep "GGUF chat would need Vulkan on this GPU, and no Windows ARM64 Vulkan bundle is published: build llama.cpp from source, or run this on x64." "Yellow"+ } else {+ substep "GGUF chat can still use this GPU through Vulkan: set" "Yellow"+ substep '$env:UNSLOTH_LLAMA_CPP_BACKEND = "vulkan" and re-run the installer. It selects' "Yellow"+ substep "the llama.cpp bundle at install time, so setting it afterwards has no effect" "Yellow"+ substep "until you install or update again." "Yellow"+ }+ Write-StudioLine ""} elseif ($ROCmGpuLabel) {Write-StudioLine ""step "gpu" "AMD GPU detected -- arch unknown" "Yellow"@@ -3080,13 +3145,17 @@ $script:CudaArch = $CudaArch$script:CudaToolkitReady = $true}-if ($HasROCm) {+if ($HasROCm -and -not $script:ROCmUnsupportedGfxArch) {$rocmVerLabel = if ($script:ROCmVersionFull) { "ROCm $script:ROCmVersionFull" } elseif ($script:ROCmVersion) { "ROCm $script:ROCmVersion" } else { "ROCm (version unknown)" }step "rocm" $rocmVerLabel} elseif ($script:ROCmGfxArch) {# GPU training/inference works via AMD's bundled-runtime ROCm PyTorch wheels;# the HIP SDK is optional (only the system ROCm toolchain).step "rocm" "GPU via bundled ROCm wheels ($script:ROCmGfxArch) -- HIP SDK optional" "Cyan"+} elseif ($script:ROCmUnsupportedGfxArch) {+ # Naming the HIP SDK here would read as "install it and this resolves"; on a+ # generation with no ROCm PyTorch wheels it never does (unslothai#8529).+ step "rocm" "AMD GPU detected ($script:ROCmUnsupportedGfxArch) -- no ROCm PyTorch wheels Unsloth installs" "Yellow"} elseif ($ROCmGpuLabel) {step "rocm" "AMD GPU detected -- arch unknown; HIP SDK not found" "Yellow"}diff --git a/studio/setup.sh b/studio/setup.shindex 21a5d6c221f..fde43767916 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -1786,6 +1786,30 @@ if [ "$_setup_torch_is_xpu" = true ]; thenrun_quiet_no_exit "install bitsandbytes (xpu)" fast_install --no-deps "bitsandbytes>=0.50.0" || \substep "[WARN] could not install an XPU-capable bitsandbytes; 4-bit QLoRA may be unavailable."fi+# The supported name table, as a matcher so the report below can ask it about a PEER adapter+# without disturbing $_setup_gfx. Kept in sync with install.sh (and the PS nameArchTable).+# gfx1102 before gfx1100 so the spaceless "RX 7700S" lands on gfx1102 (case has no lookahead).+_setup_supported_gfx_from_name() {+ _sup_gfx_in="$1"+ _sup_gfx_out=""+ case "$_sup_gfx_in" in+ *9070*|*9080*|*"R9700"*) _sup_gfx_out="gfx1201" ;; # RDNA 4 (Navi 48: RX 9070 / 9080, Radeon AI PRO R9700)+ *9060*) _sup_gfx_out="gfx1200" ;; # RDNA 4 (Navi 44)+ *"8065S"*|*"8060S"*|*"8050S"*|*"8040S"*|*"Strix Halo"*|*"Ryzen AI Max"*|*"AI Max"*) _sup_gfx_out="gfx1151" ;; # RDNA 3.5 (Strix Halo + Gorgon Halo: Radeon 8065S/8060S/8050S/8040S iGPU, Ryzen AI Max / Max+)+ *"890M"*|*"880M"*|*"Strix Point"*|*"HX 37"*|*"AI 9 HX"*|*"AI 9 36"*) _sup_gfx_out="gfx1150" ;; # RDNA 3.5 (Strix Point: Radeon 890M/880M, Ryzen AI 9 HX 370/375)+ *"860M"*|*"840M"*|*"Krackan"*|*"AI 7 35"*|*"AI 5 34"*|*"AI 7 PRO 35"*|*"AI 5 33"*) _sup_gfx_out="gfx1152" ;; # RDNA 3.5 (Krackan Point: Radeon 860M/840M, Ryzen AI 7 350 / AI 5 340)+ *"RX 7600"*|*"RX 7700S"*|*"RX 7650"*|*"PRO W7600"*|*"PRO W7500"*) _sup_gfx_out="gfx1102" ;; # RDNA 3 (Navi 33)+ *"RX 7800"*|*"RX 7700"*|*"PRO W7700"*|*"PRO V710"*) _sup_gfx_out="gfx1101" ;; # RDNA 3 (Navi 32)+ *"RX 7900"*|*"PRO W7900"*|*"PRO W7800"*) _sup_gfx_out="gfx1100" ;; # RDNA 3 desktop / workstation (Navi 31)+ *"780M"*|*"760M"*|*"740M"*|*"Phoenix"*|*"Hawk Point"*|*"Z1 Extreme"*|*"Z2 Extreme"*) _sup_gfx_out="gfx1103" ;; # RDNA 3 iGPU (Phoenix / Hawk Point)+ *"RX 6900"*|*"RX 6800"*|*"RX 6750"*|*"RX 6700"*|*"PRO W6800"*|*"PRO W6900"*) _sup_gfx_out="gfx1030" ;; # RDNA 2 (Navi 21)+ *"RX 6650"*|*"RX 6600"*|*"PRO W6600"*|*"PRO W6650"*) _sup_gfx_out="gfx1032" ;; # RDNA 2 (Navi 23)+ *"RX 6500"*|*"RX 6400"*|*"RX 6300"*|*"PRO W6400"*|*"PRO W6500"*) _sup_gfx_out="gfx1034" ;; # RDNA 2 (Navi 24)+ esac+ [ -n "$_sup_gfx_out" ] || return 1+ printf '%s\n' "$_sup_gfx_out"+}+# NVIDIA priority: classify NVIDIA first and skip the AMD probes entirely on# a usable-NVIDIA host (mirrors _has_rocm_gpu in install_python_stack.py).# This also keeps a wedged rocminfo/amd-smi from hanging setup before the@@ -1814,8 +1838,9 @@ if [ "$_setup_nvidia_usable" != true ]; then# KFD sysfs fallback, AMD vendor_id 4098 only (mirrors install.sh# _has_amd_rocm_gpu): covers AMD hosts where rocminfo/amd-smi are# missing but the kernel exposes the GPU, so the source-build gate- # below does not drop them to a CPU llama.cpp build. No gfx arch is- # available from this path; name-based inference handles it.+ # below does not drop them to a CPU llama.cpp build. Neither a gfx arch+ # nor a marketing name is available from this path, so the report below+ # reads lspci rather than _setup_mkt when it needs to name the card._setup_amd_detected=truefifi@@ -1837,23 +1862,7 @@ elif [ "$_setup_amd_detected" = true ]; thensubstep "gfx arch from UNSLOTH_ROCM_GFX_ARCH env override: $_setup_gfx"# Name-based arch inference when tools don't report gfx (mirrors setup.ps1 nameArchTable)elif [ -z "$_setup_gfx" ] && [ -n "$_setup_mkt" ]; then- # Kept in sync with the table in install.sh (and the PS nameArchTable).- # gfx1102 matched BEFORE gfx1100 so the spaceless "RX 7700S" lands on- # gfx1102 (bash case has no negative lookahead like the PS tables).- case "$_setup_mkt" in- *9070*|*9080*|*"R9700"*) _setup_gfx="gfx1201" ;; # RDNA 4 (Navi 48: RX 9070 / 9080, Radeon AI PRO R9700)- *9060*) _setup_gfx="gfx1200" ;; # RDNA 4 (Navi 44)- *"8065S"*|*"8060S"*|*"8050S"*|*"8040S"*|*"Strix Halo"*|*"Ryzen AI Max"*|*"AI Max"*) _setup_gfx="gfx1151" ;; # RDNA 3.5 (Strix Halo + Gorgon Halo: Radeon 8065S/8060S/8050S/8040S iGPU, Ryzen AI Max / Max+)- *"890M"*|*"880M"*|*"Strix Point"*|*"HX 37"*|*"AI 9 HX"*|*"AI 9 36"*) _setup_gfx="gfx1150" ;; # RDNA 3.5 (Strix Point: Radeon 890M/880M, Ryzen AI 9 HX 370/375)- *"860M"*|*"840M"*|*"Krackan"*|*"AI 7 35"*|*"AI 5 34"*|*"AI 7 PRO 35"*|*"AI 5 33"*) _setup_gfx="gfx1152" ;; # RDNA 3.5 (Krackan Point: Radeon 860M/840M, Ryzen AI 7 350 / AI 5 340)- *"RX 7600"*|*"RX 7700S"*|*"RX 7650"*|*"PRO W7600"*|*"PRO W7500"*) _setup_gfx="gfx1102" ;; # RDNA 3 (Navi 33)- *"RX 7800"*|*"RX 7700"*|*"PRO W7700"*|*"PRO V710"*) _setup_gfx="gfx1101" ;; # RDNA 3 (Navi 32)- *"RX 7900"*|*"PRO W7900"*|*"PRO W7800"*) _setup_gfx="gfx1100" ;; # RDNA 3 desktop / workstation (Navi 31)- *"780M"*|*"760M"*|*"740M"*|*"Phoenix"*|*"Hawk Point"*|*"Z1 Extreme"*|*"Z2 Extreme"*) _setup_gfx="gfx1103" ;; # RDNA 3 iGPU (Phoenix / Hawk Point)- *"RX 6900"*|*"RX 6800"*|*"RX 6750"*|*"RX 6700"*|*"PRO W6800"*|*"PRO W6900"*) _setup_gfx="gfx1030" ;; # RDNA 2 (Navi 21)- *"RX 6650"*|*"RX 6600"*|*"PRO W6600"*|*"PRO W6650"*) _setup_gfx="gfx1032" ;; # RDNA 2 (Navi 23)- *"RX 6500"*|*"RX 6400"*|*"RX 6300"*|*"PRO W6400"*|*"PRO W6500"*) _setup_gfx="gfx1034" ;; # RDNA 2 (Navi 24)- esac+ _setup_gfx=$(_setup_supported_gfx_from_name "$_setup_mkt") || _setup_gfx=""if [ -n "$_setup_gfx" ]; thensubstep "gfx arch inferred from GPU name: $_setup_gfx"substep "Tip: set UNSLOTH_ROCM_GFX_ARCH=$_setup_gfx to skip inference next time"@@ -1868,8 +1877,88 @@ elif [ "$_setup_amd_detected" = true ]; then_setup_rocm_ver=$(amd-smi version 2>/dev/null | awk -F'ROCm version: ' \'NF>1{gsub(/[[:space:]]/,"", $2); print $2; exit}' || true)fi+ # GPU name -> gfx arch for AMD generations Unsloth's ROCm wheels do NOT cover: RDNA 1+ # and Polaris 10/20/30 (unslothai#8529). Kept apart from the inference table above on+ # purpose: it only words the report below, never selects a wheel index or prebuilt.+ # AMD's TheRock ships RDNA 1 wheels, but not on the repo.amd.com indexes routed here,+ # and never gfx803. Order is load-bearing: `case` has no negative lookahead, so the+ # RDNA 1 arms must precede Polaris or *"RX 570"* would swallow an "RX 5700 XT".+ # Names from LLVM's AMDGPU tables plus libdrm amdgpu.ids/pci.ids for the Navi 10/14+ # professional parts LLVM omits; nothing is guessed, so Polaris 11/12 is left out.+ # Case-sensitive, unlike the regex copies: every source here (WMI, amd-smi, lspci)+ # spells these names as pci.ids does.+ _setup_unsupported_gfx_from_name() {+ case "$1" in+ *"Radeon Pro V520"*|*"Radeon Pro 5600M"*) echo gfx1011 ;; # RDNA 1+ *"RX 5700"*|*"RX 5600"*|*"Radeon Pro 5600 XT"*|*"Radeon Pro 5700"*|*"Radeon Pro W5700"*) echo gfx1010 ;; # RDNA 1 (Navi 10)+ *"RX 5500"*|*"RX 5300"*|*"Radeon Pro W5500"*|*"Radeon Pro W5300"*) echo gfx1012 ;; # RDNA 1 (Navi 14)+ *"RX 470"*|*"RX 480"*|*"RX 570"*|*"RX 580"*|*"RX 590"*|*"Radeon Pro WX 7100"*|*"Radeon Pro WX 5100"*) echo gfx803 ;; # Polaris 10/20/30+ *) return 1 ;;+ esac+ }+ # The KFD sysfs fallback above detects the GPU with neither rocminfo nor amd-smi, so it+ # leaves _setup_mkt empty -- and a runtime-less host is precisely the one this report+ # exists for. lspci still names the card there, the source install.sh already reads.+ # Deliberately NOT written back into _setup_mkt: the supported table keys on it and+ # would start feeding --rocm-gfx to the prebuilt and whisper commands on the KFD path.+ _setup_unsupported_gfx_any() {+ # Peer guard FIRST, so it covers the named hit too: amd-smi reports one market name,+ # the first device's, so where an RX 5700 precedes an RX 7900 the name IS the 5700.+ # Only when lspci can answer: with no adapter list there is no peer to find, and+ # suppressing there would silence the single-card host this report exists for.+ _setup_unsup_pci=""+ if command -v lspci >/dev/null 2>&1; then+ _setup_unsup_pci=$(lspci -nn 2>/dev/null | grep -E 'VGA compatible controller|3D controller|Display controller' | grep -E 'AMD|ATI' || true)+ while IFS= read -r _setup_unsup_ln; do+ [ -n "$_setup_unsup_ln" ] || continue+ if _setup_supported_gfx_from_name "$_setup_unsup_ln" >/dev/null 2>&1; then+ return 1+ fi+ done <<EOF+$_setup_unsup_pci+EOF+ fi+ # Only on a HIT: a nonempty but unmapped name (a generic "AMD Radeon Graphics"+ # from rocminfo) used to end the lookup here, so the lspci scan below never ran+ # and the report fell through to the plain "AMD ROCm" line this change replaces.+ if [ -n "$1" ] && _setup_unsup_named=$(_setup_unsupported_gfx_from_name "$1"); then+ echo "$_setup_unsup_named"+ return 0+ fi+ [ -n "$_setup_unsup_pci" ] || return 1+ while IFS= read -r _setup_unsup_ln; do+ [ -n "$_setup_unsup_ln" ] || continue+ if _setup_unsup_hit=$(_setup_unsupported_gfx_from_name "$_setup_unsup_ln"); then+ echo "$_setup_unsup_hit"+ return 0+ fi+ done <<EOF+$_setup_unsup_pci+EOF+ return 1+ }if [ -n "$_setup_gfx" ]; thenstep "gpu" "AMD ROCm ($_setup_gfx)"+ elif _setup_unsup_gfx=$(_setup_unsupported_gfx_any "$_setup_mkt"); then+ step "gpu" "AMD GPU detected ($_setup_unsup_gfx) -- no ROCm PyTorch wheels Unsloth installs"+ # Not "training runs on CPU": with no CUDA/XPU visible, unsloth raises+ # NotImplementedError at import (unsloth/device_type.py).+ # Both lines are false under an explicit index pin, which install_python_stack.py+ # honours for any arch, so a pinned run says what it is doing instead.+ # Whitespace-trimmed, as get_torch_index_url trims them: a blank value is unset+ # there, so treating it as a pin would drop the CPU warning for nothing.+ # Distinct name: _setup_pin is the XPU block's, and these are globals in POSIX sh.+ _setup_unsup_pin="${UNSLOTH_TORCH_INDEX_URL:-}${UNSLOTH_TORCH_INDEX_FAMILY:-}"+ _setup_unsup_pin=$(printf '%s' "$_setup_unsup_pin" | tr -d '[:space:]')+ if [ -n "$_setup_unsup_pin" ]; then+ substep "The torch index you pinned is used as given, so torch is whatever it publishes."+ else+ substep "torch stays CPU-only: Unsloth training and GPU inference are unavailable."+ substep "No HIP SDK install and no UNSLOTH_ROCM_GFX_ARCH value gives this GPU one."+ fi+ substep "GGUF chat can still use this GPU through Vulkan: export UNSLOTH_LLAMA_CPP_BACKEND=vulkan,"+ substep "then re-run the installer. It picks the llama.cpp bundle at install time, so setting"+ substep "it afterwards has no effect until you install or update again."elsestep "gpu" "AMD ROCm"fidiff --git a/tests/studio/install/test_pr5940_followups.py b/tests/studio/install/test_pr5940_followups.pyindex dd2a7ec4870..53d3b49ecb0 100644--- a/tests/studio/install/test_pr5940_followups.py+++ b/tests/studio/install/test_pr5940_followups.py@@ -197,7 +197,7 @@ def test_setup_sh_name_arch_table_in_sync_with_install_sh():install_rows = _sh_name_arch_rows(_INSTALL_SH.read_text(encoding = "utf-8"))setup_rows = _sh_name_arch_rows((PACKAGE_ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8"),- var = "_setup_gfx",+ var = "_sup_gfx_out",)assert setup_rows, "no name->arch case table found in studio/setup.sh"assert install_rows == setup_rows, (diff --git a/tests/studio/install/test_rdna1_unsupported_message_8529.py b/tests/studio/install/test_rdna1_unsupported_message_8529.pynew file mode 100644index 00000000000..4c905cc02e5--- /dev/null+++ b/tests/studio/install/test_rdna1_unsupported_message_8529.py@@ -0,0 +1,1462 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What the installers SAY when an AMD GPU is detected and ROCm does not cover it.++Issue #8529: an RX 5700 XT (Navi 10, gfx1010, RDNA 1) on Windows correctly landed+on CPU torch, and the installer then told the reporter to install the HIP SDK or+set UNSLOTH_ROCM_GFX_ARCH "to enable GPU ROCm". Neither can work: AMD publishes+Windows torch indexes for gfx103X, gfx110X, gfx1150, gfx1151 and gfx120X only, so+UNSLOTH_ROCM_GFX_ARCH=gfx1010 lands on the unmapped-arch path and returns CPU+anyway, after an SDK install and a reboot spent for nothing.++The fixtures are shaped around that one card because it is the only confirmed+report. Adapter names are given as Windows WMI and Linux lspci actually spell+them ("AMD Radeon RX 5700 XT", "Navi 10 [Radeon RX 5600 OEM/5600 XT / 5700/5700+XT]"), not as tidy marketing strings, since the tables are matched against the+raw probe output. The supported-card fixtures (RX 9070 XT, RX 6800 XT) are here+to prove the new lookup cannot reach a card that has wheels, and the RTX 4090 to+prove it cannot reach a non-AMD one.++CPU fallback is the correct outcome on RDNA 1 and every test below re-asserts it:+this change is about wording, never about routing.+"""++import contextlib+import importlib.util+import io+import os+import re+import shutil+import subprocess+import sys+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+++PACKAGE_ROOT = Path(__file__).resolve().parents[3]++_INSTALL_SH = PACKAGE_ROOT / "install.sh"+_INSTALL_PS1 = PACKAGE_ROOT / "install.ps1"+_SETUP_SH = PACKAGE_ROOT / "studio" / "setup.sh"+_SETUP_PS1 = PACKAGE_ROOT / "studio" / "setup.ps1"+_STACK_PY = PACKAGE_ROOT / "studio" / "install_python_stack.py"++# The setter each source has to teach, in the syntax of the shell that reads it.+# PowerShell cannot parse a bare VAR=value: it resolves it as a command name, so a+# Windows user who pastes it sets nothing and gets the same CPU bundle -- the #8458+# failure mode, reintroduced by the fix for it. Two needles, not one: the bare form is+# what a PowerShell source must never print, and folding them together let a .ps1 emit+# it and still pass (an added-bare-setter mutant survived the whole file).+_POSIX_ASSIGNMENT = "UNSLOTH_LLAMA_CPP_BACKEND=vulkan"+# `export`, not a bare assignment: a POSIX assignment without it is a shell variable,+# invisible to the installer the next line tells the user to run, so they get the CPU+# bundle again and conclude the advice was wrong (the #8458 mistake). The README block+# has always used export; these messages have to agree with it.+_POSIX_SETTER = f"export {_POSIX_ASSIGNMENT}"+_PWSH_SETTER = '$env:UNSLOTH_LLAMA_CPP_BACKEND = "vulkan"'+_SETTER = {+ "install.sh": _POSIX_SETTER,+ "setup.sh": _POSIX_SETTER,+ "install.ps1": _PWSH_SETTER,+ "setup.ps1": _PWSH_SETTER,+ "install_python_stack.py": _PWSH_SETTER, # _detect_windows_gfx_arch is Windows-only+}+++def _load_stack_module():+ spec = importlib.util.spec_from_file_location("studio_install_python_stack_rdna1", _STACK_PY)+ assert spec is not None and spec.loader is not None+ mod = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = mod+ spec.loader.exec_module(mod)+ return mod+++stack_mod = _load_stack_module()+++# Windows WMI reports the marketing name; Linux lspci reports the chip plus a+# slash-joined list of the boards built on it. Both must resolve.+_RDNA1_NAMES = [+ ("AMD Radeon RX 5700 XT", "gfx1010"),+ ("AMD Radeon RX 5700", "gfx1010"),+ ("AMD Radeon RX 5600 XT", "gfx1010"),+ ("AMD Radeon Pro 5600 XT", "gfx1010"),+ ("Navi 10 [Radeon RX 5600 OEM/5600 XT / 5700/5700 XT]", "gfx1010"),+ ("AMD Radeon Pro V520", "gfx1011"),+ ("AMD Radeon Pro 5600M", "gfx1011"),+ ("AMD Radeon RX 5500 XT", "gfx1012"),+ ("Navi 14 [Radeon RX 5500/5500M / Pro 5500M]", "gfx1012"),+ # The professional boards LLVM's table omits. Die confirmed from libdrm+ # data/amdgpu.ids read against pci.ids, which names 7312/7310 Navi 10 and+ # 7340/7341/7347/734f Navi 14, and the kernel's amdgpu table, which files those+ # ids under CHIP_NAVI10 / CHIP_NAVI14.+ ("AMD Radeon Pro W5700", "gfx1010"),+ ("Navi 10 [Radeon Pro W5700X]", "gfx1010"),+ ("AMD Radeon Pro W5500", "gfx1012"),+ ("AMD Radeon Pro W5500M", "gfx1012"),+ ("Navi 14 [Radeon Pro W5300M]", "gfx1012"),+ ("AMD Radeon RX 5300", "gfx1012"),+ ("AMD Radeon RX 5300M", "gfx1012"),+ # The Mac Pro MPX boards, pci.ids 7319 and 731b under Navi 10: the only Navi 10+ # retail parts naming neither "RX 5700" nor a W prefix.+ ("Navi 10 [Radeon Pro 5700 XT]", "gfx1010"),+ ("Navi 10 [Radeon Pro 5700]", "gfx1010"),+ ("AMD Radeon Pro 5700 XT", "gfx1010"),+]++# Cards the supported table owns, plus a non-AMD one. A hit here would print+# "ROCm does not cover this" at a user whose GPU has wheels.+_NOT_RDNA1_NAMES = [+ "AMD Radeon RX 9070 XT",+ "AMD Radeon RX 9060 XT",+ "AMD Radeon RX 7900 XTX",+ "AMD Radeon RX 6800 XT",+ "AMD Radeon 8060S Graphics",+ "NVIDIA GeForce RTX 4090",+ # The workstation boards that DO have wheels, now that this table names W-series+ # parts: "W5700" must not be read out of "W7500", nor "W5500" out of "W6500".+ "AMD Radeon PRO W7500",+ "AMD Radeon PRO W7900",+ "AMD Radeon PRO W6500",+ "AMD Radeon PRO W6400",+]+++# ── The lookup itself ────────────────────────────────────────────────────────+++class TestUnsupportedNameLookup:+ @pytest.mark.parametrize("name,expected", _RDNA1_NAMES)+ def test_rdna1_names_resolve_to_their_arch(self, name, expected):+ assert stack_mod._unsupported_gfx_arch_from_gpu_name(name) == expected++ @pytest.mark.parametrize("name", _NOT_RDNA1_NAMES)+ def test_supported_and_non_amd_names_are_not_claimed(self, name):+ assert stack_mod._unsupported_gfx_arch_from_gpu_name(name) is None++ def test_empty_name_is_not_claimed(self):+ assert stack_mod._unsupported_gfx_arch_from_gpu_name("") is None++ @pytest.mark.parametrize("name,_expected", _RDNA1_NAMES)+ def test_rdna1_still_gets_no_supported_arch(self, name, _expected):+ """The behavioural half: RDNA 1 must keep falling through to CPU torch.+ If this ever passes an arch back, the installer would try to route it."""+ assert stack_mod._gfx_arch_from_gpu_name(name) is None++ def test_no_unsupported_arch_can_reach_a_wheel_index(self):+ """The scope guard. An arch in this table with an index-family entry would+ turn a messaging row into an installation change."""+ families = stack_mod._GFX_TO_AMD_INDEX_ARCH+ for _pat, arch in stack_mod._UNSUPPORTED_GPU_NAME_ARCH_TABLE:+ assert arch not in families, f"{arch} is routable; it must not be in this table"++ def test_the_two_tables_share_no_arch(self):+ supported = {arch for _p, arch in stack_mod._WIN_GPU_NAME_ARCH_TABLE}+ unsupported = {arch for _p, arch in stack_mod._UNSUPPORTED_GPU_NAME_ARCH_TABLE}+ assert not (supported & unsupported)+++# ── The Windows WMI path end to end ──────────────────────────────────────────+++def _wmi_detect(names):+ """Drive _detect_windows_gfx_arch over `names` with no hipinfo and no amd-smi,+ which is the reporter's host: Adrenalin driver only. Returns (arch, stdout)."""+ ps_result = MagicMock()+ ps_result.returncode = 0+ amd = [n for n in names if re.search(r"AMD|Radeon", n, re.IGNORECASE)]+ ps_result.stdout = ("\r\n".join(amd) + "\r\n").encode()++ def _run(cmd, **kwargs):+ if cmd and "powershell.exe" in str(cmd[0]).lower():+ return ps_result+ raise FileNotFoundError(cmd[0])++ buf = io.StringIO()+ with patch.dict(os.environ, {}, clear = False):+ for _v in (+ "HIP_PATH",+ "ROCM_PATH",+ "UNSLOTH_ROCM_GFX_ARCH",+ "UNSLOTH_ENABLE_AMD_SMI",+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ ):+ os.environ.pop(_v, None)+ with contextlib.redirect_stdout(buf):+ with patch("shutil.which", return_value = None):+ with patch("os.path.isfile", return_value = False):+ with patch("subprocess.run", side_effect = _run):+ result = stack_mod._detect_windows_gfx_arch()+ return result, buf.getvalue()+++class TestExplicitIndexPinIsHonoured:+ """An explicit UNSLOTH_TORCH_INDEX_URL / _FAMILY reaches the ROCm install path for+ ANY gfx/rocm leaf (install.ps1's pinned-index arm), so "torch stays CPU-only and+ nothing changes that" is false on a pinned run. install.sh's CPU note already skips+ its guidance when pinned; the other four sources now agree with it."""++ _CPU_CLAIM = "torch will be CPU-only"++ def test_the_python_warning_drops_the_cpu_claim_when_pinned(self):+ with patch.dict(os.environ, {"UNSLOTH_TORCH_INDEX_URL": "https://example/gfx1010"}):+ _arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert "gfx1010" in out, "the card is still named"+ assert self._CPU_CLAIM not in out, f"a pinned index still gets the CPU-only verdict:\n{out}"++ def test_the_claim_is_there_without_a_pin(self):+ """The positive control: without it the test above passes on any wording."""+ with patch.dict(os.environ, {}, clear = False):+ for _v in ("UNSLOTH_TORCH_INDEX_URL", "UNSLOTH_TORCH_INDEX_FAMILY"):+ os.environ.pop(_v, None)+ _arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert self._CPU_CLAIM in out++ @pytest.mark.parametrize("path", [_INSTALL_PS1, _SETUP_PS1, _SETUP_SH], ids = lambda p: p.name)+ def test_each_shell_arm_reads_the_pin(self, path):+ """The shell sources cannot be called from here, so require the arm to READ the+ pin: the wording is only correct because it is conditional on it."""+ lines = _normalised(path).splitlines()+ hits = [+ i+ for i, line in enumerate(lines)+ if "so torch stays" in line and not line.lstrip().startswith("#")+ ] or [+ i+ for i, line in enumerate(lines)+ if "torch stays CPU-only" in line and not line.lstrip().startswith("#")+ ]+ assert hits, f"{path.name}: the CPU-only claim was not found"+ for i in hits:+ # Backwards: the pin is read above the claim, which is what puts the claim+ # in a branch. Bounded so an unrelated mention further up cannot satisfy it.+ window = "\n".join(lines[max(i - 10, 0) : i])+ assert "UNSLOTH_TORCH_INDEX_URL" in window, (+ f"{path.name}:{i + 1}: claims CPU-only unconditionally, which a pinned "+ f"index makes false:\n{window}"+ )+++class TestWindowsArm64GetsNoVulkanAdvice:+ """studio/setup.ps1 THROWS when the Vulkan variable is set on Windows ARM64 (no+ bundle is published there), so telling an ARM64 user to set it and re-run aborts+ the update instead of enabling GGUF acceleration."""++ def test_the_throw_this_depends_on_is_still_there(self):+ src = _normalised(_SETUP_PS1)+ assert (+ "no Windows ARM64 Vulkan bundle is published" in src+ ), "the ARM64 guard this test is built on was renamed; re-read setup.ps1"++ # The Python stack emits the PowerShell setter too, and setup.ps1 runs it before+ # reaching its own throw, so it is the last advice an ARM64 user sees. The tests+ # above pin the one offer it has today; this one covers any offer added later.+ @pytest.mark.parametrize(+ "path,guard",+ [+ (_INSTALL_PS1, "Get-HostMachineArch"),+ (_SETUP_PS1, "Get-HostMachineArch"),+ (_STACK_PY, "_is_windows_arm64"),+ ],+ ids = lambda p: getattr(p, "name", p),+ )+ def test_every_vulkan_offer_is_behind_an_arch_check(self, path, guard):+ lines = _normalised(path).splitlines()+ offers = [+ i+ for i, line in enumerate(lines)+ if _SETTER[path.name] in line and not line.lstrip().startswith("#")+ ]+ assert offers, f"{path.name}: no Vulkan offer found"+ for i in offers:+ # The resolver itself, not a boolean named after it: a mutant that kept the+ # branch and hardcoded $unsupArm64 = $false survived that spelling.+ back = "\n".join(lines[max(i - 20, 0) : i])+ assert guard in back, (+ f"{path.name}:{i + 1}: offers the Vulkan variable without checking for "+ f"Windows ARM64, where setting it throws:\n{back}"+ )+++class TestPythonStackWindowsArm64:+ """The Windows WMI path prints the same Vulkan advice as install.ps1, and the same+ ARM64 throw applies to it: setup.ps1 rejects the variable there."""++ def test_arm64_gets_a_source_build_note_instead_of_the_setter(self):+ with patch.object(stack_mod, "_is_windows_arm64", return_value = True):+ _arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert "gfx1010" in out, "the card is still named"+ assert (+ "UNSLOTH_LLAMA_CPP_BACKEND" not in out+ ), f"ARM64 is still told to set the variable setup.ps1 throws on:\n{out}"+ assert "ARM64" in out and "source" in out++ def test_x64_still_gets_the_setter(self):+ """Positive control: the guard must not silence the advice everywhere."""+ with patch.object(stack_mod, "_is_windows_arm64", return_value = False):+ _arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert "UNSLOTH_LLAMA_CPP_BACKEND" in out++ @pytest.mark.parametrize(+ "env,expected",+ [+ ({"PROCESSOR_ARCHITECTURE": "ARM64"}, True),+ ({"PROCESSOR_ARCHITECTURE": "AMD64", "PROCESSOR_ARCHITEW6432": "ARM64"}, True),+ ({"PROCESSOR_ARCHITECTURE": "AMD64", "PROCESSOR_ARCHITEW6432": ""}, False),+ ],+ ids = ["native-arm64", "emulated-x64-on-arm64", "real-x64"],+ )+ def test_the_arch_probe_reads_the_machine_not_the_process(self, env, expected):+ """PROCESSOR_ARCHITECTURE describes the PROCESS, so an emulated x64 Python on an+ ARM64 box reports AMD64; ARCHITEW6432 is ARM64 in exactly that case."""+ with patch.object(stack_mod, "IS_WINDOWS", True):+ with patch.object(stack_mod.platform, "machine", return_value = "AMD64"):+ with patch.dict(os.environ, env, clear = False):+ for _k in ("PROCESSOR_ARCHITEW6432", "PROCESSOR_ARCHITECTURE"):+ if _k not in env:+ os.environ.pop(_k, None)+ assert stack_mod._is_windows_arm64() is expected++ def test_it_is_false_off_windows(self):+ with patch.object(stack_mod, "IS_WINDOWS", False):+ with patch.dict(os.environ, {"PROCESSOR_ARCHITECTURE": "ARM64"}):+ assert stack_mod._is_windows_arm64() is False+++class TestWindowsWmiMessage:+ def test_rdna1_adapter_still_yields_no_arch(self):+ """CPU fallback unchanged. This is the assertion that keeps the fix honest."""+ arch, _out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert arch is None++ def test_rdna1_adapter_is_named_with_its_arch(self):+ _arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert "gfx1010" in out+ assert "AMD Radeon RX 5700 XT" in out++ def test_rdna1_adapter_is_not_told_to_set_the_override(self):+ """The defect proper. Setting UNSLOTH_ROCM_GFX_ARCH=gfx1010 lands on the+ unmapped-arch path and returns CPU anyway, so instructing it is an errand+ with no ending. The variable may still be NAMED, to say it cannot help."""+ _arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert "Set UNSLOTH_ROCM_GFX_ARCH to your GPU's arch" not in out+ assert "gfx1200" not in out+ assert "no UNSLOTH_ROCM_GFX_ARCH value changes that" in out++ def test_an_actually_unknown_adapter_keeps_the_override_advice(self):+ """The other half of the branch. A card we simply do not recognise is a+ different situation and the override really can rescue it."""+ arch, out = _wmi_detect(["AMD Radeon Graphics"])+ assert arch is None+ assert "Set UNSLOTH_ROCM_GFX_ARCH to your GPU's arch" in out++ def test_a_supported_adapter_is_unaffected(self):+ arch, out = _wmi_detect(["AMD Radeon RX 9070 XT"])+ assert arch == "gfx1201"+ assert "does not cover" not in out+++# ── The other four copies of the table ───────────────────────────────────────+++def _sh_function_body(source: str, name: str) -> str:+ needle = f"{name}() {{"+ start = source.find(needle)+ assert start != -1, f"{name}() not found"+ depth = 0+ i = start + len(needle) - 1+ while i < len(source):+ if source[i] == "{":+ depth += 1+ elif source[i] == "}":+ depth -= 1+ if depth == 0:+ return source[start : i + 1]+ i += 1+ raise AssertionError(f"unterminated {name}()")+++def _ps_block(source: str, header: str) -> str:+ start = source.find(header)+ assert start != -1, f"{header} not found"+ i = source.find("(", start)+ depth = 0+ while i < len(source):+ if source[i] == "(":+ depth += 1+ elif source[i] == ")":+ depth -= 1+ if depth == 0:+ return source[start : i + 1]+ i += 1+ raise AssertionError(f"unterminated {header}")+++def _sh_rows(body: str) -> "list[tuple[list[str], str]]":+ rows = []+ for line in body.splitlines():+ m = re.match(r"\s*(\*.*?)\)\s*echo\s+(gfx[0-9a-z]+)\s*;;", line.split("#", 1)[0])+ if m:+ rows.append(([p.strip() for p in m.group(1).split("|")], m.group(2)))+ return rows+++def _ps_rows(block: str) -> "list[tuple[str, str]]":+ return re.findall(r'@\{\s*P\s*=\s*"([^"]+)"\s*;\s*A\s*=\s*"(gfx[0-9a-z]+)"\s*\}', block)+++def _match_sh(rows, gpu_name):+ import fnmatch+ for patterns, arch in rows:+ for pattern in patterns:+ if fnmatch.fnmatchcase(gpu_name, pattern.replace('"', "")):+ return arch+ return None+++def _match_ps(rows, gpu_name):+ for pattern, arch in rows:+ if re.search(pattern, gpu_name, re.IGNORECASE):+ return arch+ return None+++def _all_copies():+ """Every copy of the unsupported table, as a resolver taking a GPU name."""+ sh_rows = _sh_rows(+ _sh_function_body(+ _INSTALL_SH.read_text(encoding = "utf-8"),+ "_infer_unsupported_amd_gfx_arch_from_gpu_name",+ )+ )+ setup_sh_rows = _sh_rows(+ _sh_function_body(_SETUP_SH.read_text(encoding = "utf-8"), "_setup_unsupported_gfx_from_name")+ )+ install_ps1_rows = _ps_rows(+ _ps_block(_INSTALL_PS1.read_text(encoding = "utf-8"), "$unsupportedNameArchTable = @(")+ )+ setup_ps1_rows = _ps_rows(+ _ps_block(_SETUP_PS1.read_text(encoding = "utf-8"), "$unsupportedNameArchTable = @(")+ )+ return {+ "install.sh": lambda n: _match_sh(sh_rows, n),+ "studio/setup.sh": lambda n: _match_sh(setup_sh_rows, n),+ "install.ps1": lambda n: _match_ps(install_ps1_rows, n),+ "studio/setup.ps1": lambda n: _match_ps(setup_ps1_rows, n),+ "studio/install_python_stack.py": stack_mod._unsupported_gfx_arch_from_gpu_name,+ }+++class TestUnsupportedTableParity:+ """The same drift guard the supported tables already carry. Five hand-copied+ tables is how #7264 / #7277 / #7293 each shipped half-applied."""++ def test_every_copy_parses_non_empty(self):+ rows = {+ "install.sh": _sh_rows(+ _sh_function_body(+ _INSTALL_SH.read_text(encoding = "utf-8"),+ "_infer_unsupported_amd_gfx_arch_from_gpu_name",+ )+ ),+ "studio/setup.sh": _sh_rows(+ _sh_function_body(+ _SETUP_SH.read_text(encoding = "utf-8"), "_setup_unsupported_gfx_from_name"+ )+ ),+ "install.ps1": _ps_rows(+ _ps_block(+ _INSTALL_PS1.read_text(encoding = "utf-8"), "$unsupportedNameArchTable = @("+ )+ ),+ "studio/setup.ps1": _ps_rows(+ _ps_block(_SETUP_PS1.read_text(encoding = "utf-8"), "$unsupportedNameArchTable = @(")+ ),+ }+ for where, parsed in rows.items():+ assert parsed, f"{where}: parsed an empty unsupported table (moved or renamed?)"++ @pytest.mark.parametrize("name,expected", _RDNA1_NAMES)+ def test_all_copies_agree_on_rdna1(self, name, expected):+ answers = {where: fn(name) for where, fn in _all_copies().items()}+ assert set(answers.values()) == {expected}, f"{name!r} resolves inconsistently: {answers}"++ @pytest.mark.parametrize("name", _NOT_RDNA1_NAMES)+ def test_no_copy_claims_a_supported_card(self, name):+ answers = {where: fn(name) for where, fn in _all_copies().items()}+ assert set(answers.values()) == {None}, f"{name!r} was claimed as unsupported: {answers}"+++# ── The wording, in the sources that print it ────────────────────────────────+++def _normalised(path: Path) -> str:+ """CRLF-normalised source text. install.ps1 / setup.ps1 ship CRLF, so a+ substring spanning a line break never matches without this."""+ return path.read_text(encoding = "utf-8").replace("\r\n", "\n")+++class TestAdviceIsNotEmittedForRdna1:+ """Each installer's unsupported arm must come BEFORE its "arch unknown" arm,+ and must not repeat the advice that arm gives."""++ @pytest.mark.parametrize(+ "path,unsupported_marker,unknown_marker",+ [+ (+ _INSTALL_PS1,+ "elseif ($ROCmUnsupportedGfxArch) {\n # Detected, identified",+ 'step "gpu" "AMD GPU detected -- arch unknown"',+ ),+ (+ _SETUP_PS1,+ "elseif ($script:ROCmUnsupportedGfxArch) {\n # Detected, identified",+ 'step "gpu" "AMD GPU detected -- arch unknown"',+ ),+ ],+ )+ def test_unsupported_arm_precedes_the_arch_unknown_arm(+ self, path, unsupported_marker, unknown_marker+ ):+ src = _normalised(path)+ # The "was found" guard: without it a renamed branch makes both finds -1+ # and -1 < -1 is False, so the ordering claim would pass vacuously.+ assert unsupported_marker in src, f"{path.name}: unsupported arm not found"+ assert unknown_marker in src, f"{path.name}: arch-unknown arm not found"+ assert src.index(unsupported_marker) < src.index(unknown_marker)++ @pytest.mark.parametrize("path", [_INSTALL_PS1, _SETUP_PS1])+ def test_the_unsupported_arm_says_the_override_cannot_help(self, path):+ src = _normalised(path)+ # Scoped to the card, not the host: see _HOST_WIDE_CLAIMS below for why.+ needle = "setting UNSLOTH_ROCM_GFX_ARCH will not change that for it."+ assert needle in src, f"{path.name}: the override disclaimer is missing"++ def test_install_sh_cpu_note_keeps_the_sdk_advice_only_for_unknown_cards(self):+ """install.sh emits the same wording at two sites. Pin the WHOLE line at each+ one: a shared needle matches the other site and passes a deleted branch."""+ src = _normalised(_INSTALL_SH)+ unsupported = (+ 'substep "AMD GPU detected ($_unsup_disp_gfx) -- Unsloth has no ROCm PyTorch '+ 'wheels for that arch, installing CPU PyTorch." "$C_WARN"'+ )+ sdk_advice = "Install the ROCm/HIP SDK and re-run this installer for GPU PyTorch."+ assert unsupported in src, "install.sh: unsupported arm of the CPU note not found"+ assert sdk_advice in src, "install.sh: SDK advice not found (branch renamed?)"+ assert src.index(unsupported) < src.index(sdk_advice)++ def test_install_sh_index_selection_does_not_send_users_to_repair_rocminfo(self):+ src = _normalised(_INSTALL_SH)+ unsupported = (+ 'echo "[WARN] AMD GPU detected ($_amd_unsup_gfx) -- Unsloth has no ROCm PyTorch '+ 'wheels for that arch, installing CPU PyTorch." >&2'+ )+ repair_advice = "install or repair rocminfo/amd-smi"+ assert unsupported in src, "install.sh: unsupported arm of the index selector not found"+ assert repair_advice in src, "install.sh: rocminfo advice not found (branch renamed?)"+ assert src.index(unsupported) < src.index(repair_advice)++ def test_install_sh_unsupported_lookup_is_wired_to_both_sites(self):+ """The lookup must be CALLED, not merely defined; the assertions above read+ strings that a dead branch would still contain."""+ src = _normalised(_INSTALL_SH)+ assert src.count("_infer_linux_unsupported_amd_gfx_arch 2>/dev/null") == 2++ # Every arm that would otherwise outrank the unsupported one, with the guard it+ # must carry. An installed HIP SDK is the SYMPTOM here -- the #8529 reporters+ # installed it because the old advice said to -- so unguarded, the fix never+ # prints for the exact users it was written for.+ _HIPSDK_ARMS = [+ (_INSTALL_PS1, "$HipSdkInstalled -and $ROCmGpuLabel", " -and -not $ROCmUnsupportedGfxArch"),+ (_INSTALL_PS1, "$HipSdkInstalled -and -not $HasROCm", " -and -not $ROCmUnsupportedGfxArch"),+ (+ _SETUP_PS1,+ "$HipSdkInstalled -and $ROCmGpuLabel",+ " -and -not $script:ROCmUnsupportedGfxArch",+ ),+ ]++ @pytest.mark.parametrize(+ "path,condition,guard",+ _HIPSDK_ARMS,+ ids = [f"{p.name}:{c[:34]}" for p, c, _g in _HIPSDK_ARMS],+ )+ def test_the_hip_sdk_arm_does_not_outrank_the_unsupported_arm(self, path, condition, guard):+ """Stated as a ban on the UNGUARDED condition, not as a search for the guarded+ one: asserting only that the guarded text exists stays green if someone adds a+ second, unguarded copy of the arm, and both spellings would then be present."""+ src = _normalised(path)+ assert condition + guard in src, (+ f"{path.name}: the {condition!r} arm has lost its unsupported-arch guard, so an "+ f"RDNA 1 user who already installed the HIP SDK never sees the new message"+ )+ assert condition + ")" not in src, (+ f"{path.name}: an unguarded {condition!r} arm is present and precedes the "+ f"unsupported arm"+ )++ # The claim the arms must NOT make, and the one they must. With neither CUDA nor XPU+ # visible unsloth raises NotImplementedError at import (unsloth/device_type.py), so+ # "training runs on CPU" sends the user at an ImportError; these arms say what+ # studio/setup.sh already says. Scoped per ARM, not per file: install.ps1's+ # pre-existing $ROCmGfxArch hint makes the same claim for a different card, so a+ # file-wide ban would fail on untouched code and end up deleted.+ _TRAINING_ARMS = [+ (_INSTALL_PS1, "Unsloth installs no ROCm PyTorch wheels for $ROCmUnsupportedGfxArch"),+ (+ _INSTALL_PS1,+ "Installing CPU PyTorch -- Unsloth has no ROCm PyTorch wheels for "+ "$ROCmUnsupportedGfxArch.",+ ),+ (_SETUP_PS1, "Unsloth installs no ROCm PyTorch wheels for $script:ROCmUnsupportedGfxArch"),+ (_SETUP_SH, "no ROCm PyTorch wheels Unsloth installs"),+ ]++ @pytest.mark.parametrize(+ "path,anchor", _TRAINING_ARMS, ids = [f"{p.name}:{a[:34]}" for p, a in _TRAINING_ARMS]+ )+ def test_no_unsupported_arm_promises_cpu_training(self, path, anchor):+ lines = _normalised(path).splitlines()+ hits = [+ i+ for i, line in enumerate(lines)+ if anchor in line and not line.lstrip().startswith("#")+ ]+ assert len(hits) == 1, f"{path.name}: expected one arm anchored on {anchor!r}, got {hits}"+ window = "\n".join(+ line+ for line in _arm_window(lines, hits[0])+ if not line.lstrip().startswith(("#", "//"))+ )+ assert "runs on CPU on this GPU" not in window, (+ f"{path.name}:{hits[0] + 1}: promises CPU training, which raises "+ f"NotImplementedError at `import unsloth` on a host with no CUDA/XPU "+ f"accelerator:\n{window}"+ )+ assert "training and GPU inference are unavailable" in window, (+ f"{path.name}:{hits[0] + 1}: never says training is unavailable on this "+ f"GPU:\n{window}"+ )++ def test_readme_does_not_sweep_in_every_pre_rdna2_amd_gpu(self):+ """Vega 20 (Radeon VII / MI50, gfx906) is older than RDNA 2 and DOES have a+ ROCm PyTorch path -- install.sh routes it to the rocm6.3 index. A blanket+ "AMD GPUs older than RDNA 2" would send those users to Vulkan and CPU torch+ for nothing."""+ src = _normalised(PACKAGE_ROOT / "README.md")+ # Any spelling of the cutoff, not one literal: "every AMD GPU older than RDNA 2"+ # slipped past an exact-string ban while contradicting the gfx906 carve-out.+ blanket = re.search(r"AMD GPUs? older than RDNA ?2", src, re.IGNORECASE)+ assert not blanket, (+ f"README: {blanket.group(0)!r} claims ROCm PyTorch covers nothing older "+ "than RDNA 2, which is wrong for gfx906"+ )+ # The group must be named by its members, or the carve-out has nothing to cut.+ for _member in ("Polaris", "RDNA 1"):+ assert _member in src, f"README: never names {_member} as part of the unsupported group"+ assert "gfx906" in src, "README: never carves Vega 20 out of the unsupported group"+ # The carve-out has to be true of the installer, not just of the README.+ assert "rocm6.3" in _normalised(_INSTALL_SH), "install.sh: no gfx906 ROCm index left"++ def test_setup_sh_names_the_arch_instead_of_claiming_rocm(self):+ src = _normalised(_SETUP_SH)+ needle = 'step "gpu" "AMD GPU detected ($_setup_unsup_gfx) -- no ROCm PyTorch wheels Unsloth installs"'+ fallthrough = 'step "gpu" "AMD ROCm"'+ assert needle in src, "studio/setup.sh: unsupported arm not found"+ assert fallthrough in src, "studio/setup.sh: plain AMD ROCm arm not found"+ assert src.index(needle) < src.index(fallthrough)+++# ── studio/setup.sh on a host with no ROCm userspace at all ──────────────────+++def _run_setup_kfd_lookup(gpu_name: str, lspci_lines: "list[str] | None", tmp_path) -> str:+ """Run studio/setup.sh's report-side lookup with a scripted lspci.++ `lspci_lines is None` means the binary is absent, which is the other half of+ the KFD-only host: amdgpu exposes /dev/kfd, no ROCm userspace is installed.+ """+ src = _SETUP_SH.read_text(encoding = "utf-8")+ body = "\n".join(+ _sh_function_body(src, name)+ for name in ("_setup_unsupported_gfx_from_name", "_setup_unsupported_gfx_any")+ )+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ # PATH is bin_dir and nothing else, so "lspci absent" really is absent rather than+ # the host's own lspci answering. The shell itself has to be linked in for that.+ real_sh = shutil.which("sh")+ assert real_sh, "no POSIX sh on this host"+ (bin_dir / "sh").symlink_to(real_sh)+ for _tool in ("grep", "cat"):+ _found = shutil.which(_tool)+ assert _found, f"no {_tool} on this host"+ (bin_dir / _tool).symlink_to(_found)+ if lspci_lines is not None:+ fake = bin_dir / "lspci"+ printed = "\n".join(lspci_lines)+ fake.write_text(f'#!/bin/sh\ncat <<"LSPCI_EOF"\n{printed}\nLSPCI_EOF\n', encoding = "utf-8")+ fake.chmod(0o755)+ env = dict(os.environ, PATH = str(bin_dir))+ out = subprocess.run(+ ["sh", "-c", f'{body}\n_setup_unsupported_gfx_any "$1" || true\n', "sh", gpu_name],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 30,+ env = env,+ )+ return out.stdout.strip()+++_KFD_NAVI10 = [+ "0a:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] "+ "Navi 10 [Radeon RX 5600 OEM/5600 XT / 5700/5700 XT] [1002:731f] (rev c1)"+]+_KFD_POLARIS = [+ "01:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] "+ "Ellesmere [Radeon RX 470/480/570/570X/580/580X/590] [1002:67df] (rev e7)"+]+_KFD_NAVI31 = [+ "03:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] "+ "Navi 31 [Radeon RX 7900 XT/7900 XTX/7900M] [1002:744c] (rev cc)"+]++[email protected](os.name == "nt", reason = "POSIX shell only")+class TestSetupShKfdOnlyHost:+ """The KFD sysfs fallback marks the host AMD without rocminfo or amd-smi, so it+ leaves _setup_mkt empty -- and a host with no ROCm userspace is exactly the one+ #8529 and #8458 describe. Handed "", the lookup used to fall through to the plain+ "AMD ROCm" report on a machine that has no ROCm."""++ def test_the_kfd_host_is_diagnosed_from_lspci(self, tmp_path):+ assert _run_setup_kfd_lookup("", _KFD_NAVI10, tmp_path) == "gfx1010"++ def test_polaris_on_the_kfd_host_is_diagnosed_too(self, tmp_path):+ assert _run_setup_kfd_lookup("", _KFD_POLARIS, tmp_path) == "gfx803"++ def test_a_covered_card_is_never_claimed_from_lspci(self, tmp_path):+ """The scope guard: an RX 7900 with no ROCm installed is a missing runtime,+ not an uncovered generation, and must keep the plain report."""+ assert _run_setup_kfd_lookup("", _KFD_NAVI31, tmp_path) == ""++ def test_no_lspci_is_not_an_error(self, tmp_path):+ assert _run_setup_kfd_lookup("", None, tmp_path) == ""++ def test_a_reported_name_still_decides(self, tmp_path):+ """rocminfo/amd-smi named the card; lspci is not consulted behind their back."""+ assert _run_setup_kfd_lookup("AMD Radeon RX 5500 XT", _KFD_NAVI10, tmp_path) == "gfx1012"++ def test_an_unmapped_reported_name_falls_through_to_lspci(self, tmp_path):+ """A name that maps ENDS the lookup (above); one that does not must not, or a+ generic "AMD Radeon Graphics" from rocminfo hides a card lspci names outright.+ Only reachable with no gfx from the tools, so a covered compute card cannot be+ talked over here: rocminfo reports its arch and the supported arm wins first."""+ assert _run_setup_kfd_lookup("AMD Radeon Graphics", _KFD_NAVI10, tmp_path) == "gfx1010"++ def test_an_unmapped_name_over_a_covered_card_still_claims_nothing(self, tmp_path):+ assert _run_setup_kfd_lookup("AMD Radeon Graphics", _KFD_NAVI31, tmp_path) == ""++ def test_the_report_site_uses_the_lspci_aware_lookup(self):+ src = _normalised(_SETUP_SH)+ assert (+ 'elif _setup_unsup_gfx=$(_setup_unsupported_gfx_any "$_setup_mkt"); then' in src+ ), "studio/setup.sh: the gpu report no longer goes through the lspci-aware lookup"++ def test_the_lspci_name_never_reaches_the_routing_table(self):+ """Routing must stay byte-identical. The supported inference table keys on+ _setup_mkt, which feeds --rocm-gfx into the prebuilt and whisper commands, so+ the lspci read must not be written back into it."""+ src = _normalised(_SETUP_SH)+ assigns = re.findall(r"^\s*_setup_mkt=(.*)$", src, re.MULTILINE)+ assert assigns, "studio/setup.sh: no _setup_mkt assignment found"+ for rhs in assigns:+ assert "lspci" not in rhs, f"_setup_mkt fed from lspci: {rhs!r}"+++# ── The new variable has to outlive the block that sets it ───────────────────+++def test_the_unsupported_arch_variable_is_declared_outside_the_amd_block():+ """install.ps1 reads it on paths an NVIDIA host takes.++ `$ROCmUnsupportedGfxArch` is set inside `if (-not $HasNvidiaSmi)`, but the arms+ that read it sit outside that gate, so on an NVIDIA host the read is of a variable+ that was never assigned. `Set-StrictMode -Version Latest` turns that into a hard+ stop. Install-UnslothStudio runs with strict mode off, which is why this has not+ bitten, but its five neighbours (HasROCm, HipSdkInstalled, ROCmGpuLabel,+ ROCmVersion, ROCmGfxArch) are all declared above the gate and this one has to be+ too. studio/setup.ps1 already hoists its copy.+ """+ src = _normalised(_INSTALL_PS1)+ m = re.search(+ r"^ \$ROCmGfxArch = \$null\n(?P<between>(?:.*\n)*?) if \(-not \$HasNvidiaSmi\) \{",+ src,+ re.MULTILINE,+ )+ assert m, "install.ps1: the AMD declaration block was restructured; re-check this test"+ assert "$ROCmUnsupportedGfxArch = $null" in m.group("between"), (+ "install.ps1: $ROCmUnsupportedGfxArch is declared inside the -not $HasNvidiaSmi "+ "block, so an NVIDIA host reaches its readers with the variable unset"+ )+++def test_setup_ps1_hoists_the_unsupported_arch_variable_too():+ """Same property, expressed as setup.ps1 writes it: at script scope, column 0,+ so no block can gate the declaration away from the summary that reads it."""+ src = _normalised(_SETUP_PS1)+ decl = "$script:ROCmUnsupportedGfxArch = $null"+ assert decl in src, "setup.ps1: the unsupported-arch declaration is gone"+ assert any(line == decl for line in src.split("\n")), (+ "setup.ps1: the unsupported-arch declaration is indented, so it now sits "+ "inside a block an NVIDIA host skips"+ )+++# ── An identified uncovered card outranks the generic ROCm report ────────────+++_ROCM_ARM = {+ "install.ps1": ("} elseif ($HasROCm", "$ROCmUnsupportedGfxArch"),+ "setup.ps1": ("} elseif ($HasROCm", "$script:ROCmUnsupportedGfxArch"),+}++[email protected]("name", sorted(_ROCM_ARM))+def test_the_generic_rocm_arm_yields_to_an_identified_uncovered_card(name):+ """amd-smi can report a GPU with no gfx token and only a market name.++ That sets $HasROCm with no arch, so the generic arm fires and calls an RX 5700 XT+ "AMD ROCm" while the wheel note in the same run says gfx1010 has none. The host is+ not hypothetical: amd-smi is only probed when the HIP SDK is present, which is what+ the #8529 and #8458 reporters installed because the old message told them to. Same+ guard the HIP SDK arm below it already carries.+ """+ source_path = _INSTALL_PS1 if name == "install.ps1" else _SETUP_PS1+ opener, var = _ROCM_ARM[name]+ src = _normalised(source_path)+ arm = next((ln for ln in src.split("\n") if ln.strip().startswith(opener)), None)+ assert arm is not None, f"{name}: the $HasROCm arm was renamed"+ assert f"-not {var}" in arm, (+ f"{name}: the generic ROCm arm outranks the identified-uncovered-card arm, so a "+ f"card we already named is reported as ordinary ROCm:\n{arm}"+ )+++def test_the_rocm_summary_chain_yields_to_an_identified_uncovered_card():+ """The summary chain opens with a bare `if ($HasROCm)`, not an `} elseif`.++ So the check above walks straight past it. Its own third arm names the uncovered+ card, and that arm is reached only when nothing outranks it: on a host where+ amd-smi enumerates an RDNA 1 card with no gfx token, the "ROCm x.y" arm wins and+ the arm written for that card never runs.+ """+ src = _normalised(_SETUP_PS1)+ lines = src.split("\n")+ opener = next(+ (+ i+ for i, ln in enumerate(lines)+ if ln.strip().startswith("if ($HasROCm")+ and "$rocmVerLabel" in "\n".join(lines[i : i + 3])+ ),+ None,+ )+ assert opener is not None, "setup.ps1: the ROCm summary chain was renamed"+ chain = "\n".join(lines[opener : opener + 20])+ assert (+ "$script:ROCmUnsupportedGfxArch" in chain+ ), "setup.ps1: the summary chain no longer has an uncovered-card arm"+ assert "-not $script:ROCmUnsupportedGfxArch" in lines[opener], (+ "setup.ps1: the ROCm summary reports an uncovered card as ordinary ROCm, so the "+ f"same run says 'ROCm' here and 'no wheels' below:\n{lines[opener]}"+ )+++# ── Scope: these sentences speak for one card, not for the host ───────────+++# A host is not one GPU. An RX 580 beside an RX 7900 XTX is a host where masking to the+# other card and pinning its arch DOES install wheels, so a host-wide "nothing can enable+# ROCm here" is false there. Deciding it at runtime was tried and dropped: "any adapter we+# cannot name" misfires on the Vega-class iGPU on most Ryzen desktops, and "any covered+# peer" misses the Instinct and V620 parts no name table carries.+_ALL_SOURCES = [_INSTALL_SH, _SETUP_SH, _INSTALL_PS1, _SETUP_PS1, _STACK_PY]++_HOST_WIDE_CLAIMS = [+ "will not enable ROCm PyTorch.",+ "Installing the ROCm/HIP SDK will not change this.",+ "no UNSLOTH_ROCM_GFX_ARCH value changes that.",+ "UNSLOTH_ROCM_GFX_ARCH will not change that.",+ "can enable ROCm here.",+]++_SCOPED_CLAIMS = {+ "install.sh": [+ "will not give it ROCm PyTorch.",+ "Installing the ROCm/HIP SDK will not give this GPU ROCm PyTorch.",+ ],+ "setup.sh": [+ "no UNSLOTH_ROCM_GFX_ARCH value gives this GPU one.",+ ],+ "install.ps1": [+ "will not change that for it.",+ "can give this GPU ROCm.",+ ],+ "setup.ps1": [+ "will not change that for it.",+ ],+ "install_python_stack.py": [+ "changes that on this GPU.",+ ],+}++[email protected]("source_path", _ALL_SOURCES, ids = [p.name for p in _ALL_SOURCES])+def test_no_advice_arm_speaks_for_the_whole_host(source_path):+ src = _normalised(source_path)+ for line in src.split("\n"):+ if line.lstrip().startswith("#"):+ continue+ for claim in _HOST_WIDE_CLAIMS:+ assert claim not in line, (+ f"{source_path.name}: this sentence claims the HOST has no ROCm path, "+ f"which is false beside a covered card:\n{line}"+ )++[email protected]("name,claims", sorted(_SCOPED_CLAIMS.items()))+def test_the_scoped_wording_is_the_one_that_ships(name, claims):+ """The other half: dropping the sentence entirely would also pass the ban above,+ and would take the answer with it. Each arm still has to say ROCm cannot reach+ the card it just named."""+ source_path = next(p for p in _ALL_SOURCES if p.name == name)+ src = _normalised(source_path)+ emitted = [ln for ln in src.split("\n") if not ln.lstrip().startswith("#")]+ for claim in claims:+ assert any(claim in ln for ln in emitted), (+ f"{source_path.name}: the scoped verdict {claim!r} is gone; an arm that "+ f"names an uncovered arch has to say ROCm does not reach it"+ )+++# ── The shell copies, executed rather than parsed ────────────────────────────+++def _run_sh_lookup(source_path: Path, fn_name: str, gpu_name: str) -> str:+ body = _sh_function_body(source_path.read_text(encoding = "utf-8"), fn_name)+ script = f'{body}\n{fn_name} "$1" || true\n'+ out = subprocess.run(+ ["sh", "-c", script, "sh", gpu_name],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 30,+ )+ return out.stdout.strip()++[email protected](os.name == "nt", reason = "POSIX shell only")+class TestShellLookupsRun:+ """Parsing a case table and evaluating it in Python is not the same as the+ shell evaluating it; run the real thing on the reporter's card."""++ @pytest.mark.parametrize(+ "path,fn",+ [+ (_INSTALL_SH, "_infer_unsupported_amd_gfx_arch_from_gpu_name"),+ (_SETUP_SH, "_setup_unsupported_gfx_from_name"),+ ],+ )+ def test_rx_5700_xt_resolves_to_gfx1010(self, path, fn):+ assert _run_sh_lookup(path, fn, "AMD Radeon RX 5700 XT") == "gfx1010"++ @pytest.mark.parametrize(+ "path,fn",+ [+ (_INSTALL_SH, "_infer_unsupported_amd_gfx_arch_from_gpu_name"),+ (_SETUP_SH, "_setup_unsupported_gfx_from_name"),+ ],+ )+ def test_rx_9070_xt_is_not_claimed(self, path, fn):+ assert _run_sh_lookup(path, fn, "AMD Radeon RX 9070 XT") == ""++ @pytest.mark.parametrize(+ "path,fn",+ [+ (_INSTALL_SH, "_infer_unsupported_amd_gfx_arch_from_gpu_name"),+ (_SETUP_SH, "_setup_unsupported_gfx_from_name"),+ ],+ )+ @pytest.mark.parametrize(+ "name,expected",+ [+ ("AMD Radeon RX 580", "gfx803"),+ ("AMD Radeon RX 5700 XT", "gfx1010"),+ ("AMD Radeon RX 5500 XT", "gfx1012"),+ ],+ )+ def test_polaris_does_not_shadow_rdna1_in_the_real_shell(self, path, fn, name, expected):+ """`case` has no negative lookahead, so the *"RX 570"* arm is only safe+ because it comes last. Evaluate it in a real shell rather than trusting+ the ordering by inspection."""+ assert _run_sh_lookup(path, fn, name) == expected+++# ── The Vulkan pointer (#8458) ───────────────────────────────────────────────+++def _arm_window(lines: "list[str]", start: int) -> "list[str]":+ """The rest of the branch the line at `start` belongs to, not a fixed line count.++ The advice is now emitted from if/else arms (an index pin and Windows ARM64 each+ change what is true), so a fixed window either stops mid-branch or spills into the+ NEXT arm, which is the failure this test's docstring already warns about. Stop at+ the first line that dedents past the anchor, which closes the arm in every language+ here, and cap the span so a missing closer cannot swallow the file.+ """+ indent = len(lines[start]) - len(lines[start].lstrip())+ # One step out, not the anchor's own indent: the claim it anchors now sits in a+ # nested if/else, and the Vulkan offer is its SIBLING branch, so stopping at the+ # anchor's own level would cut the window before the thing under test.+ floor = max(indent - 4, 0)+ out = [lines[start]]+ for line in lines[start + 1 : start + 25]:+ if line.strip() and (len(line) - len(line.lstrip())) < floor:+ break+ out.append(line)+ return out+++class TestVulkanAdvice:+ """#8458 is the same shape as #8529 -- a pre-RDNA 2 AMD card (RX 580, Polaris,+ gfx803) told it had no usable GPU -- but its reporter got the card working+ through Vulkan, as LM Studio does with the same hardware. So the unsupported+ arm must not dead-end at "ROCm does not cover this"; it has somewhere to send+ the user.++ Two things are load-bearing in that advice and both are asserted here:++ * the CURRENT variable name. ``UNSLOTH_FORCE_VULKAN`` (what #8458's reporter+ used) is still honoured, but only as a legacy fallback consulted when+ ``UNSLOTH_LLAMA_CPP_BACKEND`` is unset or unrecognised+ (``install_llama_prebuilt.py::force_vulkan_requested``). New text must+ teach the current spelling.+ * WHEN to set it. Every consumer of the selector lives in+ ``install_llama_prebuilt.py`` (``_route_to_vulkan_prebuilt``,+ ``install_prebuilt``, ``main``): it chooses which llama.cpp bundle gets+ downloaded, at install time. A user who exports it and merely relaunches+ Studio sees no change and concludes the advice was wrong -- which is+ exactly what happened in #8458. Advice that omits the timing is worse than+ no advice, so a message naming the variable must also name the moment.+ """++ # The four sources whose advice is a literal in an emitting statement. The Python+ # copy joins string fragments, so line-scoped source reading cannot see it; the+ # (stronger) live-output tests below cover it instead.+ _SHELL_SOURCES = [_INSTALL_PS1, _SETUP_PS1, _INSTALL_SH, _SETUP_SH]++ # Everything the advice has to carry, asserted against EMITTED text only: every+ # phrase here also appears in the comments explaining the branch, so a whole-file+ # search stays green after the message is gutted (three such mutants survived). The+ # setter is per-file (see _SETTER) and gets its own tests below.+ _REQUIRED = [+ # The offer must survive, not just the variable name: "no GPU acceleration is+ # available" followed by a GPU backend's name is worse than either half alone.+ ("through Vulkan", "the affirmative Vulkan offer"),+ ]++ @staticmethod+ def _emitted_text(path: Path) -> str:+ """Only the lines that PRINT, so comments explaining the branch cannot+ satisfy an assertion about what the user is told."""+ emitters = ("substep", "echo ", "_safe_print", "step ", "Write-StudioLine")+ return "\n".join(+ line+ for line in _normalised(path).splitlines()+ if any(e in line for e in emitters) and not line.lstrip().startswith(("#", "//"))+ )++ @pytest.mark.parametrize("path", _SHELL_SOURCES, ids = lambda p: p.name)+ @pytest.mark.parametrize("needle,what", _REQUIRED, ids = lambda v: v if " " not in v else None)+ def test_the_emitted_advice_carries_every_part(self, path, needle, what):+ assert needle in self._emitted_text(+ path+ ), f"{path.name}: the message a user actually sees is missing {what} ({needle!r})"++ @pytest.mark.parametrize("path", _SHELL_SOURCES, ids = lambda p: p.name)+ def test_the_emitted_advice_uses_the_right_shell_syntax(self, path):+ """The setter has to be pasteable into the shell that reads this file."""+ emitted = self._emitted_text(path)+ assert _SETTER[path.name] in emitted, (+ f"{path.name}: the printed advice never gives the setter in this shell's "+ f"syntax ({_SETTER[path.name]!r})"+ )++ @pytest.mark.parametrize("path", [_INSTALL_PS1, _SETUP_PS1, _STACK_PY], ids = lambda p: p.name)+ def test_no_windows_source_teaches_the_posix_setter(self, path):+ """The regression guard for the syntax above, stated as a ban.++ Asserted on emitters only: a comment may legitimately quote the POSIX form+ while explaining why the emitted line does not use it.+ """+ offenders = [+ line.strip()+ for line in _normalised(path).splitlines()+ if _POSIX_ASSIGNMENT in line+ and any(e in line for e in ("substep", "_safe_print", "step ", "Write-StudioLine"))+ and not line.lstrip().startswith("#")+ ]+ assert (+ not offenders+ ), f"{path.name}: prints a POSIX assignment PowerShell cannot parse: {offenders}"++ # Every arm that TELLS a pre-RDNA 2 user torch cannot use their GPU, with the expected+ # occurrence count. The count is the point: the tests either side of this one are+ # file-scoped, so a site deleted outright leaves both green. Anchors are each arm's+ # announcement line, so a deleted arm fails the count and a gutted one fails the window+ # below. install.ps1's second anchor names $ROCmUnsupportedGfxArch deliberately: the+ # same sentence four lines earlier is for a supported card.+ _ADVICE_SITES = [+ (_INSTALL_SH, "Unsloth has no ROCm PyTorch wheels for that arch", 2),+ (_INSTALL_PS1, "Unsloth installs no ROCm PyTorch wheels for $ROCmUnsupportedGfxArch", 1),+ (+ _INSTALL_PS1,+ "Installing CPU PyTorch -- Unsloth has no ROCm PyTorch wheels for "+ "$ROCmUnsupportedGfxArch.",+ 1,+ ),+ (+ _SETUP_PS1,+ "Unsloth installs no ROCm PyTorch wheels for $script:ROCmUnsupportedGfxArch",+ 1,+ ),+ (_SETUP_SH, "no ROCm PyTorch wheels Unsloth installs", 1),+ ]++ @pytest.mark.parametrize(+ "path,anchor,count",+ _ADVICE_SITES,+ ids = [f"{p.name}:{a[:34]}" for p, a, _c in _ADVICE_SITES],+ )+ def test_each_advisory_arm_offers_vulkan(self, path, anchor, count):+ """Per SITE, by real line number, so a whole arm cannot be deleted quietly.++ Windowed on the source lines rather than on the emitter-only projection the+ other tests use: that projection concatenates print statements from branches+ hundreds of lines apart, so a window over it can be satisfied by an unrelated+ arm that happens to be the next thing that prints.+ """+ lines = _normalised(path).splitlines()+ hits = [+ i+ for i, line in enumerate(lines)+ if anchor in line and not line.lstrip().startswith("#")+ ]+ assert len(hits) == count, (+ f"{path.name}: expected {count} advisory arm(s) anchored on {anchor!r}, found "+ f"{len(hits)} at lines {[i + 1 for i in hits]}. An arm was removed, renamed, or "+ f"duplicated; the advice must follow it either way."+ )+ for i in hits:+ # Comments stripped from the WINDOW, not just the anchor: every phrase+ # below also appears in the comment explaining the branch, so raw lines+ # stay green after the message is demoted to a comment (observed mutant).+ window = "\n".join(+ line for line in _arm_window(lines, i) if not line.lstrip().startswith(("#", "//"))+ )+ # The offer, not one phrasing of it: these arms are hard-wrapped to different+ # widths. Both halves are required -- a backend without what it buys, or GGUF+ # chat without the backend, is half an answer. "Vulkan" is matched+ # case-sensitively in PROSE, so the setter's lowercase spelling cannot stand+ # in for the sentence explaining it.+ assert "GGUF chat" in window and "Vulkan" in window, (+ f"{path.name}:{i + 1}: this arm dead-ends without offering GPU GGUF chat "+ f"through Vulkan:\n{window}"+ )+ assert _SETTER[path.name] in window, (+ f"{path.name}:{i + 1}: this arm offers Vulkan without naming the variable "+ f"that selects it, in this shell's syntax:\n{window}"+ )+ assert "install time" in window or "at launch" in window, (+ f"{path.name}:{i + 1}: this arm names the variable but never says the bundle "+ f"is chosen at install time, which is the mistake #8458 made:\n{window}"+ )++ @pytest.mark.parametrize("path", _SHELL_SOURCES, ids = lambda p: p.name)+ def test_every_site_that_names_the_variable_also_says_when(self, path):+ """The anti-#8458 clause, checked per SITE rather than per file.++ install.sh prints this advice at two places (index selection and the CPU+ note). A file-level "install time" search is satisfied by whichever site+ still has it, so gutting the other one passes -- observed: that exact+ mutant survived. Require the timing near each mention instead.+ """+ emitted = self._emitted_text(path).splitlines()+ mentions = [i for i, line in enumerate(emitted) if _SETTER[path.name] in line]+ assert mentions, f"{path.name}: no site names the Vulkan variable"+ for i in mentions:+ window = "\n".join(emitted[i : i + 4])+ assert "install time" in window, (+ f"{path.name}: the advice at emitted line {i + 1} names the variable but "+ f"never says the bundle is chosen at install time:\n{window}"+ )++ @pytest.mark.parametrize("path", _SHELL_SOURCES + [_STACK_PY], ids = lambda p: p.name)+ def test_the_legacy_spelling_is_not_taught(self, path):+ """UNSLOTH_FORCE_VULKAN still works, but it is the legacy name and loses to+ UNSLOTH_LLAMA_CPP_BACKEND whenever that parses, so new text must not spread+ it.++ Scoped to lines that PRINT. setup.sh and setup.ps1 legitimately *read* the+ legacy variable for back-compat, and this fix does not touch that; a+ whole-file ban would fail on working code and would have to be deleted,+ taking the real assertion with it.+ """+ emitters = ("substep", "echo", "_safe_print", "step ", "Write-StudioLine")+ offenders = [+ line.strip()+ for line in _normalised(path).splitlines()+ if "UNSLOTH_FORCE_VULKAN" in line and any(e in line for e in emitters)+ ]+ assert not offenders, f"{path.name}: teaches the legacy variable: {offenders}"++ @pytest.mark.parametrize("needle,what", _REQUIRED, ids = lambda v: v if " " not in v else None)+ def test_the_vulkan_advice_is_reached_by_the_rdna1_wmi_path(self, needle, what):+ """Source-text assertions cannot tell a live branch from a dead one, and the+ Python copy's message is not readable line by line. Drive the real Windows+ path and read what it actually printed."""+ arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert arch is None, "routing must be unchanged; this is a wording fix"+ assert needle in out, f"the printed advice is missing {what} ({needle!r})"++ def test_the_printed_advice_uses_powershell_syntax(self):+ """This branch is Windows-only, so its setter has to be pasteable into+ PowerShell. Read the live output, not the source: the message is built from+ implicitly-joined fragments and no single source line carries it."""+ _arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert _PWSH_SETTER in out, f"the printed advice is not pasteable into PowerShell:\n{out}"+ assert (+ _POSIX_ASSIGNMENT not in out+ ), f"the printed advice gives a POSIX assignment PowerShell cannot parse:\n{out}"++ def test_the_printed_advice_says_when_to_set_it(self):+ """The anti-#8458 clause for the Python copy.++ The shell/PS sources get this per-site from source text; Python builds its+ message from implicitly-joined fragments, so only the live output can show+ it. Kept as its own test rather than folded into the shared list above,+ because that list is also used for the per-line source scan where a timing+ phrase legitimately lives on a different line than the variable.+ """+ _arch, out = _wmi_detect(["AMD Radeon RX 5700 XT"])+ assert "install time" in out, (+ f"the printed advice names the Vulkan variable but never says when to "+ f"set it:\n{out}"+ )++ def test_an_unknown_amd_card_gets_no_vulkan_advice(self):+ """Scope. A card we simply failed to recognise may well have ROCm wheels,+ so it keeps the override advice and must not be pushed onto Vulkan."""+ _arch, out = _wmi_detect(["AMD Radeon Graphics"])+ assert "UNSLOTH_LLAMA_CPP_BACKEND" not in out++ def test_a_supported_card_gets_no_vulkan_advice(self):+ _arch, out = _wmi_detect(["AMD Radeon RX 9070 XT"])+ assert "UNSLOTH_LLAMA_CPP_BACKEND" not in out++ def test_readme_copy_paste_blocks_use_the_current_spelling(self):+ """The installer now tells users a variable name and the README is where+ they check it, but it documented only the legacy spelling.++ Asserted against the fenced COMMANDS, not the prose: a reader copies the+ block. An earlier version of this test compared first-occurrence indexes,+ which the surrounding prose satisfied on its own and which therefore passed+ with both code blocks still reverted to UNSLOTH_FORCE_VULKAN.+ """+ src = _normalised(PACKAGE_ROOT / "README.md")+ blocks = re.findall(r"```(?:bash|powershell)\n(.*?)```", src, re.DOTALL)+ setters = [+ line.strip()+ for block in blocks+ for line in block.splitlines()+ if "VULKAN" in line.upper() or "LLAMA_CPP_BACKEND" in line+ ]+ assert setters, "README: no Vulkan setup command found at all"+ for line in setters:+ assert (+ "UNSLOTH_LLAMA_CPP_BACKEND" in line+ ), f"README teaches the legacy spelling in a copy-paste block: {line!r}"++ def test_readme_does_not_promise_vulkan_to_macos(self):+ """The block sits under a combined "macOS, Linux, WSL" heading, but macOS has no+ Vulkan llama.cpp bundle: install_llama_prebuilt.py logs that the variable is+ ignored and installs Metal. An Intel Mac carrying one of these very cards (the+ 16-inch MacBook Pro shipped Radeon Pro 5300M/5500M/5600M, all rows above) would+ follow the documented command and get nothing."""+ prebuilt = (PACKAGE_ROOT / "studio" / "install_llama_prebuilt.py").read_text(+ encoding = "utf-8"+ )+ assert "ignored on macOS" in prebuilt, (+ "the macOS branch this test documents was renamed; re-read it before "+ "trusting the README assertion below"+ )+ src = _normalised(PACKAGE_ROOT / "README.md")+ paragraph = next(+ (+ para+ for para in src.split("\n\n")+ if "no ROCm PyTorch wheels for" in para and "Polaris" in para+ ),+ None,+ )+ assert paragraph, "README: the uncovered-AMD Vulkan paragraph was not found"+ assert re.search(r"\bLinux\b.{0,12}\bWSL\b", paragraph), (+ "README: the Vulkan-for-uncovered-AMD paragraph sits under a heading that "+ "also covers macOS, so it has to name the platforms it is true for: "+ f"{paragraph!r}"+ )+ after = src.split(paragraph, 1)[1]+ assert re.search(+ r"macOS[^\n]*Metal", after+ ), "README: nothing tells a macOS reader what happens there instead"+++# ── Polaris, the second card in the cluster (#8458) ──────────────────────────+++_POLARIS_NAMES = [+ ("AMD Radeon RX 580", "gfx803"),+ ("AMD Radeon RX 580 Series", "gfx803"),+ ("AMD Radeon RX 570", "gfx803"),+ ("AMD Radeon RX 590", "gfx803"),+ ("AMD Radeon RX 480", "gfx803"),+ ("AMD Radeon RX 470", "gfx803"),+ ("Ellesmere [Radeon RX 470/480/570/570X/580/580X/590]", "gfx803"),+ # The Polaris 10 workstation boards: pci.ids groups them on Ellesmere, the RX 580+ # die from #8458, and their names carry no RX number for the consumer rows to hit.+ ("Ellesmere [Radeon Pro WX 7100 / WX 7100 Mobile / WX 5100 / V7300X / V7350x2]", "gfx803"),+ ("AMD Radeon Pro WX 7100", "gfx803"),+ ("AMD Radeon Pro WX 5100", "gfx803"),+]++# Polaris 11/12. Deliberately NOT in the table: a different die, and this table+# is only worth having while it never guesses an arch.+_POLARIS_11_12_NAMES = [+ "AMD Radeon RX 560",+ "AMD Radeon RX 550",+ "AMD Radeon RX 460",+]+++class TestPolarisRow:+ @pytest.mark.parametrize("name,expected", _POLARIS_NAMES)+ def test_polaris_names_resolve_to_gfx803(self, name, expected):+ assert stack_mod._unsupported_gfx_arch_from_gpu_name(name) == expected++ @pytest.mark.parametrize("name,_expected", _POLARIS_NAMES)+ def test_polaris_still_gets_no_supported_arch(self, name, _expected):+ """The behavioural half again: CPU torch must remain the outcome."""+ assert stack_mod._gfx_arch_from_gpu_name(name) is None++ @pytest.mark.parametrize("name", _POLARIS_11_12_NAMES)+ def test_polaris_11_12_is_not_claimed(self, name):+ assert stack_mod._unsupported_gfx_arch_from_gpu_name(name) is None++ @pytest.mark.parametrize("name,expected", _RDNA1_NAMES)+ def test_polaris_patterns_do_not_swallow_rdna1(self, name, expected):+ """The collision this row is one keystroke away from: "RX 570" is a prefix+ of "RX 5700" and "RX 550" of "RX 5500". Re-assert every RDNA 1 name still+ resolves to its own arch now that a Polaris row exists."""+ assert stack_mod._unsupported_gfx_arch_from_gpu_name(name) == expected++ @pytest.mark.parametrize("name,_expected", _RDNA1_NAMES)+ def test_the_polaris_pattern_is_correct_on_its_own(self, name, _expected):+ """The test above passes for the wrong reason and cannot replace this one.++ Table order already saves it: the RDNA 1 rows are matched first, so the+ Polaris pattern is never even reached for an RDNA 1 name and deleting its+ (?!0) guards changes nothing observable. That is precisely how a guard rots+ -- it stays correct only until someone reorders the table. Match the+ Polaris pattern ALONE, where the guard is the only thing standing between+ "RX 5700 XT" and gfx803.+ """+ pattern = next(+ p for p, arch in stack_mod._UNSUPPORTED_GPU_NAME_ARCH_TABLE if arch == "gfx803"+ )+ assert (+ re.search(pattern, name, re.IGNORECASE) is None+ ), f"the Polaris pattern claims the RDNA 1 name {name!r} when matched on its own"++ @pytest.mark.parametrize("name,expected", _POLARIS_NAMES)+ def test_all_copies_agree_on_polaris(self, name, expected):+ answers = {where: fn(name) for where, fn in _all_copies().items()}+ assert set(answers.values()) == {expected}, f"{name!r} resolves inconsistently: {answers}"++ @pytest.mark.parametrize("name", _POLARIS_11_12_NAMES)+ def test_no_copy_claims_polaris_11_12(self, name):+ answers = {where: fn(name) for where, fn in _all_copies().items()}+ assert set(answers.values()) == {None}, f"{name!r} was claimed: {answers}"++ @pytest.mark.parametrize("name,_expected", _RDNA1_NAMES)+ def test_the_polaris_row_is_correct_alone_in_every_regex_copy(self, name, _expected):+ """The same standalone check as above, for the two PowerShell copies.++ Row order masks a missing guard identically there, and the .ps1 tables are+ maintained by hand alongside the Python one, so a guard dropped from just+ those two is invisible to every other test in this file. PowerShell's+ -match and Python's re agree on (?!0), which is what makes checking the+ extracted pattern here meaningful.+ """+ for where, rows in (+ (+ "install.ps1",+ _ps_rows(_ps_block(_normalised(_INSTALL_PS1), "$unsupportedNameArchTable = @(")),+ ),+ (+ "studio/setup.ps1",+ _ps_rows(_ps_block(_normalised(_SETUP_PS1), "$unsupportedNameArchTable = @(")),+ ),+ ):+ pattern = next(p for p, arch in rows if arch == "gfx803")+ assert (+ re.search(pattern, name, re.IGNORECASE) is None+ ), f"{where}: the Polaris pattern claims the RDNA 1 name {name!r} when matched alone"++ @pytest.mark.parametrize(+ "path,fn",+ [+ (_INSTALL_SH, "_infer_unsupported_amd_gfx_arch_from_gpu_name"),+ (_SETUP_SH, "_setup_unsupported_gfx_from_name"),+ ],+ ids = ["install.sh", "studio/setup.sh"],+ )+ def test_the_shell_case_arms_keep_polaris_last(self, path, fn):+ """In the shell copies, ORDER is the correctness mechanism, so pin it.++ `case` globs have no negative lookahead, so the *"RX 570"* arm cannot be+ made safe on its own the way the Python and PowerShell (?!0) rows can. The+ only thing stopping it from swallowing an "RX 5700 XT" is that every RDNA 1+ arm is matched first. That makes arm order load-bearing rather than+ cosmetic, and a reorder is otherwise a silent regression, so assert it+ directly instead of leaving it to the behavioural test alone.+ """+ rows = _sh_rows(_sh_function_body(path.read_text(encoding = "utf-8"), fn))+ arches = [arch for _patterns, arch in rows]+ assert "gfx803" in arches, f"{path.name}: no Polaris arm"+ assert arches[-1] == "gfx803", (+ f"{path.name}: the Polaris arm must stay last, after every RDNA 1 arm; "+ f"arm order is {arches}"+ )++ def test_gfx803_is_not_routable(self):+ """The scope guard, restated for the new arch: gfx803 must stay absent from+ the wheel-index map, or a messaging row becomes an install change."""+ assert "gfx803" not in stack_mod._GFX_TO_AMD_INDEX_ARCHdiff --git a/tests/studio/install/test_rocm_arch_table_parity.py b/tests/studio/install/test_rocm_arch_table_parity.pyindex 6bbb3238c9e..ec65ac6c791 100644--- a/tests/studio/install/test_rocm_arch_table_parity.py+++ b/tests/studio/install/test_rocm_arch_table_parity.py@@ -12,7 +12,7 @@ The same three tables are hand-copied into up to seven places each:GPU name -> gfx install.sh (_infer_amd_gfx_arch_from_gpu_name)install.sh (case "$_gpu_disp_mkt", detection banner + env tip)- studio/setup.sh (case "$_setup_mkt")+ studio/setup.sh (_setup_supported_gfx_from_name)install.ps1 ($nameArchTable)studio/setup.ps1 ($nameArchTable)studio/install_python_stack.py (_WIN_GPU_NAME_ARCH_TABLE)@@ -378,7 +378,7 @@ def _name_tables() -> dict[str, object]:install_sh, '"$_gpu_disp_mkt"', "_gpu_disp_gfx"),"studio/setup.sh": _name_table_sh_case(- _SETUP_SH.read_text(encoding = "utf-8"), '"$_setup_mkt"', "_setup_gfx"+ _SETUP_SH.read_text(encoding = "utf-8"), '"$_sup_gfx_in"', "_sup_gfx_out"),"install.ps1": _name_table_ps(_INSTALL_PS1),"studio/setup.ps1": _name_table_ps(_SETUP_PS1),diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.pyindex 4e0f0424244..e1e2612723a 100644--- a/tests/studio/install/test_rocm_support.py+++ b/tests/studio/install/test_rocm_support.py@@ -2050,22 +2050,126 @@ class TestInstallShStructure:"""An explicit UNSLOTH_TORCH_INDEX_URL/_FAMILY CPU pin is a request, nota detection failure: the */cpu wheel note must report the pin instead ofclaiming ROCm/HIP is unusable, the WSL setup guidance must be skipped,- and the gpu summary must not label a pinned AMD host "no usable ROCm"."""+ and the gpu summary must not label a pinned AMD host "no usable ROCm".++ The property is ORDER: the pin arm opens the chain the message sits in, so+ a pinned host never reaches the message. This used to be approximated by a+ character window before the message, which is a different claim -- it is a+ budget on how much source may sit between the two, and every arm added to+ the chain eats into it. #8529 added an unsupported-arch arm and pushed the+ real distance to ~1121, so the window had to grow 400 -> 1400 for reasons+ that had nothing to do with what the test is for. Walk the enclosing+ if/elif chains instead: no distance, nothing to re-tune.+ """sh_path = PACKAGE_ROOT / "install.sh"source = sh_path.read_text(encoding = "utf-8")- note = source.find('substep "AMD GPU detected, but no usable ROCm/HIP install')- assert note != -1- assert (- '[ "$_torch_index_pinned" = true ]' in source[note - 400 : note]- ), "the */cpu note must check the explicit pin before diagnosing ROCm"+ self._assert_guarded_by_pin_arm(+ source,+ 'substep "AMD GPU detected, but no usable ROCm/HIP install',+ 'substep "CPU-only PyTorch (index pinned via UNSLOTH_TORCH_INDEX_URL / _FAMILY)."',+ "elif _has_amd_rocm_gpu; then",+ "the */cpu note must check the explicit pin before diagnosing ROCm",+ )assert ('[ "$OS" = "wsl" ] && [ "$_torch_index_pinned" = false ]' in source), "ROCm-on-WSL guidance is detection advice; skip it for pinned installs"- summary = source.find('step "gpu" "AMD GPU (no usable ROCm -- CPU fallback)"')- assert summary != -1- assert (- '[ "$_torch_index_pinned" = true ]' in source[summary - 700 : summary]- ), "the gpu summary must not claim no usable ROCm for a pinned index"+ self._assert_guarded_by_pin_arm(+ source,+ 'step "gpu" "AMD GPU (no usable ROCm -- CPU fallback)"',+ 'step "gpu" "AMD GPU (torch index pinned: $_torch_index_leaf)"',+ "else",+ "the gpu summary must not claim no usable ROCm for a pinned index",+ )++ _PIN_ARM = 'if [ "$_torch_index_pinned" = true ]'++ # `fi` as a command of its own: at the start of the line, or after a `;`. install.sh+ # closes chains inline too (`else :; fi`), and such a closure is invisible to a+ # startswith("fi") test, leaving a closed chain looking open across the message.+ _CLOSER = re.compile(r"(?:^|;)\s*fi\b")++ # install.sh indents in 4-space steps, so a closure less than one step deeper than the+ # arm closes the arm's own chain (or an enclosing one) rather than something nested in+ # it. Comparing against the step, not the exact indent, keeps a `fi` re-indented by a+ # space or two counting as the closure it is.+ _INDENT_STEP = 4++ @staticmethod+ def _indent(line):+ return len(line) - len(line.lstrip())++ @classmethod+ def _assert_guarded_by_pin_arm(cls, source, needle, pinned_note, arm, message):+ """Assert ``needle`` sits in the ``arm`` arm of a still-open chain whose+ first arm is the pin check and whose pin arm says ``pinned_note``.++ Deliberately local rather than a whole-file walk of if/elif/fi. install.sh+ embeds awk programs and PowerShell in quoted blocks, all of which contain+ their own `if (...)`, and it closes some chains with a trailing `; fi`; a+ global keyword walk mis-nests on both and can end up satisfying this guard+ from an unrelated chain. Indentation is the structure install.sh is written+ in and needs no parse: find the pin arm above the message, then require the+ chain it opens to still be open (nothing closes it before the message) and+ to have moved on to another arm (an `elif`/`else` at its indent).++ The pin arm has to be the exact whole line and the arm the message sits in+ has to be the exact expected one, or "a chain opened by something that+ mentions the pin" is enough to pass: a never-firing `&& [ ... ]` extension+ of the condition, or a decoy chain left open across the message with the+ real guard deleted, both read as guards otherwise. And a guard that routes+ pinned hosts to an empty arm still suppresses the message, so the pin arm+ must be checked to carry its own note.+ """+ lines = source.splitlines()+ # Skip comments: a commented-out `substep` is not a message users ever see.+ hits = [+ i+ for i, line in enumerate(lines)+ if needle in line and not line.lstrip().startswith("#")+ ]+ assert len(hits) == 1, f"expected exactly one {needle!r} in install.sh, found {len(hits)}"+ message_line = hits[0]++ opens = [i for i in range(message_line) if lines[i].strip() == cls._PIN_ARM + "; then"]+ assert opens, f"{message}\nno pin check appears anywhere above the message"+ pin_line = opens[-1]+ indent = cls._indent(lines[pin_line])+ between = range(pin_line + 1, message_line)++ closed = [+ i + 1+ for i in between+ if cls._CLOSER.search(lines[i].strip())+ and cls._indent(lines[i]) < indent + cls._INDENT_STEP+ ]+ assert not closed, (+ f"{message}\ninstall.sh:{pin_line + 1} opens on the pin check but the chain "+ f"closes at install.sh:{closed[0]}, before the message at "+ f"install.sh:{message_line + 1}, so the two are unrelated"+ )+ later_arms = [+ i+ for i in between+ if re.match(r"^(elif|else)\b", lines[i].strip()) and cls._indent(lines[i]) == indent+ ]+ assert later_arms, (+ f"{message}\nthe message at install.sh:{message_line + 1} is inside the pin "+ f"arm opened at install.sh:{pin_line + 1}, so a pinned host still reaches it"+ )+ # The last arm before the message is the one the message is actually in.+ enclosing_arm = lines[later_arms[-1]].strip()+ assert enclosing_arm == arm, (+ f"{message}\nthe message at install.sh:{message_line + 1} sits in "+ f"`{enclosing_arm}` at install.sh:{later_arms[-1] + 1}, not in the expected "+ f"`{arm}`, so the chain guarding it is not the one this test describes"+ )+ pin_body = lines[pin_line + 1 : later_arms[0]]+ assert any(+ pinned_note in line and not line.lstrip().startswith("#") for line in pin_body+ ), (+ f"{message}\nthe pin arm at install.sh:{pin_line + 1} no longer says "+ f"{pinned_note!r}, so a pinned host is told nothing at all"+ )_ROCM_VERSION_SOURCES = ("_rocm_tag_from_amd_smi",@@ -2659,11 +2763,10 @@ class TestInstallShStructure:assert all(version_fns), "ROCm version helpers not found in install.sh"with tempfile.TemporaryDirectory() as d:# Neutralise the host's real ROCm: the version chain reads- # /opt/rocm/.info/version directly (no tool to shim), which resolves- # a tag on a real ROCm box and skips the no-version endpoint under- # test. Same path-substitution technique as the KFD topology tests.- # The read moved into _rocm_tag_from_version_file, so the rewrite has to- # land on the helper text; applying it to fn alone is a no-op.+ # /opt/rocm/.info/version directly (no tool to shim), which resolves a tag on+ # a real ROCm box and skips the no-version endpoint under test. The read lives+ # in _rocm_tag_from_version_file, so the rewrite has to land on the helper+ # text; applying it to fn alone is a no-op.version_fns = [body.replace("/opt/rocm/.info/version", Path(d, "no-rocm-version").as_posix())for body in version_fnsdiff --git a/tests/studio/install/test_unsupported_arch_routing_guards_8529.py b/tests/studio/install/test_unsupported_arch_routing_guards_8529.pynew file mode 100644index 00000000000..8a040251922--- /dev/null+++ b/tests/studio/install/test_unsupported_arch_routing_guards_8529.py@@ -0,0 +1,864 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The one safety property behind the #8529 unsupported-arch table: it is MESSAGING.++The table added for #8529 (and extended for #8458) names AMD generations ROCm+PyTorch does not cover: gfx1010 / gfx1011 / gfx1012 (RDNA 1, Navi 10/14) and+gfx803 (Polaris 10/20/30). Every one of those must keep landing on CPU torch. If+any of them ever reaches an AMD per-arch wheel index, the fix stops being a+wording change: pip would install a repo.amd.com wheel built for another arch and+the user gets an import-time HIP failure instead of a slow-but-working CPU stack.++test_rdna1_unsupported_message_8529.py already asserts that property, but only+against the SHAPE of one Python dict (`_GFX_TO_AMD_INDEX_ARCH`). Mutation testing+showed three real routing changes that the whole suite still passes:++* an extra `gfx803|gfx1010|gfx1011|gfx1012) echo gfx103X-all ;;` arm in install.sh's+ `_amd_arch_index_family_for_gfx`, which sends UNSLOTH_ROCM_GFX_ARCH=gfx803 to+ https://repo.amd.com/rocm/whl/gfx103X-all/ instead of the CPU index;+* an extra `"gfx803" = "gfx110X-all"` entry in `$archFamilyMap`, in install.ps1 or+ studio/setup.ps1 (only ever caught transitively, and only when the two copies+ disagreed with each other);+* a behavioural bypass inside `_amd_arch_index_url` / `_windows_rocm_index_url`+ that hands back a family the dict does not contain, which a shape assertion on+ the dict cannot see at all.++So the tests below ask each source the routing question the installer asks it, in+that source's own language: the Python functions are CALLED, install.sh's case+table is EXECUTED under sh, and the PowerShell maps are read as maps (and, where+pwsh exists, evaluated). Every group carries a positive control, because "no AMD+index came back" is also what a renamed or unparsed table returns.+"""++import importlib.util+import os+import re+import shutil+import subprocess+import textwrap+import sys+from pathlib import Path+from unittest.mock import patch++import pytest+++PACKAGE_ROOT = Path(__file__).resolve().parents[3]++_INSTALL_SH = PACKAGE_ROOT / "install.sh"+_INSTALL_PS1 = PACKAGE_ROOT / "install.ps1"+_SETUP_SH = PACKAGE_ROOT / "studio" / "setup.sh"+_SETUP_PS1 = PACKAGE_ROOT / "studio" / "setup.ps1"+_STACK_PY = PACKAGE_ROOT / "studio" / "install_python_stack.py"+++def _load_stack_module():+ spec = importlib.util.spec_from_file_location("studio_install_python_stack_routing", _STACK_PY)+ assert spec is not None and spec.loader is not None+ mod = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = mod+ spec.loader.exec_module(mod)+ return mod+++stack_mod = _load_stack_module()+++# The four arches the messaging table owns. Nothing here may produce an index.+_UNSUPPORTED_ARCHES = ["gfx803", "gfx1010", "gfx1011", "gfx1012"]++# The same arches as the installers may actually receive them. UNSLOTH_ROCM_GFX_ARCH+# is user-typed (so any case), and a gcnArchName copied out of hipinfo/rocminfo carries+# the target features ("gfx1010:xnack-"), which is why the override reader lowercases+# and splits on ":". A routing bypass written against a prefix would take these too.+_UNSUPPORTED_ARCH_INPUTS = (+ _UNSUPPORTED_ARCHES+ + [a.upper() for a in _UNSUPPORTED_ARCHES]+ + [f"{a}:xnack-" for a in _UNSUPPORTED_ARCHES]+)++# Arches that MUST route, so that "no index" cannot pass for the right answer when the+# table has been renamed, emptied or parsed wrong. gfx1030 is RDNA 2 (RX 6800 XT) and+# gfx1100 is RDNA 3 (RX 7900 XTX); both ship AMD wheels today.+_ROUTABLE_ARCHES = [("gfx1030", "gfx103X-all"), ("gfx1100", "gfx110X-all")]+++# ── The Python resolvers, called rather than inspected ───────────────────────++[email protected](autouse = True)+def _no_index_mirror():+ """Both resolvers honour a mirror override, and a host that has one set would+ answer with its URL instead of repo.amd.com. Clear them so the assertions below+ are about the arch tables and not about the environment running the suite."""+ with patch.dict(os.environ, {}, clear = False):+ for _v in ("UNSLOTH_AMD_ROCM_MIRROR", "UNSLOTH_ROCM_WINDOWS_MIRROR"):+ os.environ.pop(_v, None)+ yield+++class TestPythonIndexResolversAreAskedDirectly:+ """`_GFX_TO_AMD_INDEX_ARCH` is where the answer SHOULD come from, but the callers+ go through `_amd_arch_index_url` / `_windows_rocm_index_url`, and only those two+ decide what pip is pointed at. Ask them."""++ @pytest.mark.parametrize("arch", _UNSUPPORTED_ARCH_INPUTS)+ @pytest.mark.parametrize("is_windows", [False, True], ids = ["linux", "windows"])+ def test_no_unsupported_arch_gets_an_index_url(self, arch, is_windows):+ # IS_WINDOWS is read inside _amd_arch_index_url, so both platform arms are+ # reachable from this host; the Windows arm is the one #8529 was filed from.+ with patch.object(stack_mod, "IS_WINDOWS", is_windows):+ url = stack_mod._amd_arch_index_url(arch)+ assert url is None, f"{arch} was routed to {url!r}; it must fall through to CPU torch"++ @pytest.mark.parametrize("arch", _UNSUPPORTED_ARCH_INPUTS)+ def test_no_unsupported_arch_gets_a_windows_index_url(self, arch):+ """The Windows resolver on its own: install_python_stack calls it directly at+ the Windows torch site, not only through _amd_arch_index_url."""+ url = stack_mod._windows_rocm_index_url(arch)+ assert url is None, f"{arch} was routed to {url!r}"++ @pytest.mark.parametrize("arch", _UNSUPPORTED_ARCH_INPUTS)+ @pytest.mark.parametrize("is_windows", [False, True], ids = ["linux", "windows"])+ def test_no_unsupported_arch_reaches_repo_amd_com(self, arch, is_windows):+ """The same claim stated as the consequence, so that a resolver which starts+ returning some other truthy non-index string still fails here."""+ with patch.object(stack_mod, "IS_WINDOWS", is_windows):+ url = stack_mod._amd_arch_index_url(arch) or ""+ assert "repo.amd.com" not in url, f"{arch} reaches an AMD wheel index: {url!r}"++ @pytest.mark.parametrize("arch,family", _ROUTABLE_ARCHES)+ @pytest.mark.parametrize("is_windows", [False, True], ids = ["linux", "windows"])+ def test_a_covered_arch_still_gets_its_index(self, arch, family, is_windows):+ """The positive control. Without it every assertion above passes on a build+ where the resolvers were gutted to `return None`."""+ with patch.object(stack_mod, "IS_WINDOWS", is_windows):+ url = stack_mod._amd_arch_index_url(arch)+ assert url is not None, f"{arch} lost its wheel index"+ assert url.endswith(f"/{family}/"), f"{arch} routed to {url!r}, expected the {family} index"++ @pytest.mark.parametrize("arch", _UNSUPPORTED_ARCHES)+ def test_no_unsupported_arch_is_a_key_of_the_family_map(self, arch):+ """The shape half, kept alongside the behavioural one: a table entry and a+ code bypass are different mistakes and each should name itself."""+ assert arch not in stack_mod._GFX_TO_AMD_INDEX_ARCH+++# ── install.sh's case table, executed under sh ───────────────────────────────+++def _sh_function_body(source: str, name: str) -> str:+ """Same extraction as test_rdna1_unsupported_message_8529.py: take the function+ verbatim from the installer so the shell evaluates the shipped text, not a+ Python re-implementation of it."""+ needle = f"{name}() {{"+ start = source.find(needle)+ assert start != -1, f"{name}() not found"+ depth = 0+ i = start + len(needle) - 1+ while i < len(source):+ if source[i] == "{":+ depth += 1+ elif source[i] == "}":+ depth -= 1+ if depth == 0:+ return source[start : i + 1]+ i += 1+ raise AssertionError(f"unterminated {name}()")+++def _run_sh_index_family(arch: str) -> "tuple[int, str]":+ body = _sh_function_body(+ _INSTALL_SH.read_text(encoding = "utf-8"), "_amd_arch_index_family_for_gfx"+ )+ script = f'{body}\n_amd_arch_index_family_for_gfx "$1"\n'+ out = subprocess.run(+ ["sh", "-c", script, "sh", arch],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 30,+ )+ return out.returncode, out.stdout.strip()++[email protected](os.name == "nt", reason = "POSIX shell only")[email protected](shutil.which("sh") is None, reason = "no POSIX sh on this host")+class TestInstallShIndexFamilyRuns:+ """install.sh picks the Linux AMD index from `_amd_arch_index_family_for_gfx`, and+ its three call sites treat a non-zero return as "no AMD wheels, use CPU". An arm+ added there is invisible to every Python-side assertion, so run the real case."""++ @pytest.mark.parametrize("arch", _UNSUPPORTED_ARCH_INPUTS)+ def test_no_unsupported_arch_yields_a_family(self, arch):+ rc, out = _run_sh_index_family(arch)+ assert rc != 0 and out == "", (+ f"install.sh maps {arch} to the {out!r} index family, so "+ f"UNSLOTH_ROCM_GFX_ARCH={arch} would install a repo.amd.com wheel built "+ f"for another arch instead of CPU PyTorch"+ )++ @pytest.mark.parametrize("arch,family", _ROUTABLE_ARCHES)+ def test_a_covered_arch_still_yields_its_family(self, arch, family):+ """The positive control: proves the function was found, sourced and reached."""+ rc, out = _run_sh_index_family(arch)+ assert (rc, out) == (0, family), f"{arch} resolved to {out!r} (rc {rc})"++ def test_the_index_selector_is_still_the_function_under_test(self):+ """The extraction above is only meaningful while install.sh actually asks this+ function; a renamed selector would leave the tests green against dead code."""+ src = _INSTALL_SH.read_text(encoding = "utf-8").replace("\r\n", "\n")+ calls = len(+ re.findall(r"^\s*[^#\n]*_amd_arch_index_family_for_gfx \"\$", src, re.MULTILINE)+ )+ assert calls >= 3, f"install.sh calls the index-family selector {calls} times, expected 3"+++# ── install.sh's whole index selector, executed under sh ─────────────────────+++# What get_torch_index_url calls that is not in the two functions extracted below. Each+# stub is the shape of a host with an AMD GPU, no NVIDIA GPU and no readable ROCm+# userspace, the arrangement that carries a user-pinned arch all the way to the routing+# decision. The probe stub reproduces the override arm of the real _probe_amd_gfx_arch+# so a case-shifted pin arrives at the selector as it would on a real host.+_INDEX_URL_STUBS = """+uname() { case "$1" in -m) echo x86_64 ;; *) echo Linux ;; esac; }+_has_usable_nvidia_gpu() { return 1; }+_has_amd_rocm_gpu() { return 0; }+_probe_amd_gfx_arch() { printf '%s\\n' "${UNSLOTH_ROCM_GFX_ARCH:-}" | tr '[:upper:]' '[:lower:]'; }+_infer_linux_amd_gfx_arch() { printf '%s\\n' "${UNSLOTH_ROCM_GFX_ARCH:-}"; }+_infer_linux_unsupported_amd_gfx_arch() { return 1; }+_detect_rocm_version_tag() { [ -n "${_STUB_ROCM_TAG:-}" ] && printf '%s\\n' "$_STUB_ROCM_TAG"; }+"""+++def _run_sh_get_torch_index_url(arch: str, rocm_tag: str = "") -> "tuple[str, str]":+ """Run install.sh's real get_torch_index_url with UNSLOTH_ROCM_GFX_ARCH=arch."""+ src = _INSTALL_SH.read_text(encoding = "utf-8")+ script = (+ _sh_function_body(src, "_amd_arch_index_family_for_gfx")+ + "\n"+ + _sh_function_body(src, "get_torch_index_url")+ + "\n"+ + _INDEX_URL_STUBS+ + "\nget_torch_index_url\n"+ )+ env = dict(os.environ)+ # The two pins short-circuit the whole selector, and a mirror override would+ # rewrite the base out from under the assertions.+ for _v in (+ "UNSLOTH_TORCH_INDEX_URL",+ "UNSLOTH_TORCH_INDEX_FAMILY",+ "UNSLOTH_PYTORCH_MIRROR",+ "UNSLOTH_AMD_ROCM_MIRROR",+ ):+ env.pop(_v, None)+ env["UNSLOTH_ROCM_GFX_ARCH"] = arch+ env["_STUB_ROCM_TAG"] = rocm_tag+ out = subprocess.run(+ ["sh", "-c", script],+ stdout = subprocess.PIPE,+ stderr = subprocess.PIPE,+ text = True,+ env = env,+ timeout = 60,+ )+ return out.stdout.strip(), out.stderr++[email protected](os.name == "nt", reason = "POSIX shell only")[email protected](shutil.which("sh") is None, reason = "no POSIX sh on this host")+class TestInstallShIndexSelectorRuns:+ """The case table above is only one of get_torch_index_url's decisions, and the+ function is what install.sh actually calls. An arch test written straight into+ the selector -- a `case "$_amd_gfx_probe" in gfx1010) ...` shortcut ahead of the+ family lookup -- leaves the case table innocent and still routes the card. So ask+ the selector itself, with the arch pinned the way a user of an uncovered card is+ told to pin it."""++ @pytest.mark.parametrize("arch", _UNSUPPORTED_ARCH_INPUTS)+ def test_no_unsupported_arch_leaves_the_cpu_index(self, arch):+ url, err = _run_sh_get_torch_index_url(arch)+ assert url.endswith(+ "/cpu"+ ), f"UNSLOTH_ROCM_GFX_ARCH={arch} selected {url!r}, not the CPU index"+ assert "repo.amd.com" not in (+ url + err+ ), f"UNSLOTH_ROCM_GFX_ARCH={arch} reaches an AMD wheel index: {url!r}"++ def test_a_covered_arch_is_recognised_by_the_selector(self):+ """First positive control: the selector really does tell the two apart. A+ covered arch reaches the per-arch handoff (the reroute below get_torch_index_url+ turns that into the repo.amd.com URL; the selector's own job is to name it),+ and no unsupported arch does -- so "everything lands on /cpu" cannot be what+ makes the bans above pass."""+ covered, covered_err = _run_sh_get_torch_index_url("gfx1030")+ assert covered.endswith("/cpu"), f"gfx1030 selected {covered!r}"+ assert (+ "AMD per-arch wheels" in covered_err+ ), "gfx1030 no longer reaches the per-arch handoff, so the bans above prove nothing"+ for arch in _UNSUPPORTED_ARCHES:+ _url, err = _run_sh_get_torch_index_url(arch)+ assert (+ "AMD per-arch wheels" not in err+ ), f"{arch} reaches the per-arch handoff, which reroutes to repo.amd.com"++ def test_the_selector_still_reaches_its_amd_branch(self):+ """Second positive control: on the same stubbed host with a readable ROCm+ version the selector returns a ROCm index, which it can only do by running the+ AMD branch the test above depends on."""+ url, _err = _run_sh_get_torch_index_url("gfx1030", rocm_tag = "rocm6.4")+ assert url.endswith("/rocm6.4"), f"the AMD branch was not reached: {url!r}"+++# ── studio/setup.sh: the unsupported lookup is report-only ───────────────────+++# setup.sh forwards `--rocm-gfx "$_setup_gfx"` to install_llama_prebuilt.py and the whisper+# installer, and keys the supported table on $_setup_mkt. The unsupported lookup exists to+# print a line, so its result must not flow into either: assigning it to _setup_gfx passes+# every arch assertion in this file and still ships --rocm-gfx gfx803.+_SETUP_SH_UNSUPPORTED_HELPERS = ("_setup_unsupported_gfx_any", "_setup_unsupported_gfx_from_name")+++_ROUTED_SETUP_VARS = ("_setup_gfx", "_setup_mkt")++# Assignment targets anywhere in a line, not only at its start: the lookup is+# captured mid-condition (`elif _setup_unsup_gfx=$(...); then`), which is exactly+# where the routed variable would be substituted for the report-only one.+_SH_ASSIGN_TARGET = re.compile(r"(?:^|[;&|(]|\s)([A-Za-z_][A-Za-z0-9_]*)=")+++def test_setup_sh_never_feeds_the_unsupported_lookup_into_a_routed_variable():+ src = _SETUP_SH.read_text(encoding = "utf-8").replace("\r\n", "\n")+ code = [line for line in src.splitlines() if not line.lstrip().startswith("#")]+ captures = [+ line.strip()+ for line in code+ if any(h in line for h in _SETUP_SH_UNSUPPORTED_HELPERS) and _SH_ASSIGN_TARGET.search(line)+ ]+ # Positive control: the report-only capture is still there to be checked.+ assert captures, "studio/setup.sh no longer captures the unsupported lookup at all"+ for line in captures:+ for target in _SH_ASSIGN_TARGET.findall(line):+ assert target not in _ROUTED_SETUP_VARS, (+ f"studio/setup.sh writes the unsupported lookup into ${target}: {line!r}. "+ f"That variable selects --rocm-gfx for the llama.cpp and whisper installers, "+ f"so an uncovered card would be built for as if it had wheels"+ )+ # The same ban one hop later: capturing the lookup in its own variable and then+ # copying that into the routed one is the same mutation written in two lines.+ relayed = [+ line.strip()+ for line in code+ if re.search(+ r"(?:^|[;&|(]|\s)(?:" + "|".join(_ROUTED_SETUP_VARS) + r")=[^\n]*_setup_unsup", line+ )+ ]+ assert (+ not relayed+ ), f"studio/setup.sh relays the unsupported lookup into a routed variable: {relayed}"+ forwards = [line for line in code if "--rocm-gfx" in line and "_setup_gfx" in line]+ assert forwards, "studio/setup.sh no longer forwards --rocm-gfx from $_setup_gfx (renamed?)"++[email protected]("arch", _UNSUPPORTED_ARCHES)+def test_setup_sh_never_assigns_an_unsupported_arch_to_the_routed_variable(arch):+ """The same property from the other end: whatever names the unsupported arches,+ none of them may be written into the variable that becomes --rocm-gfx."""+ src = _SETUP_SH.read_text(encoding = "utf-8").replace("\r\n", "\n")+ hits = [+ line.strip()+ for line in src.splitlines()+ if not line.lstrip().startswith("#") and re.search(r"_setup_gfx=[^\n]*" + arch, line)+ ]+ assert not hits, f"studio/setup.sh routes {arch} into --rocm-gfx: {hits}"+++# ── The PowerShell copies of the same map ────────────────────────────────────+++def _ps_block(source: str, header: str, opener: str, closer: str) -> str:+ """The literal `@{...}` or `@(...)` that `header` opens, balanced."""+ start = source.find(header)+ assert start != -1, f"{header} not found"+ i = source.find(opener, start)+ depth = 0+ while i < len(source):+ if source[i] == opener:+ depth += 1+ elif source[i] == closer:+ depth -= 1+ if depth == 0:+ return source[start : i + 1]+ i += 1+ raise AssertionError(f"unterminated {header}")+++def _ps_table_arches(path: Path, header: str, opener: str, closer: str) -> "list[str]":+ """Every gfx arch one PowerShell routing table routes, read out of its own file.+ CRLF-normalised first: install.ps1 and setup.ps1 both ship CRLF."""+ return _ps_arches(+ _ps_block(path.read_text(encoding = "utf-8").replace("\r\n", "\n"), header, opener, closer)+ )+++def _ps_arches(block: str) -> "list[str]":+ """Every gfx arch the block routes: hashtable keys ("gfx1030" = ...) and plain+ array members alike. Comments are stripped first, since both blocks annotate+ their rows with generation names.++ Quoting is not part of the property: PowerShell takes 'gfx803', "gfx803" and a+ bare gfx803 as the same key or member, so all three have to be read, or a row+ added in the other style is silently reported as absent. The trailing guard+ stops a family VALUE from being misread as a routed arch: gfx103X-all shares a+ prefix with gfx103, and only the full token is a routing key."""+ stripped = "\n".join(line.split("#", 1)[0] for line in block.splitlines())+ keys = re.findall(r"""['"]?(gfx[0-9a-z]+)['"]?\s*=(?!=)""", stripped)+ if keys:+ return keys+ return re.findall(r"""['"]?(gfx[0-9a-z]+)(?![0-9a-zA-Z-])""", stripped)+++# Each PowerShell routing table, checked in its OWN file. The parity test in+# test_rocm_arch_table_parity.py compares the copies against each other, which stays+# green when the same wrong arch is added to all of them.+_PS_TABLES = [+ (_INSTALL_PS1, "$archFamilyMap = @{", "{", "}"),+ (_SETUP_PS1, "$archFamilyMap = @{", "{", "}"),+ (_SETUP_PS1, "$_rocmWheelArches = @(", "(", ")"),+]+_PS_TABLE_IDS = [f"{p.name}:{h.split()[0][1:]}" for p, h, _o, _c in _PS_TABLES]++# Every way PowerShell can change $archFamilyMap: a keyed assignment, a rebind, a+# merge, or one of the IDictionary mutators. Reads (`.ContainsKey($a)`, `$map[$a]`+# as a value) deliberately do not match.+_PS_MAP_WRITE = re.compile(+ r"\$archFamilyMap\s*(?:\[[^\]]*\]\s*=(?!=)|=(?!=)|\+=|\.\s*(?:Add|Remove|Clear|set_Item)\s*\()",+ re.IGNORECASE,+)+++class TestPowerShellRoutingTables:+ @pytest.mark.parametrize("path,header,opener,closer", _PS_TABLES, ids = _PS_TABLE_IDS)+ def test_the_table_parses_and_still_routes_a_covered_arch(self, path, header, opener, closer):+ """The positive control for the two tests below, which are both bans and would+ otherwise pass on a block that parsed to nothing."""+ arches = _ps_table_arches(path, header, opener, closer)+ assert arches, f"{path.name}: {header} parsed empty (moved or renamed?)"+ for _arch, _family in _ROUTABLE_ARCHES:+ assert _arch in arches, f"{path.name}: {header} no longer routes {_arch}"++ @pytest.mark.parametrize("arch", _UNSUPPORTED_ARCHES)+ @pytest.mark.parametrize("path,header,opener,closer", _PS_TABLES, ids = _PS_TABLE_IDS)+ def test_no_unsupported_arch_is_routed(self, path, header, opener, closer, arch):+ arches = _ps_table_arches(path, header, opener, closer)+ assert arch not in arches, (+ f"{path.name}: {header} routes {arch}, so a card the installer is about to "+ f"call uncovered would be sent to an AMD wheel index"+ )++ @pytest.mark.parametrize("path", [_INSTALL_PS1, _SETUP_PS1], ids = lambda p: p.name)+ def test_the_family_map_is_never_written_to_after_it_is_declared(self, path):+ """The tests above read the `@{...}` literal, which is the whole map only for+ as long as nothing edits it later. `$archFamilyMap["gfx803"] = "gfx103X-all"`+ (or `.Add("gfx803", ...)`) anywhere below the declaration routes gfx803 in the+ real installer while leaving the literal, and so every assertion on it, intact.+ The map is a constant table; require it to stay one."""+ src = path.read_text(encoding = "utf-8").replace("\r\n", "\n")+ block = _ps_block(src, "$archFamilyMap = @{", "{", "}")+ assert _PS_MAP_WRITE.search(block), (+ f"{path.name}: the write pattern no longer matches the declaration itself, "+ f"so it would not match an added row either"+ )+ rest = src.replace(block, "", 1)+ writes = [+ line.strip()+ for line in rest.splitlines()+ if _PS_MAP_WRITE.search(line) and not line.lstrip().startswith("#")+ ]+ assert not writes, (+ f"{path.name}: $archFamilyMap is modified after its declaration ({writes}), "+ f"so the routing this file checks is not the routing the installer performs"+ )+ # Positive control: the map is still consulted below the declaration, so the+ # region searched above is the one a late addition would have to live in.+ assert (+ "$archFamilyMap.ContainsKey" in rest+ ), f"{path.name}: nothing reads $archFamilyMap any more (renamed or removed?)"++[email protected](shutil.which("pwsh") is None, reason = "pwsh not available")+class TestPowerShellMapEvaluated:+ """The gate the installers actually run is `$archFamilyMap.ContainsKey($arch)`.+ Let PowerShell answer it, so a row this file's regex misreads (a differently+ quoted key, a splatted addition) is not silently treated as absent."""++ @pytest.mark.parametrize("path", [_INSTALL_PS1, _SETUP_PS1], ids = lambda p: p.name)+ def test_containskey_is_false_for_every_unsupported_arch(self, path):+ src = path.read_text(encoding = "utf-8").replace("\r\n", "\n")+ block = _ps_block(src, "$archFamilyMap = @{", "{", "}")+ probes = ", ".join(f'"{a}"' for a in _UNSUPPORTED_ARCHES)+ script = (+ f"{block}\n"+ f"foreach ($a in @({probes})) {{\n"+ f' if ($archFamilyMap.ContainsKey($a)) {{ "ROUTED:$a" }}\n'+ f"}}\n"+ f"if ($archFamilyMap.ContainsKey('gfx1030')) {{ 'CONTROL_OK' }}\n"+ )+ out = subprocess.run(+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 120,+ )+ assert out.returncode == 0, f"{path.name}: the map did not evaluate under pwsh"+ printed = out.stdout.split()+ assert "CONTROL_OK" in printed, f"{path.name}: gfx1030 lost its wheel index"+ routed = [line for line in printed if line.startswith("ROUTED:")]+ assert not routed, f"{path.name}: {routed} reach an AMD wheel index"++ def test_contains_is_false_for_every_unsupported_arch(self):+ """setup.ps1 gates the Windows AMD wheels on `$_rocmWheelArches -contains $arch`+ rather than on the map, so that list needs the same evaluated check: a member+ added in a quoting style this file's regex does not read would otherwise pass+ the textual ban above and still route the arch."""+ src = _SETUP_PS1.read_text(encoding = "utf-8").replace("\r\n", "\n")+ block = _ps_block(src, "$_rocmWheelArches = @(", "(", ")")+ probes = ", ".join(f'"{a}"' for a in _UNSUPPORTED_ARCHES)+ script = (+ f"{block}\n"+ f"foreach ($a in @({probes})) {{\n"+ f' if ($_rocmWheelArches -contains $a) {{ "ROUTED:$a" }}\n'+ f"}}\n"+ f"if ($_rocmWheelArches -contains 'gfx1030') {{ 'CONTROL_OK' }}\n"+ )+ out = subprocess.run(+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 120,+ )+ assert out.returncode == 0, "setup.ps1: $_rocmWheelArches did not evaluate under pwsh"+ printed = out.stdout.split()+ assert "CONTROL_OK" in printed, "setup.ps1: gfx1030 lost its wheel index"+ routed = [line for line in printed if line.startswith("ROUTED:")]+ assert not routed, f"setup.ps1: {routed} reach an AMD wheel index"+++# ── The second, independent arch to repo.amd.com gate ────────────────────────+++# The Strix reroute picks a per-arch index without consulting either family map, so it is+# a routing site the assertions above cannot see. Reachability is narrow, but "narrow" is+# not the property this file defends, and the literal is one line per source.+_STRIX_SITES = [+ (_INSTALL_SH, r"^\s*(gfx[0-9a-z|]+)\)\s+_strix_gfx="),+ (_STACK_PY, r"^\s*_strix_gfx\s*=\s*\{([^}]*)\}"),+]+_STRIX_IDS = [p.name for p, _r in _STRIX_SITES]++[email protected]("source_path,pattern", _STRIX_SITES, ids = _STRIX_IDS)+def test_the_strix_reroute_names_no_unsupported_arch(source_path, pattern):+ src = source_path.read_text(encoding = "utf-8")+ hits = re.findall(pattern, src, re.MULTILINE)+ assert hits, f"{source_path.name}: the Strix reroute arm was not found; was it renamed?"+ named = " ".join(hits)+ for arch in _UNSUPPORTED_ARCHES:+ assert arch not in named, (+ f"{source_path.name}: {arch} reached the Strix per-arch reroute, which "+ f"builds a repo.amd.com URL without going through the family map"+ )+ # Positive control: the arm really does name the arches it is supposed to route.+ assert "gfx1151" in named, f"{source_path.name}: extraction matched nothing useful"+++# ── The CPU summary must blame the card the fallback is actually about ───────+++_SUMMARY_GUARD_ANCHOR = "_covered_disp_gfx=$(_infer_linux_amd_gfx_arch"+++def _summary_guard_snippet() -> str:+ """The peer guard as install.sh ships it. Extracted rather than retyped, so gutting+ it there fails here."""+ src = _INSTALL_SH.read_text(encoding = "utf-8").replace("\r\n", "\n")+ start = src.find(_SUMMARY_GUARD_ANCHOR)+ assert start != -1, "install.sh: the CPU summary's peer guard was not found"+ end = src.find('if [ -n "$_unsup_disp_gfx" ]; then', start)+ assert end != -1, "install.sh: the guard no longer feeds the unsupported-card arm"+ return src[start:end]+++def _run_summary_guard(tmp_path, lspci_lines: "list[str]") -> str:+ """Which of the two CPU-summary arms wins on a host whose lspci says this."""+ source = _INSTALL_SH.read_text(encoding = "utf-8")+ funcs = "\n".join(+ _sh_function_body(source, name)+ for name in (+ "_infer_amd_gfx_arch_from_gpu_name",+ "_infer_unsupported_amd_gfx_arch_from_gpu_name",+ "_infer_linux_unsupported_amd_gfx_arch",+ "_infer_linux_amd_gfx_arch",+ "_amd_arch_index_family_for_gfx",+ "_amd_gpu_present_via_pci",+ )+ )+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir(exist_ok = True)+ fixture = tmp_path / "lspci.txt"+ fixture.write_text("\n".join(lspci_lines) + "\n", encoding = "utf-8")+ lspci = bin_dir / "lspci"+ lspci.write_text(f'#!/bin/sh\ncat "{fixture}"\n', encoding = "utf-8")+ lspci.chmod(0o755)+ script = (+ f"{funcs}\n{_summary_guard_snippet()}\n"+ 'if [ -n "$_unsup_disp_gfx" ]; then echo "UNCOVERED $_unsup_disp_gfx"; '+ "else echo GENERIC; fi\n"+ )+ out = subprocess.run(+ ["sh", "-c", script],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 60,+ env = {"PATH": f"{bin_dir}:/usr/bin:/bin"},+ )+ return out.stdout.strip()+++_RX_5700 = (+ "01:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. "+ "[AMD/ATI] Navi 10 [Radeon RX 5700/5700 XT] [1002:731f]"+)+_RX_580 = (+ "01:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. "+ "[AMD/ATI] Ellesmere [Radeon RX 580] [1002:67df]"+)+_RX_7900 = (+ "02:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. "+ "[AMD/ATI] Navi 31 [Radeon RX 7900 XT/7900 XTX] [1002:744c]"+)++[email protected](os.name == "nt", reason = "POSIX shell only")[email protected](shutil.which("sh") is None, reason = "no POSIX sh on this host")+class TestInstallShCpuSummaryBlamesTheRightCard:+ """The end-of-run summary reaches its lspci lookup even when the arch read fine, so+ unlike the arm in get_torch_index_url it has no empty-probe gate. An RX 5700 beside+ an RX 7900 lands on CPU whenever the 7900's ROCm is too old, and naming the 5700+ there would replace the upgrade advice with advice false for the card at fault."""++ @pytest.mark.parametrize("lines", [[_RX_5700], [_RX_580]], ids = ["rx5700", "rx580"])+ def test_a_lone_uncovered_card_is_still_named(self, tmp_path, lines):+ """The positive control, and the case the whole PR exists for."""+ verdict = _run_summary_guard(tmp_path, lines)+ assert verdict.startswith(+ "UNCOVERED"+ ), f"install.sh's CPU summary no longer names the uncovered card: {verdict!r}"++ @pytest.mark.parametrize(+ "lines",+ [[_RX_5700, _RX_7900], [_RX_7900, _RX_5700], [_RX_580, _RX_7900]],+ ids = ["5700-first", "7900-first", "580-plus-7900"],+ )+ def test_a_covered_peer_keeps_the_summary_quiet(self, tmp_path, lines):+ verdict = _run_summary_guard(tmp_path, lines)+ assert verdict == "GENERIC", (+ "install.sh's CPU summary blamed an uncovered card on a host that also has "+ f"a covered one, so the real reason for the CPU fallback is hidden: {verdict!r}"+ )++ def test_a_covered_card_alone_says_nothing_about_uncovered_arches(self, tmp_path):+ assert _run_summary_guard(tmp_path, [_RX_7900]) == "GENERIC"+++# ── setup.sh's KFD report must blame the right card too ──────────────────────+++_SETUP_SH_FUNCS = (+ "_setup_supported_gfx_from_name",+ "_setup_unsupported_gfx_from_name",+ "_setup_unsupported_gfx_any",+)+++def _run_setup_report(+ tmp_path,+ lspci_lines: "list[str]",+ mkt: str = "",+) -> str:+ """setup.sh's lookup on the KFD path, where no market name is available and the+ lookup falls back to lspci. Same fixtures as the install.sh summary above."""+ source = _SETUP_SH.read_text(encoding = "utf-8")+ funcs = "\n".join(textwrap.dedent(_sh_function_body(source, name)) for name in _SETUP_SH_FUNCS)+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir(exist_ok = True)+ fixture = tmp_path / "lspci.txt"+ fixture.write_text("\n".join(lspci_lines) + "\n", encoding = "utf-8")+ lspci = bin_dir / "lspci"+ lspci.write_text(f'#!/bin/sh\ncat "{fixture}"\n', encoding = "utf-8")+ lspci.chmod(0o755)+ script = (+ f'{funcs}\nif _g=$(_setup_unsupported_gfx_any "{mkt}"); then echo "UNCOVERED $_g"; '+ "else echo GENERIC; fi\n"+ )+ out = subprocess.run(+ ["sh", "-c", script],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 60,+ env = {"PATH": f"{bin_dir}:/usr/bin:/bin"},+ )+ return out.stdout.strip()++[email protected](os.name == "nt", reason = "POSIX shell only")[email protected](shutil.which("sh") is None, reason = "no POSIX sh on this host")+class TestSetupShReportBlamesTheRightCard:+ """The KFD fallback detects the GPU with neither rocminfo nor amd-smi, so the report+ reads lspci and takes the first uncovered adapter. On a host whose RX 5700 enumerates+ before an RX 7900 that is the wrong card: selecting the 7900 and setting its arch+ does reach the supported path, so "no override can help" is false there."""++ @pytest.mark.parametrize("lines", [[_RX_5700], [_RX_580]], ids = ["rx5700", "rx580"])+ def test_a_lone_uncovered_card_is_still_named(self, tmp_path, lines):+ assert _run_setup_report(tmp_path, lines).startswith("UNCOVERED")++ @pytest.mark.parametrize(+ "lines",+ [[_RX_5700, _RX_7900], [_RX_7900, _RX_5700], [_RX_580, _RX_7900]],+ ids = ["5700-first", "7900-first", "580-plus-7900"],+ )+ def test_a_covered_peer_keeps_the_report_quiet(self, tmp_path, lines):+ assert (+ _run_setup_report(tmp_path, lines) == "GENERIC"+ ), "setup.sh named an uncovered card on a host that also carries a covered one"++ @pytest.mark.parametrize(+ "mkt",+ ["", "AMD Radeon Graphics", "Advanced Micro Devices, Inc. [AMD/ATI]"],+ ids = ["kfd-no-name", "generic-name", "vendor-only"],+ )+ def test_an_unmapped_market_name_still_reaches_the_lspci_scan(self, tmp_path, mkt):+ """rocminfo can hand back a nonempty name that maps to nothing. Returning that+ failure ended the lookup, so the lspci scan never ran and the report fell back to+ the plain "AMD ROCm" line this change exists to replace."""+ assert _run_setup_report(tmp_path, [_RX_5700], mkt).startswith(+ "UNCOVERED"+ ), f"an unmapped market name ({mkt!r}) hides an uncovered card lspci can see"++ def test_a_mapped_market_name_short_circuits(self):+ """The name still wins when it maps: no lspci call is needed or made."""+ source = _SETUP_SH.read_text(encoding = "utf-8")+ funcs = "\n".join(+ textwrap.dedent(_sh_function_body(source, name)) for name in _SETUP_SH_FUNCS+ )+ out = subprocess.run(+ ["sh", "-c", f'{funcs}\n_setup_unsupported_gfx_any "AMD Radeon RX 580"\n'],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 30,+ # sh itself still has to be found; the point is that lspci is not on PATH,+ # so a fallback that ran would come back empty and fail this.+ env = {"PATH": os.path.dirname(shutil.which("sh") or "/bin")},+ )+ assert out.stdout.strip() == "gfx803"++ def test_an_unmapped_name_beside_a_covered_peer_stays_quiet(self, tmp_path):+ verdict = _run_setup_report(tmp_path, [_RX_5700, _RX_7900], "AMD Radeon Graphics")+ assert verdict == "GENERIC"++ @pytest.mark.parametrize(+ "lines",+ [[_RX_5700, _RX_7900], [_RX_7900, _RX_5700]],+ ids = ["5700-first", "7900-first"],+ )+ def test_a_named_hit_is_guarded_by_the_peers_too(self, tmp_path, lines):+ """amd-smi reports ONE market name, the first device's, so on a mixed host the+ name itself is the uncovered card. Accepting it before the peer scan put the+ false verdict back through the other door."""+ verdict = _run_setup_report(tmp_path, lines, "AMD Radeon RX 5700 XT")+ assert verdict == "GENERIC", f"a named hit skipped the covered-peer guard: {verdict!r}"++ def test_a_named_hit_survives_a_host_with_no_lspci(self, tmp_path):+ """The guard must not become a silencer: with no adapter list there is no peer to+ find, and the single-card host this report exists for still has to be told."""+ source = _SETUP_SH.read_text(encoding = "utf-8")+ funcs = "\n".join(+ textwrap.dedent(_sh_function_body(source, name)) for name in _SETUP_SH_FUNCS+ )+ out = subprocess.run(+ [+ "sh",+ "-c",+ f'{funcs}\n_setup_unsupported_gfx_any "AMD Radeon RX 5700 XT"\n',+ ],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 30,+ env = {"PATH": os.path.dirname(shutil.which("sh") or "/bin")},+ )+ assert out.stdout.strip() == "gfx1010"++ def test_the_supported_matcher_still_answers(self, tmp_path):+ """Positive control on the extracted table: without it the guard above would be+ vacuous, since a matcher that never matches also keeps the report quiet."""+ source = _SETUP_SH.read_text(encoding = "utf-8")+ script = (+ textwrap.dedent(_sh_function_body(source, "_setup_supported_gfx_from_name"))+ + '\n_setup_supported_gfx_from_name "AMD Radeon RX 7900 XTX"\n'+ )+ out = subprocess.run(["sh", "-c", script], stdout = subprocess.PIPE, text = True, timeout = 30)+ assert out.stdout.strip() == "gfx1100"++[email protected](os.name == "nt", reason = "POSIX shell only")[email protected](shutil.which("sh") is None, reason = "no POSIX sh on this host")+ "url,family,pinned",+ [+ ("", "", False),+ (" ", "", False),+ ("\t\n ", " ", False),+ ("https://example/gfx1010", "", True),+ ("", "rocm7.2", True),+ ],+ ids = ["unset", "spaces", "mixed-blank", "url", "family"],+)+def test_setup_sh_treats_a_blank_index_pin_as_unset(url, family, pinned):+ """get_torch_index_url trims both variables and treats a blank one as unset, so a+ blank value here must not suppress the CPU-only warning. The two lines that decide+ it are taken from setup.sh rather than retyped."""+ src = _SETUP_SH.read_text(encoding = "utf-8").replace("\r\n", "\n")+ start = src.index('_setup_unsup_pin="${UNSLOTH_TORCH_INDEX_URL')+ end = src.index('if [ -n "$_setup_unsup_pin" ]', start)+ snippet = textwrap.dedent(src[start:end])+ out = subprocess.run(+ [+ "sh",+ "-c",+ f'{snippet}\nif [ -n "$_setup_unsup_pin" ]; then echo PINNED; else echo UNSET; fi\n',+ ],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ timeout = 30,+ env = {+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),+ "UNSLOTH_TORCH_INDEX_URL": url,+ "UNSLOTH_TORCH_INDEX_FAMILY": family,+ },+ )+ assert out.stdout.strip() == ("PINNED" if pinned else "UNSET"), (+ f"setup.sh read UNSLOTH_TORCH_INDEX_URL={url!r} / _FAMILY={family!r} as "+ f"{out.stdout.strip()}"+ )diff --git a/tests/studio/test_rdna1_unsupported_message_8529.ps1 b/tests/studio/test_rdna1_unsupported_message_8529.ps1new file mode 100644index 00000000000..c9625ab94ab--- /dev/null+++ b/tests/studio/test_rdna1_unsupported_message_8529.ps1@@ -0,0 +1,407 @@+#!/usr/bin/env pwsh+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# Behavioural test for the RDNA 1 "detected but not covered by ROCm" wording in+# install.ps1 and studio/setup.ps1 (issue #8529). The reporter's card is an RX 5700 XT+# (Navi 10, gfx1010). AMD's Windows torch indexes are gfx103X/110X/1150/1151/120X only,+# so CPU torch is correct and stays; the bug was telling them to install the HIP SDK or+# set UNSLOTH_ROCM_GFX_ARCH, neither of which can succeed on gfx1010.+#+# The Python suite evaluates the table with Python's `re`; this runs it under the .NET+# engine that ships it, the only place -match semantics are real. Fixtures are raw WMI+# adapter names, which is what the table is matched against.+#+# Run: pwsh -NoProfile -File tests/studio/test_rdna1_unsupported_message_8529.ps1++$ErrorActionPreference = "Stop"+$root = (Resolve-Path ([System.IO.Path]::Combine($PSScriptRoot, "..", ".."))).Path++$failures = 0+function Check($name, $cond) {+ if ($cond) { Write-Host " PASS $name" }+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }+}++# Returns the source text of a variable assignment. The caller Invoke-Expression's+# it at script scope; doing that inside a function would lose the value on return.+function Get-AssignmentSource($path, $varName) {+ $errors = $null+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($path, [ref]$null, [ref]$errors)+ if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "$path has parse errors" }+ $hits = $ast.FindAll({ param($n)+ $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and+ $n.Left.Extent.Text -eq $varName+ }, $true)+ if ($hits.Count -lt 1) { throw "expected $varName in $path, found none" }+ return $hits[0].Extent.Text+}++foreach ($file in @("install.ps1", "studio/setup.ps1")) {+ $path = Join-Path $root $file+ Write-Host ""+ Write-Host "=== $file ==="++ Invoke-Expression (Get-AssignmentSource $path '$unsupportedNameArchTable')++ # The same first-match-wins loop both installers run over the table.+ function Resolve-Unsupported($name) {+ foreach ($row in $unsupportedNameArchTable) {+ if ($name -match $row.P) { return $row.A }+ }+ return $null+ }++ # --- the reporter's card, and the rest of RDNA 1 ---------------------------+ Check "RX 5700 XT -> gfx1010" ((Resolve-Unsupported "AMD Radeon RX 5700 XT") -eq 'gfx1010')+ Check "RX 5700 -> gfx1010" ((Resolve-Unsupported "AMD Radeon RX 5700") -eq 'gfx1010')+ Check "RX 5600 XT -> gfx1010" ((Resolve-Unsupported "AMD Radeon RX 5600 XT") -eq 'gfx1010')+ Check "Radeon Pro 5600 XT -> gfx1010" ((Resolve-Unsupported "AMD Radeon Pro 5600 XT") -eq 'gfx1010')+ Check "Radeon Pro V520 -> gfx1011" ((Resolve-Unsupported "AMD Radeon Pro V520") -eq 'gfx1011')+ Check "Radeon Pro 5600M -> gfx1011" ((Resolve-Unsupported "AMD Radeon Pro 5600M") -eq 'gfx1011')+ Check "RX 5500 XT -> gfx1012" ((Resolve-Unsupported "AMD Radeon RX 5500 XT") -eq 'gfx1012')+ # The professional boards LLVM's table omits, mapped from libdrm data/amdgpu.ids read+ # against pci.ids, which files 7312/7310 under Navi 10 and 7340/7341/7347/734f under+ # Navi 14.+ Check "Radeon Pro W5700 -> gfx1010" ((Resolve-Unsupported "AMD Radeon Pro W5700") -eq 'gfx1010')+ Check "Radeon Pro W5700X -> gfx1010" ((Resolve-Unsupported "AMD Radeon Pro W5700X") -eq 'gfx1010')+ Check "Radeon Pro W5500 -> gfx1012" ((Resolve-Unsupported "AMD Radeon Pro W5500") -eq 'gfx1012')+ Check "Radeon Pro W5500M -> gfx1012" ((Resolve-Unsupported "AMD Radeon Pro W5500M") -eq 'gfx1012')+ Check "Radeon Pro W5300M -> gfx1012" ((Resolve-Unsupported "AMD Radeon Pro W5300M") -eq 'gfx1012')+ Check "RX 5300 -> gfx1012" ((Resolve-Unsupported "AMD Radeon RX 5300") -eq 'gfx1012')+ Check "RX 5300M -> gfx1012" ((Resolve-Unsupported "AMD Radeon RX 5300M") -eq 'gfx1012')+ # The Mac Pro MPX boards, pci.ids 7319 and 731b under Navi 10. The only Navi 10+ # retail parts whose name carries neither "RX 5700" nor a W prefix.+ Check "Radeon Pro 5700 XT -> gfx1010" ((Resolve-Unsupported "AMD Radeon Pro 5700 XT") -eq 'gfx1010')+ Check "Radeon Pro 5700 -> gfx1010" ((Resolve-Unsupported "AMD Radeon Pro 5700") -eq 'gfx1010')+ # The W-series that DOES have wheels: "W5700" must not be read out of "W7500".+ Check "PRO W7500 unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon PRO W7500"))+ Check "PRO W6500 unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon PRO W6500"))+ Check "PRO W6400 unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon PRO W6400"))++ # --- Polaris, the second card in the cluster (#8458) ----------------------+ # #8458 is an RX 580: Polaris 20, gfx803, also with no ROCm PyTorch wheels.+ Check "RX 580 -> gfx803" ((Resolve-Unsupported "AMD Radeon RX 580") -eq 'gfx803')+ Check "RX 580 Series -> gfx803" ((Resolve-Unsupported "AMD Radeon RX 580 Series") -eq 'gfx803')+ Check "RX 570 -> gfx803" ((Resolve-Unsupported "AMD Radeon RX 570") -eq 'gfx803')+ Check "RX 590 -> gfx803" ((Resolve-Unsupported "AMD Radeon RX 590") -eq 'gfx803')+ Check "RX 480 -> gfx803" ((Resolve-Unsupported "AMD Radeon RX 480") -eq 'gfx803')+ Check "RX 470 -> gfx803" ((Resolve-Unsupported "AMD Radeon RX 470") -eq 'gfx803')+ # The Polaris 10 workstation boards, grouped on Ellesmere by pci.ids. Their names+ # carry no RX number, so the consumer rows could never have reached them.+ Check "Radeon Pro WX 7100 -> gfx803" ((Resolve-Unsupported "AMD Radeon Pro WX 7100") -eq 'gfx803')+ Check "Radeon Pro WX 5100 -> gfx803" ((Resolve-Unsupported "AMD Radeon Pro WX 5100") -eq 'gfx803')++ # Polaris 11/12 is a different die and is deliberately absent: this table is+ # only worth having while it never guesses an arch.+ Check "RX 560 unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon RX 560"))+ Check "RX 550 unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon RX 550"))+ Check "RX 460 unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon RX 460"))++ # "RX 570" is a prefix of "RX 5700" and "RX 550" of "RX 5500". Matched ALONE: table+ # order already keeps RDNA 1 names away from Polaris, so a dropped (?!0) guard+ # changes nothing observable until someone reorders.+ $polarisPattern = @($unsupportedNameArchTable | Where-Object { $_.A -eq 'gfx803' })[0].P+ foreach ($rdna1 in @("AMD Radeon RX 5700 XT", "AMD Radeon RX 5700", "AMD Radeon RX 5500 XT")) {+ Check "Polaris pattern alone does not claim '$rdna1'" (-not ($rdna1 -match $polarisPattern))+ }++ # --- and nothing else -----------------------------------------------------+ # A hit here would print "ROCm does not cover this" at a card that has wheels.+ Check "RX 9070 XT unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon RX 9070 XT"))+ Check "RX 9060 XT unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon RX 9060 XT"))+ Check "RX 7900 XTX unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon RX 7900 XTX"))+ Check "RX 6800 XT unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon RX 6800 XT"))+ Check "8060S Graphics unclaimed" ($null -eq (Resolve-Unsupported "AMD Radeon 8060S Graphics"))+ Check "RTX 4090 unclaimed" ($null -eq (Resolve-Unsupported "NVIDIA GeForce RTX 4090"))++ # --- the supported table must still miss RDNA 1 ---------------------------+ # The behavioural half: CPU fallback is correct here and must not move.+ Invoke-Expression (Get-AssignmentSource $path '$nameArchTable')+ function Resolve-Supported($name) {+ foreach ($row in $nameArchTable) {+ if ($name -match $row.P) { return $row.A }+ }+ return $null+ }+ Check "RX 5700 XT gets no supported arch" ($null -eq (Resolve-Supported "AMD Radeon RX 5700 XT"))+ Check "RX 5500 XT gets no supported arch" ($null -eq (Resolve-Supported "AMD Radeon RX 5500 XT"))+ Check "RX 9070 XT still maps to gfx1201" ((Resolve-Supported "AMD Radeon RX 9070 XT") -eq 'gfx1201')++ # No arch may appear in both tables: one routes to a wheel index, the other+ # exists precisely because nothing routes.+ $bothTables = @($unsupportedNameArchTable | ForEach-Object { $_.A }) |+ Where-Object { @($nameArchTable | ForEach-Object { $_.A }) -contains $_ }+ Check "the two tables share no arch" ($bothTables.Count -eq 0)++ # --- the wording, in the source that prints it ----------------------------+ # CRLF normalisation is mandatory: both files ship CRLF, so any needle+ # spanning a line break never matches the raw text.+ $src = (Get-Content -Raw $path) -replace "`r`n", "`n"++ # Every ordering claim below is preceded by a "was found" guard, so a renamed+ # branch fails loudly instead of comparing two -1s and passing vacuously.+ $unsupArm = 'step "gpu" "AMD GPU detected ($'+ $unknownArm = 'step "gpu" "AMD GPU detected -- arch unknown"'+ Check "unsupported gpu arm is present" ($src.Contains($unsupArm))+ Check "arch-unknown gpu arm is present" ($src.Contains($unknownArm))+ Check "unsupported arm precedes arch-unknown arm" `+ ($src.IndexOf($unsupArm) -ge 0 -and $src.IndexOf($unknownArm) -ge 0 -and+ $src.IndexOf($unsupArm) -lt $src.IndexOf($unknownArm))++ # Scoped to the card: a host can pair an uncovered GPU with a covered one, so the+ # sentence says what is true of the card just named and claims nothing beyond it.+ $disclaimer = "setting UNSLOTH_ROCM_GFX_ARCH will not change that for it."+ Check "unsupported arm says the override cannot help" ($src.Contains($disclaimer))++ $sdkAdvice = 'substep "Could not determine the GPU arch'+ Check "HIP SDK advice still exists for genuinely unknown cards" ($src.Contains($sdkAdvice))+ Check "HIP SDK advice comes after the unsupported arm" `+ ($src.IndexOf($sdkAdvice) -ge 0 -and $src.IndexOf($unsupArm) -ge 0 -and+ $src.IndexOf($unsupArm) -lt $src.IndexOf($sdkAdvice))++ # --- the Vulkan pointer (#8458) -------------------------------------------+ # Torch ends on these cards; llama.cpp does not. Asserted against PRINTING lines only:+ # every phrase below also appears in the comments explaining the branch, so a file-wide+ # search stays green after the message is gutted. Single quotes count too -- the setter+ # is a literal so PowerShell prints $env:... instead of expanding it.+ $emitted = @(($src -split "`n") | Where-Object {+ $_ -match 'substep\s+["'']' -and $_.TrimStart() -notmatch '^#'+ })+ Check "the emitted advice offers Vulkan" `+ (($emitted -join "`n").Contains("through Vulkan"))+ # PowerShell syntax, verified by PARSING rather than matching text: a bare+ # UNSLOTH_LLAMA_CPP_BACKEND=vulkan parses as a command name, so a user who pastes+ # it sets nothing and gets the same CPU bundle -- the #8458 failure mode again.+ $setter = '$env:UNSLOTH_LLAMA_CPP_BACKEND = "vulkan"'+ Check "the emitted advice teaches the current spelling" `+ (($emitted -join "`n").Contains($setter))+ $posix = @($emitted | Where-Object { $_ -match 'UNSLOTH_LLAMA_CPP_BACKEND=vulkan' })+ Check "no emitted line gives a POSIX assignment" ($posix.Count -eq 0)+ $setterAst = [System.Management.Automation.Language.Parser]::ParseInput(+ $setter, [ref]$null, [ref]$null)+ Check "the taught setter parses as an assignment, not a command" `+ (@($setterAst.FindAll({ param($n)+ $n -is [System.Management.Automation.Language.AssignmentStatementAst] }, $true)).Count -eq 1)++ # UNSLOTH_FORCE_VULKAN still works, but force_vulkan_requested() resolves+ # UNSLOTH_LLAMA_CPP_BACKEND first and only falls back to the legacy name, so new+ # text must not spread that spelling. Scoped to emitters: setup.ps1 legitimately+ # READS the legacy variable for back-compat and that is untouched here.+ $teachesLegacy = @($emitted | Where-Object { $_ -match 'UNSLOTH_FORCE_VULKAN' })+ Check "the legacy spelling is not taught" ($teachesLegacy.Count -eq 0)++ # WHEN to set it, per SITE: install.ps1 prints this advice twice, so a file-level+ # "install time" search is satisfied by whichever site still has it.+ $mentions = @(0..($emitted.Count - 1) | Where-Object {+ $emitted[$_].Contains($setter)+ })+ Check "at least one site names the Vulkan variable" ($mentions.Count -ge 1)+ foreach ($i in $mentions) {+ $window = ($emitted[$i..([Math]::Min($i + 3, $emitted.Count - 1))]) -join "`n"+ Check "the advice at emitted line $($i + 1) says it applies at install time" `+ ($window.Contains("install time"))+ }++ # --- which arm actually WINS, evaluated rather than read ------------------+ # Source offsets cannot see a branch made unreachable by an earlier condition.+ # Parse the real if/elseif chain, evaluate each clause in order against the #8529+ # host -- RX 5700 XT, no ROCm runtime, HIP SDK installed because the old advice+ # said to -- and assert the FIRST true clause is the unsupported arm.+ $chainAst = [System.Management.Automation.Language.Parser]::ParseFile(+ $path, [ref]$null, [ref]$null)+ $chains = @($chainAst.FindAll({ param($n)+ $n -is [System.Management.Automation.Language.IfStatementAst] -and+ ($n.Clauses | Where-Object { $_.Item1.Extent.Text -match 'ROCmUnsupportedGfxArch' }) -and+ ($n.Clauses | Where-Object { $_.Item2.Extent.Text -match 'step "gpu"' })+ }, $true))+ Check "the gpu report chain was found" ($chains.Count -eq 1)+ if ($chains.Count -eq 1) {+ $HasNvidiaSmi = $false+ $script:IsIntelXpu = $false+ $HasROCm = $false+ $HipSdkInstalled = $true # they installed it because we told them to+ $ROCmGpuLabel = "AMD Radeon RX 5700 XT"+ $ROCmGfxArch = $null+ $script:ROCmGfxArch = $null+ $ROCmUnsupportedGfxArch = "gfx1010"+ $script:ROCmUnsupportedGfxArch = "gfx1010"+ $winner = -1+ $unsupIdx = -1+ for ($c = 0; $c -lt $chains[0].Clauses.Count; $c++) {+ $cond = $chains[0].Clauses[$c].Item1.Extent.Text+ if ($cond -match 'ROCmUnsupportedGfxArch' -and $cond -notmatch '-not') { $unsupIdx = $c }+ if ($winner -lt 0 -and [bool](& ([scriptblock]::Create($cond)))) { $winner = $c }+ }+ Check "the unsupported arm exists in the chain" ($unsupIdx -ge 0)+ Check "an RDNA 1 host with the HIP SDK installed reaches the unsupported arm" `+ ($winner -eq $unsupIdx)+ }++ # The scope guard, in source: the unsupported lookup must never assign the+ # arch the installers route on.+ $tableSrc = Get-AssignmentSource $path '$unsupportedNameArchTable'+ Check "the table assigns no routable arch" (-not ($tableSrc -match 'gfx1(0[3-9]|1|2)'))++ # The table has to be READ, not just declared: everything above evaluates it in+ # isolation, so a lookup never wired to the message arms would sail through.+ $consumer = if ($file -eq "install.ps1") {+ 'foreach ($row in $unsupportedNameArchTable) {'+ } else {+ '-Table $unsupportedNameArchTable'+ }+ Check "the table is consumed by the arch resolver" ($src.Contains($consumer))+ Check "the resolver feeds the variable the arms read" ($src -match 'ROCmUnsupportedGfxArch\s*=\s*(\$row\.A|Get-GfxArchFromGpuName)')+}++# studio/setup.ps1 reads $script:ROCmUnsupportedGfxArch in the unconditional ROCm summary,+# so it must be initialised OUTSIDE the `-not $HasNvidiaSmi` block. Left inside, an NVIDIA+# host never defines it and a caller's Set-StrictMode turns the summary into an aborting+# undefined-variable error (unslothai#8529).+$setupSrc = (Get-Content -Raw (Join-Path $root "studio/setup.ps1")) -replace "`r`n", "`n"+# Ask the parser, not the text: the file has three `-not $HasNvidiaSmi` blocks, so a+# line-order check picks the wrong one and brace counting trips over braces in strings.+# The invariant is that one assignment is NOT nested in any conditional.+$setupAst = [System.Management.Automation.Language.Parser]::ParseFile(+ (Join-Path $root "studio/setup.ps1"), [ref]$null, [ref]$null)+$assignments = $setupAst.FindAll({+ param($n)+ $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and+ $n.Left.Extent.Text -eq '$script:ROCmUnsupportedGfxArch'+}, $true)+Check "the unsupported-arch assignments were found" ($assignments.Count -gt 0)+$unconditional = @($assignments | Where-Object {+ $p = $_.Parent+ $nested = $false+ while ($null -ne $p) {+ if ($p -is [System.Management.Automation.Language.IfStatementAst]) { $nested = $true; break }+ $p = $p.Parent+ }+ -not $nested+})+Check "the unsupported-arch state is initialised outside every conditional" ($unconditional.Count -gt 0)++# install.ps1's WMI fallback takes adapter [0], so on a host pairing an RX 5700 with an+# RX 7900 the label is the 5700 and "nothing can enable ROCm here" would be false: masking+# to the 7900 and setting gfx1100 installs. Such a host must keep the arch-unknown arm.+# Run the REAL block, pulled out by AST rather than retyped.+Write-Host ""+Write-Host "=== install.ps1 mixed-adapter guard ==="+$installPath = Join-Path $root "install.ps1"+$installAst = [System.Management.Automation.Language.Parser]::ParseFile($installPath, [ref]$null, [ref]$null)+$guardBlocks = @($installAst.FindAll({+ param($n)+ $n -is [System.Management.Automation.Language.IfStatementAst] -and+ $n.Extent.Text.Contains('$unsupportedNameArchTable') -and+ $n.Extent.Text.Contains('$ROCmUnsupportedGfxArch') -and+ $n.Extent.Text.Contains('$wmiAmdNames')+}, $true) | Sort-Object { $_.Extent.Text.Length })+# Requiring $wmiAmdNames is what makes this load-bearing: delete the peer scan and no+# block matches, so this check fails rather than the cases below quietly going vacuous.+Check "the unsupported lookup block consults the peer list" ($guardBlocks.Count -gt 0)++# The cases below inject $wmiAmdNames, so they cannot see whether anything FILLS it.+# Assert the producer separately: the WMI scan must build it from the adapter list it+# indexed, not from the single chosen adapter.+$peerAssign = @($installAst.FindAll({+ param($n)+ $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and+ $n.Left.Extent.Text -eq '$wmiAmdNames' -and+ $n.Right.Extent.Text.Contains('$wmiAdapters')+}, $true))+Check "the WMI scan fills the peer list from every adapter" ($peerAssign.Count -eq 1)++# ...and it must not be gated on $HasROCm. amd-smi can report GPUs with no gfx token and+# only the first market name, which sets $HasROCm with no arch: gated that way the scan+# was skipped and the guard above saw an empty peer list on exactly the multi-GPU host it+# is for. The enclosing if must test the ARCH, which is what decides whether the lookup+# below can run at all.+$peerScanGate = $null+foreach ($assign in $peerAssign) {+ # Walk PAST the inner `if ($wmiGpu)`: the gate under test is the outer one, the only+ # condition on this path that mentions either signal.+ $node = $assign.Parent+ while ($node) {+ if ($node -is [System.Management.Automation.Language.IfStatementAst]) {+ $cond = $node.Clauses[0].Item1.Extent.Text+ if ($cond.Contains('$ROCmGfxArch') -or $cond.Contains('$HasROCm')) {+ $peerScanGate = $cond+ break+ }+ }+ $node = $node.Parent+ }+}+Check "the peer scan is not gated on `$HasROCm" (+ $peerScanGate -and $peerScanGate.Contains('$ROCmGfxArch') -and -not $peerScanGate.Contains('$HasROCm')+)++# studio/setup.ps1 carries the same scan for its own inference, and had the same gate: on+# the amd-smi market-name-only path $script:ROCmGpuLabels held one name, so $gpuNames was+# one entry and the whole host was judged on it. Its inference runs under+# `if (-not $script:ROCmGfxArch)`, so the scan that feeds it must run there too.+$setupPath = Join-Path $root "studio/setup.ps1"+$setupAst = [System.Management.Automation.Language.Parser]::ParseFile($setupPath, [ref]$null, [ref]$null)+$setupPeerAssign = @($setupAst.FindAll({+ param($n)+ $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and+ $n.Left.Extent.Text -eq '$script:ROCmGpuLabels' -and+ $n.Right.Extent.Text.Contains('$wmiGpus')+}, $true))+Check "setup.ps1 fills its peer list from every adapter" ($setupPeerAssign.Count -eq 1)+$setupGate = $null+foreach ($assign in $setupPeerAssign) {+ $node = $assign.Parent+ while ($node) {+ if ($node -is [System.Management.Automation.Language.IfStatementAst]) {+ $cond = $node.Clauses[0].Item1.Extent.Text+ if ($cond.Contains('$script:ROCmGfxArch') -or $cond.Contains('$HasROCm')) {+ $setupGate = $cond+ break+ }+ }+ $node = $node.Parent+ }+}+Check "setup.ps1's peer scan is not gated on `$HasROCm" (+ $setupGate -and $setupGate.Contains('$script:ROCmGfxArch') -and -not $setupGate.Contains('$HasROCm')+)++Invoke-Expression (Get-AssignmentSource $installPath '$nameArchTable')+Invoke-Expression (Get-AssignmentSource $installPath '$unsupportedNameArchTable')++# Driven at SCRIPT scope on purpose. Invoke-Expression inside a function would let the+# block's own `$ROCmUnsupportedGfxArch = $row.A` land in that function's scope, so every+# "claims nothing" case would pass without the guard existing at all.+$guardCases = @(+ # The reporter's host: one RDNA 1 card, nothing else. The verdict must still be reached.+ @{ N = "lone RX 5700 XT is still named gfx1010"+ L = "AMD Radeon RX 5700 XT"; A = @("AMD Radeon RX 5700 XT"); E = 'gfx1010' }+ # The mixed host: adapter 0 is the 5700, adapter 1 has wheels. Stay quiet and keep the+ # arch-unknown arm, which points at the override that really does work there.+ @{ N = "RX 5700 beside an RX 7900 XTX claims nothing"+ L = "AMD Radeon RX 5700 XT"; A = @("AMD Radeon RX 5700 XT", "AMD Radeon RX 7900 XTX"); E = $null }+ @{ N = "RX 580 beside an RX 9070 XT claims nothing"+ L = "AMD Radeon RX 580"; A = @("AMD Radeon RX 580", "AMD Radeon RX 9070 XT"); E = $null }+ # Two uncovered cards are still an uncovered host.+ @{ N = "RX 5700 XT beside an RX 580 is still named"+ L = "AMD Radeon RX 5700 XT"; A = @("AMD Radeon RX 5700 XT", "AMD Radeon RX 580"); E = 'gfx1010' }+ # A peer we cannot map is not a covered peer; it is the unknown the arm already handles.+ @{ N = "RX 5700 XT beside an unmappable Radeon is still named"+ L = "AMD Radeon RX 5700 XT"; A = @("AMD Radeon RX 5700 XT", "AMD Radeon Graphics"); E = 'gfx1010' }+ # The amd-smi paths never enter the WMI scan, so the peer list is empty there.+ @{ N = "an empty peer list does not suppress the verdict"+ L = "AMD Radeon RX 5700 XT"; A = @(); E = 'gfx1010' }+)+$guardSource = $guardBlocks[0].Extent.Text+foreach ($case in $guardCases) {+ $ROCmGfxArch = $null+ $ROCmUnsupportedGfxArch = $null+ $ROCmGpuLabel = $case.L+ $wmiAmdNames = @($case.A)+ Invoke-Expression $guardSource+ Check $case.N ($ROCmUnsupportedGfxArch -eq $case.E)+}++Write-Host ""+if ($failures -gt 0) { Write-Host "$failures check(s) FAILED" -ForegroundColor Red; exit 1 }+Write-Host "All checks passed" -ForegroundColor Greendiff --git a/tests/test_windows_amd_gpu_scan_fallback.py b/tests/test_windows_amd_gpu_scan_fallback.pyindex 7e29611fb0a..1667fbb1619 100644--- a/tests/test_windows_amd_gpu_scan_fallback.py+++ b/tests/test_windows_amd_gpu_scan_fallback.py@@ -95,9 +95,11 @@ def _without_the_array_wraps(src: str) -> str:def _amd_scan_block(src: str) -> str:- """The `if (-not $HasROCm)` WMI fallback: the adapter list the label is read from."""+ """The WMI fallback: the adapter list the label is read from. Gated on the ARCH,+ not on $HasROCm, so the peer list also exists on the amd-smi market-name-only path+ (an arch there is null while $HasROCm is true)."""m = re.search(- r"^ if \(-not \$HasROCm\) \{\n try \{\n.*?^ \}\n",+ r"^ if \(-not \$script:ROCmGfxArch\) \{\n try \{\n.*?^ \}\n",src,re.DOTALL | re.MULTILINE,)@@ -438,10 +440,12 @@ def test_a_user_override_is_the_escape_hatch_under_a_mask(tmp_path):def _installer_scan_block() -> str:- """install.ps1's own `if (-not $HasROCm)` WMI fallback plus the name table it feeds."""+ """install.ps1's own WMI fallback plus the name table it feeds. Gated on the ARCH,+ not on $HasROCm: amd-smi can set the latter with no arch, and the peer list this+ block builds has to exist on that path too."""src = INSTALL_PS1.read_text(encoding = "utf-8")start = src.index(- " if (-not $HasROCm) {\n try {\n # ConfigManagerErrorCode"+ " if (-not $ROCmGfxArch) {\n try {\n # ConfigManagerErrorCode")end = src.index(" # Capture ROCm version for wheel selection", start)return src[start:end]@@ -457,7 +461,10 @@ def _run_installer_scan(tmp_path: Path, adapters: list[tuple[str, int]]) -> dict"\n".join(["$ErrorActionPreference = 'Stop'",- f"function Get-WmiObject {{ param([Parameter(ValueFromRemainingArguments = $true)]$Rest) @({items}) }}",+ # Both names: install.ps1 asks CIM, and the old name throws as it does on+ # PowerShell 7, so a revert fails instead of answering nothing via the catch.+ f"function Get-CimInstance {{ param([Parameter(ValueFromRemainingArguments = $true)]$Rest) @({items}) }}",+ "function Get-WmiObject { throw 'Get-WmiObject is not available in PowerShell 7' }","function substep { param($a, $b) }","$HasROCm = $false","$ROCmGpuLabel = $null",