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
Linux: index AMD visible-device masks by device, and floor gfx1102/RDNA4 to rocm6.4 (#9672)
Leo Borcherding838f4bd61b70
diff --git a/install.sh b/install.shindex bf50697d862..9b1c3bc3435 100755--- a/install.sh+++ b/install.sh@@ -3541,6 +3541,120 @@ _kfd_gfx_targets() {return 0}+# Pair each rocminfo GPU gfx id with its marketing name, not the CPU-first global name (#7307). Blank names keep device ordinals; no GPU keeps the old fallback. Keep in sync with studio/setup.sh.+_rocminfo_gpu_records() {+ awk '+ # Split at the first colon so embedded colons survive.+ function value(line, v) {+ v = line+ sub(/^[^:]*:[[:space:]]*/, "", v)+ gsub(/^[[:space:]]+|[[:space:]]+$/, "", v)+ return v+ }+ /^[[:space:]]*Name:/ {+ # Keep a slot for a nameless GPU.+ if (gfx != "" && !named) { print gfx "|"; gpus++ }+ gfx = ""; named = 0+ name = value($0)+ # Accept target suffixes such as gfx90a:sramecc+, but reject ISA names.+ if (match(name, /^gfx[1-9][0-9a-z][0-9a-z][0-9a-z]?/)) {+ rest = substr(name, RLENGTH + 1)+ if (rest == "" || rest ~ /^[^0-9a-z]/) gfx = substr(name, 1, RLENGTH)+ }+ next+ }+ /^[[:space:]]*Marketing Name:/ {+ mkt = value($0)+ if (gfx != "" && !named) { print gfx "|" mkt; gpus++; named = 1 }+ else if (first == "") first = mkt+ next+ }+ END {+ if (gfx != "" && !named) { print gfx "|"; gpus++ }+ if (gpus == 0 && first != "") print "|" first+ }+ '+}++_amd_smi_hip_order() {+ # POSIX awk forbids a newline in a -v value (fatal under gawk --posix), so records arrive+ # on stdin before the map, sentinel-separated. Line 1 names the index space.+ { printf '%s\n' "$1"; echo "@@hip-map@@"; cat; } | awk '+ function value(line, v) {+ v = line+ sub(/^[^:]*:[[:space:]]*/, "", v)+ gsub(/^[[:space:]]+|[[:space:]]+$/, "", v)+ return v+ }+ function keep( i) { print "discovery"; for (i = 1; i <= r; i++) print rec[i] }+ !split_seen && $0 == "@@hip-map@@" { split_seen = 1; next }+ !split_seen { if ($0 != "") rec[++r] = $0; next }+ /^[[:space:]]*GPU:[[:space:]]*[0-9]/ { n++; hip[n] = -1; next }+ n && tolower($0) ~ /hip.?id/ {+ if (hip[n] < 0) { v = value($0); if (v ~ /^[0-9]+$/) hip[n] = v + 0 }+ next+ }+ END {+ # All or nothing, like get_hip_id_by_gpu_index: a partial or colliding map is not 1:1.+ if (r == 0 || n != r) { keep(); exit }+ for (i = 1; i <= n; i++) {+ if (hip[i] < 0 || hip[i] >= r || (hip[i] in used)) { keep(); exit }+ used[hip[i]] = 1+ out[hip[i]] = rec[i]+ }+ print "hip"+ for (i = 0; i < r; i++) print out[i]+ }+ '+}++# amd-smi enumerates in KFD discovery order while HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES index HIP/ROCr order, and the two disagree on real hardware (MI350X SPX/NPS1), so an untranslated ordinal here can fetch a prebuilt for another card's arch. `amd-smi list -e` is the map AMD publishes for this (HIP_ID, ROCm 6.4.0+), the same field utils/hardware/amd.py get_hip_id_by_gpu_index reads. Keep in sync with studio/setup.sh.+# `gfx|marketing name` records to one arch per adapter, ordinals intact. An unreadable arch+# keeps its slot as `unknown`: dropping it would shift every later device under a mask.+# Prints nothing when NO adapter has an arch, so the caller falls through to the next probe.+_gfx_arch_slots() {+ awk -F'|' '+ NF { rec[n++] = $1; if ($1 != "") any = 1 }+ END {+ if (!any) exit+ for (i = 0; i < n; i++) print (rec[i] == "" ? "unknown" : rec[i])+ }+ '+}++# One `gfx|marketing name` per adapter, in `GPU: N` order, so the mask picks both halves of one device. Was: arch indexed, name always adapter 0's, and on amd-smi 6.1.1, which has no TARGET_GRAPHICS_VERSION, that name is what --rocm-gfx is inferred from. Keep in sync with studio/setup.sh.+_amd_smi_gpu_records() {+ awk '+ function value(line, v) {+ v = line+ sub(/^[^:]*:[[:space:]]*/, "", v)+ gsub(/^[[:space:]]+|[[:space:]]+$/, "", v)+ return v+ }+ function flush() {+ if (started) print gfx "|" mkt+ gfx = ""; mkt = ""+ }+ # amd-smi upper-cases every key (amdsmi_logger.py _capitalize_keys), so match+ # case-folded. Two header shapes: `GPU: 0` opens a keyed block with the arch later,+ # `GPU[0] : gfx1100` IS the record. Matching only the first answered no arch at all.+ /^[[:space:]]*GPU[[:space:]]*[:\[][[:space:]]*[0-9]/ {+ flush(); started = 1+ if (match($0, /gfx[1-9][0-9a-z][0-9a-z][0-9a-z]?/)) gfx = substr($0, RSTART, RLENGTH)+ next+ }+ !started { next }+ tolower($0) ~ /market.?name/ { if (mkt == "") mkt = value($0); next }+ tolower($0) ~ /target.?graphics.?version/ {+ v = value($0)+ if (gfx == "" && v ~ /^gfx[1-9][0-9a-z][0-9a-z][0-9a-z]?$/) gfx = v+ next+ }+ END { flush() }+ '+}++# Physical gfx arch when the ISA probe is an HSA_OVERRIDE_GFX_VERSION spoof (#7331): $1 = the arch inferred from the product name, $2 = the probed gfx token list. Prints the physical arch, or nothing to mean "believe the probe" (the default). Requires ALL of: the override is set; the product name inferred a spoofable RDNA 3.5 APU arch and the probe reported a DIFFERENT one; the probe saw exactly ONE distinct arch (rocminfo repeats the token per agent, so this is a pre-filter, not the safety property); the variable names EXACTLY the arch that was reported, since ROCr can only spoof to the target the variable names; and a source the override cannot reach agrees with the product name, KFD sysfs first, then rocminfo re-run with the variable unset. That keeps a mixed Strix APU plus discrete AMD GPU host out of reach. Corroboration is REQUIRED, with deliberately no "the variable names the reported arch, so assume a spoof" fallback: that shape is identical on a host telling the truth (a real gfx1100 dGPU in a Ryzen AI Max chassis whose owner set the override for unrelated reasons), and rerouting a working machine to the wrong wheels is worse than #7331 itself. Kept in sync with _hsa_spoofed_physical_gfx in studio/install_python_stack.py._hsa_spoofed_physical_gfx() {_hsp_inferred="${1:-}"@@ -4610,6 +4724,10 @@ case "$_torch_index_leaf" inesac_amd_gpu_radeon=false+# Set when the runtime GPU has a generic-wheel floor, rerouted or not; the floor is per arch and the migrated-venv repair below must reuse the same number.+_gfx_rocm64_target=false+_gfx_rocm64_floor_maj=""+_gfx_rocm64_floor_min=""if [ "$_torch_index_pinned" = false ]; then# On the LEAF, like every other index classifier here: the AMD per-arch mirror is https://repo.amd.com/ROCM/whl/gfx120X-all/, so a whole-URL */rocm* glob brands every per-arch reroute as Radeon and the summary then reports repo.radeon.com wheels that were never fetched. The two older per-arch reroutes each clear the flag by hand afterwards; matching the leaf is what stops the next one from having to.case "$_torch_index_leaf" in@@ -4629,31 +4747,62 @@ _rocm_leaf_below() {if [ "$_maj" -eq "$2" ] && [ "$_min" -lt "$3" ]; then return 0; fireturn 1}+# 0 when the venv's torch has no identifiable rocm family at $2.$3 or newer, mirroring _installed_rocm_wheel_is_below in studio/install_python_stack.py+_venv_torch_rocm_below() {+ _vtr_leaf=$("$1" -c 'import re, torch; m = re.search(r"rocm([0-9]+)\.([0-9]+)", getattr(torch, "__version__", "") or ""); print("rocm%s.%s" % m.groups() if m else "")' 2>/dev/null || true)+ [ -n "$_vtr_leaf" ] || return 0+ _rocm_leaf_below "$_vtr_leaf" "$2" "$3"+}+# ── Strix Halo / Strix Point: route to the AMD arch-specific index ───────────# gfx1151/gfx1150 need torch 2.11+rocm7.13 from repo.amd.com/rocm/whl/gfx<arch>/, which carries AMD's real fixes (the rocm7.1 _grouped_mm segfault, moe_utils.py:167, and later Strix kernel bugs). Every generic pytorch.org index below rocm7.13 lacks them, and the Radeon repo can be offline (#7264), so reroute a detected Strix GPU whenever the picked index is older than the arch build; rocm7.13+ already has the fixes.case "$_torch_index_leaf" inrocm[0-9]*)- # Collect every gfx token in rocminfo / amd-smi enumeration order (skipping duplicates), then index by HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES so a mixed Strix iGPU + non-Strix dGPU box where the user selected the dGPU does NOT get rerouted to the Strix per-gfx index. `|| true` on each probe: no gfx match makes grep exit 1, which under set -euo pipefail would abort the installer before the next fallback runs. A user-supplied UNSLOTH_ROCM_GFX_ARCH overrides probing, mirroring setup.sh and the display block.- _gfx_all=$(printf '%s' "${UNSLOTH_ROCM_GFX_ARCH:-}" | tr '[:upper:]' '[:lower:]')+ # Re-declared because test_rocm_support.py lifts this arm out whole: under `set -u` an outside initialiser would abort it instead of routing.+ _gfx_rocm64_target=false+ _gfx_rocm64_floor_maj=""+ _gfx_rocm64_floor_min=""+ # One record per adapter in probe enumeration order, indexed by HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES so the mask selects a CARD. A deduplicated arch list could not: gfx1100 + gfx1100 + gfx1200 ran off the end of a two-entry list, and a Strix iGPU + dGPU box rerouted the selected dGPU to the Strix per-gfx index. `|| true` on each probe so one that finds nothing does not abort the installer under set -euo pipefail before the next fallback. UNSLOTH_ROCM_GFX_ARCH overrides probing, mirroring setup.sh and the display block.+ _gfx_all=$(printf '%s' "${UNSLOTH_ROCM_GFX_ARCH:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')+ # strip a copied hip gcnArchName suffix, matching _gfx906_env below and the python helper+ _gfx_all=${_gfx_all%%:*}+ # which probe answered: only rocminfo is filtered by an rocr mask, so only it can pre-apply one+ _gfx_probe=""+ # Which index space _gfx_all is in: `hip` for rocminfo and for an explicit UNSLOTH_ROCM_GFX_ARCH, which names one arch outright, and for amd-smi only once _amd_smi_hip_order has translated its discovery order.+ _gfx_space=hipif [ -z "$_gfx_all" ] && command -v rocminfo >/dev/null 2>&1; then- _gfx_all=$(rocminfo 2>/dev/null | grep -oE 'gfx[1-9][0-9a-z]{2,3}' || true)+ _gfx_all=$(rocminfo 2>/dev/null | _rocminfo_gpu_records | _gfx_arch_slots || true)+ # rocminfo is an ROCr client, so it enumerates in the order HIP numbers from.+ [ -n "$_gfx_all" ] && { _gfx_probe=rocminfo; _gfx_space=hip; }fiif [ -z "$_gfx_all" ] && command -v amd-smi >/dev/null 2>&1; then- _gfx_all=$(amd-smi list 2>/dev/null | grep -oE 'gfx[1-9][0-9a-z]{2,3}' || true)+ _gfx_records=$(amd-smi list 2>/dev/null | _amd_smi_gpu_records || true)# PowerShell paths also probe `amd-smi static --asic`; mirror it so a host with hipinfo-less amd-smi reports the gfx target.- if [ -z "$_gfx_all" ]; then- _gfx_all=$(amd-smi static --asic 2>/dev/null | grep -oE 'gfx[1-9][0-9a-z]{2,3}' || true)+ # `amd-smi list` may answer ids with no arch (a record per device, arch column empty), so test for an arch, not for records.+ case "$_gfx_records" in *gfx*) ;; *)+ _gfx_records=$(amd-smi static --asic 2>/dev/null | _amd_smi_gpu_records || true) ;;+ esac+ if [ -n "$_gfx_records" ]; then+ # HIP_ID from `amd-smi list -e` maps discovery order onto the order HIP numbers, as the GPU summary below does. The first output line reports which space came back.+ _gfx_smi_out=$(amd-smi list -e 2>/dev/null | _amd_smi_hip_order "$_gfx_records" || true)+ _gfx_space=$(printf '%s\n' "$_gfx_smi_out" | head -n 1)+ _gfx_records=$(printf '%s\n' "$_gfx_smi_out" | tail -n +2)+ _gfx_all=$(printf '%s\n' "$_gfx_records" | _gfx_arch_slots || true)+ [ -n "$_gfx_all" ] && _gfx_probe=amd-smififi# get_torch_index_url reads the arch with ROCR/HIP masks cleared, so a mask hiding every agent (ROCR_VISIBLE_DEVICES=-1) still lands here on a generic rocm index; re-probe unmasked or a masked-out Strix box keeps the broken generic wheels. Partial masks never get here (they enumerate at least one agent above) and keep their selection. ${VAR+x}, not :-, because a SET-but-empty mask also hides every agent and must trigger the re-probe.if [ -z "$_gfx_all" ] && [ -n "${ROCR_VISIBLE_DEVICES+x}${HIP_VISIBLE_DEVICES+x}" ]; thenif command -v rocminfo >/dev/null 2>&1; then- _gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; rocminfo 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' || true)+ _gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; rocminfo 2>/dev/null) | _rocminfo_gpu_records | _gfx_arch_slots || true)+ [ -n "$_gfx_all" ] && _gfx_space=hipfiif [ -z "$_gfx_all" ] && command -v amd-smi >/dev/null 2>&1; then- _gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; amd-smi list 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' || true)+ _gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; amd-smi list 2>/dev/null) | _amd_smi_gpu_records | _gfx_arch_slots || true)[ -z "$_gfx_all" ] && \- _gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; amd-smi static --asic 2>/dev/null) | grep -oE 'gfx[1-9][0-9a-z]{2,3}' || true)+ _gfx_all=$( (unset ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES; amd-smi static --asic 2>/dev/null) | _amd_smi_gpu_records | _gfx_arch_slots || true)+ # Left in discovery space: the single-GPU box this rescue is for routes normally, a mixed one declines below.+ [ -n "$_gfx_all" ] && _gfx_space=discoveryfifi# HSA_OVERRIDE_GFX_VERSION=11.0.0 (the circulated Strix workaround) makes ROCr hand rocminfo the SPOOFED ISA, so a gfx1151 host reports gfx1100 and the Strix case below never matches (#7331). Correct the reading back to the physical arch first, only in the narrow shape that cannot be a real mixed host.@@ -4664,8 +4813,31 @@ case "$_torch_index_leaf" in[ -n "$_spoof_physical" ] && _gfx_all="$_spoof_physical"fi_runtime_gfx=""+ _rocr_unresolved=""if [ -n "$_gfx_all" ]; then- _vis="${HIP_VISIBLE_DEVICES:-${ROCR_VISIBLE_DEVICES:-}}"+ # first-set-wins, mirroring _pick_visible_index (and _HIP_LAYER_MASKS) in+ # studio/install_python_stack.py. rocminfo output is ALREADY ROCr-filtered, so+ # indexing by ROCR again shadows CUDA, its HIP alias: ROCR=2,1 + CUDA=1 is survivor 2.+ _vis_masks="HIP_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES"+ if [ "$_gfx_probe" != rocminfo ] && [ -n "${ROCR_VISIBLE_DEVICES:-}" ] && [ "$ROCR_VISIBLE_DEVICES" != "-1" ]; then+ # amd-smi is not ROCr-filtered: ROCr decides which devices exist, then HIP indexes the survivors (_rocr_visible_subset). Ordinals in mask order; none in range keeps the whole list, as _pick_visible_index does.+ _rocr_kept=$(printf '%s\n' "$_gfx_all" | awk -v m="$ROCR_VISIBLE_DEVICES" '+ NF { v[n++] = $0 }+ END { k = split(m, t, ","); for (i = 1; i <= k; i++) { gsub(/[[:space:]]/, "", t[i]); if (t[i] ~ /^[0-9]+$/ && t[i] + 0 < n) print v[t[i] + 0] } }')+ [ -n "$_rocr_kept" ] && _gfx_all="$_rocr_kept"+ # A UUID token names a device but no position here, so with unlike adapters no survivor is known to be the one selected: decline, as _rocr_visible_subset does.+ _rocr_unresolved=$(printf '%s' "$ROCR_VISIBLE_DEVICES" | tr -d '0-9, \t')+ fi+ _vis_var=""+ _vis=""+ for _vis_m in $_vis_masks; do+ eval "_vis_m_set=\${$_vis_m+x}"+ if [ -n "$_vis_m_set" ]; then+ _vis_var="$_vis_m"+ eval "_vis=\$$_vis_m"+ break+ fi+ done_idx=0if [ -n "$_vis" ] && [ "$_vis" != "-1" ]; then_first=${_vis%%,*}@@ -4675,11 +4847,31 @@ case "$_torch_index_leaf" inesacfi_runtime_gfx=$(printf '%s\n' "$_gfx_all" | awk -v idx="$_idx" '- NF && !seen[$0]++ { vals[n++] = $0 }+ NF { vals[n++] = $0 }END {if (idx < 0 || idx >= n) idx = 0if (n > 0) print vals[idx]}')+ # No HIP_ID map and unlike adapters: in amd-smi discovery order no ordinal names a+ # known device, so routing would install wheels for a card the runtime will not use.+ if [ "$_gfx_space" != hip ] && \+ [ "$(printf '%s\n' "$_gfx_all" | awk 'NF && !seen[$0]++ { n++ } END { print n + 0 }')" -gt 1 ]; then+ echo "" >&2+ echo " [WARN] amd-smi lists unlike adapters in discovery order and \`amd-smi list -e\`" >&2+ echo " [WARN] returned no HIP_ID map, so no ordinal here names a known device." >&2+ echo " [WARN] Skipping arch-specific torch routing. Set UNSLOTH_ROCM_GFX_ARCH to" >&2+ echo " [WARN] name the target explicitly." >&2+ echo "" >&2+ _runtime_gfx=""+ elif [ -n "${_rocr_unresolved:-}" ] && \+ [ "$(printf '%s\n' "$_gfx_all" | awk 'NF && !seen[$0]++ { n++ } END { print n + 0 }')" -gt 1 ]; then+ echo "" >&2+ echo " [WARN] ROCR_VISIBLE_DEVICES selects a GPU by UUID, which amd-smi output cannot map to a" >&2+ echo " [WARN] position, and the adapters differ. Skipping arch-specific torch routing." >&2+ echo " [WARN] Set UNSLOTH_ROCM_GFX_ARCH to name the target explicitly." >&2+ echo "" >&2+ _runtime_gfx=""+ fifi# An explicit UNSLOTH_ROCM_GFX_ARCH=gfx906 pins the runtime target to the MI50 / Radeon VII path and must win over Strix probe-order detection on a mixed Strix + MI50 host, so the Strix reroute is suppressed when it is set. Normalize a copied HIP gcnArchName (gfx906:sramecc-:xnack- to gfx906) and trim whitespace so the suffix or a stray newline does not defeat the exact gfx906 comparisons below._gfx906_env=$(printf '%s' "${UNSLOTH_ROCM_GFX_ARCH:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')@@ -4718,6 +4910,51 @@ case "$_torch_index_leaf" inecho " [WARN] (~/.bashrc, ~/.profile) as well, or the next terminal restores it." >&2fifi+ # Navi 33 (gfx1102) and RDNA 4 (gfx1200/gfx1201) have no kernels in the+ # older generic wheel families. The floor is per arch, read from the+ # rocBLAS and hipBLASLt Tensile library names in each leaf's cp312 wheels:+ #+ # rocm6.0 (2.3.1-2.4.1) gfx1030 gfx1100+ # rocm6.1 (2.5.0-2.6.0) gfx1030 gfx1100 gfx1101+ # rocm6.2 (2.5.0-2.5.1) gfx1030 gfx1100+ # rocm6.3 (2.7.0-2.9.1) gfx1030 gfx1100 gfx1101 gfx1102 gfx1200 gfx1201+ # rocm6.4 (2.8.0-2.9.1) same set+ #+ # gfx1102 floors at 6.3. gfx1200/gfx1201 keep 6.4, matching+ # _GENERIC_WHEEL_GFX_MIN_ROCM in studio/install_python_stack.py (keep the+ # two tables in step) and AMD's matrix, which puts production RDNA 4 at 6.4.+ #+ # Beside the gfx906 policy, not inside the runtime-less */cpu reroute,+ # because a valid host ROCm reading can otherwise select broken rocm6.1+ # wheels. Explicit torch-index pins skip this whole block.+ case "$_runtime_gfx" in+ gfx1102) _gfx_rocm64_floor_maj=6; _gfx_rocm64_floor_min=3 ;;+ gfx1200|gfx1201) _gfx_rocm64_floor_maj=6; _gfx_rocm64_floor_min=4 ;;+ esac+ if [ -n "$_gfx_rocm64_floor_maj" ]; then+ _gfx_rocm64_target=true+ # These arches train from the generic wheels, never repo.radeon.com, so+ # clear the marketing-name flag as the gfx906 branch below does: the+ # newest rocm-rel-6.4 trio (torch 2.6.0+rocm6.4.0) carries no gfx1102+ # Tensile library, and rocm-rel-7.2 is narrower still (gfx120X-all,+ # gfx90a, gfx942, gfx950). Cleared whenever the arch is the runtime+ # target, even when the leaf already satisfies the floor and the reroute+ # below is a no-op.+ _amd_gpu_radeon=false+ _gfx_rocm64_tag="rocm${_gfx_rocm64_floor_maj}.${_gfx_rocm64_floor_min}"+ if _rocm_leaf_below "$_torch_index_leaf" "$_gfx_rocm64_floor_maj" "$_gfx_rocm64_floor_min"; then+ echo "" >&2+ echo " [WARN] $_runtime_gfx detected -- routing torch to $_gfx_rocm64_tag because older" >&2+ echo " [WARN] generic ROCm wheel families do not ship $_runtime_gfx kernels." >&2+ echo "" >&2+ _amd_rocm64_base="${UNSLOTH_PYTORCH_MIRROR:-https://download.pytorch.org/whl}"+ while [ "${_amd_rocm64_base%/}" != "$_amd_rocm64_base" ]; do+ _amd_rocm64_base="${_amd_rocm64_base%/}"+ done+ TORCH_INDEX_URL="${_amd_rocm64_base}/${_gfx_rocm64_tag}"+ _torch_index_leaf="$_gfx_rocm64_tag"+ fi+ fi# ── MI50 / Radeon VII (gfx906, Vega 20): legacy community-supported path ──# Newer rocm wheel families bundle ROCm libraries whose Tensile kernels dropped gfx906 (rocBLAS "TensileLibrary.dat ... not read for gfx906", ROCm/TheRock#1844), so a rocm6.4+/7.x index installs a torch that fails at the first BLAS call. The rocm6.3 index is the last one whose wheels run on gfx906 (torch 2.7.0 verified on MI50 32GB; up to 2.9 in community use), so reroute any newer picked index and leave rocm6.0-6.3 alone. Target resolution: an explicit UNSLOTH_ROCM_GFX_ARCH wins, letting a host whose rocminfo/amd-smi emit no gfx token still opt in. Otherwise only treat gfx906 as the target when it is the SOLE distinct arch present: _gfx_all is de-duplicated by visible index, which loses per-device ordinals on a mixed host, so a non-gfx906 selection must never be downgraded to rocm6.3._gfx906_target=false@@ -4772,105 +5009,6 @@ fi_TAURI_GPU_BRANCH=$(_tauri_gpu_branch "$_TAURI_TORCH_INDEX_FAMILY" "$_amd_gpu_radeon")tauri_diag_marker "$_TAURI_GPU_BRANCH" "$_TAURI_TORCH_INDEX_FAMILY"-# Pair each rocminfo GPU gfx id with its marketing name instead of using the CPU-first global name (#7307). Blank names keep device ordinals; no GPU keeps the old fallback. Keep in sync with studio/setup.sh.-_rocminfo_gpu_records() {- awk '- # Split at the first colon so embedded colons survive.- function value(line, v) {- v = line- sub(/^[^:]*:[[:space:]]*/, "", v)- gsub(/^[[:space:]]+|[[:space:]]+$/, "", v)- return v- }- /^[[:space:]]*Name:/ {- # Keep a slot for a nameless GPU.- if (gfx != "" && !named) { print gfx "|"; gpus++ }- gfx = ""; named = 0- name = value($0)- # Accept target suffixes such as gfx90a:sramecc+, but reject ISA names.- if (match(name, /^gfx[1-9][0-9a-z][0-9a-z][0-9a-z]?/)) {- rest = substr(name, RLENGTH + 1)- if (rest == "" || rest ~ /^[^0-9a-z]/) gfx = substr(name, 1, RLENGTH)- }- next- }- /^[[:space:]]*Marketing Name:/ {- mkt = value($0)- if (gfx != "" && !named) { print gfx "|" mkt; gpus++; named = 1 }- else if (first == "") first = mkt- next- }- END {- if (gfx != "" && !named) { print gfx "|"; gpus++ }- if (gpus == 0 && first != "") print "|" first- }- '-}--# amd-smi enumerates in discovery order over its KFD view, while HIP_VISIBLE_DEVICES and ROCR_VISIBLE_DEVICES index HIP/ROCr order, which the library derives from the KFD node id instead. The two disagree on real hardware (MI350X SPX/NPS1), and _gfx here becomes --rocm-gfx, so an untranslated ordinal can fetch a prebuilt for another card's arch. `amd-smi list -e` is the map AMD publishes for this (HIP_ID, ROCm 6.4.0+); utils/hardware/amd.py get_hip_id_by_gpu_index reads the same field. Keep in sync with studio/setup.sh.-_amd_smi_hip_order() {- # POSIX awk forbids a physical newline in a -v value (gawk --posix makes it fatal),- # so the records arrive on stdin ahead of the map, separated by a sentinel. The first- # output line reports which index space the records came back in; the caller needs to- # know, because a mask cannot be applied to an untranslated list of unlike adapters.- { printf '%s\n' "$1"; echo "@@hip-map@@"; cat; } | awk '- function value(line, v) {- v = line- sub(/^[^:]*:[[:space:]]*/, "", v)- gsub(/^[[:space:]]+|[[:space:]]+$/, "", v)- return v- }- function keep( i) { print "discovery"; for (i = 1; i <= r; i++) print rec[i] }- !split_seen && $0 == "@@hip-map@@" { split_seen = 1; next }- !split_seen { if ($0 != "") rec[++r] = $0; next }- /^[[:space:]]*GPU:[[:space:]]*[0-9]/ { n++; hip[n] = -1; next }- n && tolower($0) ~ /hip.?id/ {- if (hip[n] < 0) { v = value($0); if (v ~ /^[0-9]+$/) hip[n] = v + 0 }- next- }- END {- # All or nothing, like get_hip_id_by_gpu_index: an older CLI rejects -e, and- # hip_id reads N/A when the library cannot reach a KFD node. A partial or- # colliding map is not a 1:1 device mapping, so keep discovery order.- if (r == 0 || n != r) { keep(); exit }- for (i = 1; i <= n; i++) {- if (hip[i] < 0 || hip[i] >= r || (hip[i] in used)) { keep(); exit }- used[hip[i]] = 1- out[hip[i]] = rec[i]- }- print "hip"- for (i = 0; i < r; i++) print out[i]- }- '-}--# One `gfx|marketing name` per adapter, in `GPU: N` order, so the mask picks both halves of one device. Was: arch indexed, name always adapter 0's, and on amd-smi 6.1.1, which has no TARGET_GRAPHICS_VERSION, that name is what --rocm-gfx is inferred from. Keep in sync with studio/setup.sh.-_amd_smi_gpu_records() {- awk '- function value(line, v) {- v = line- sub(/^[^:]*:[[:space:]]*/, "", v)- gsub(/^[[:space:]]+|[[:space:]]+$/, "", v)- return v- }- function flush() {- if (started) print gfx "|" mkt- gfx = ""; mkt = ""- }- # amd-smi upper-cases every key (amdsmi_logger.py _capitalize_keys): MARKET_NAME,- # TARGET_GRAPHICS_VERSION. Matched case-folded so older spellings work too.- /^[[:space:]]*GPU:[[:space:]]*[0-9]/ { flush(); started = 1; next }- !started { next }- tolower($0) ~ /market.?name/ { if (mkt == "") mkt = value($0); next }- tolower($0) ~ /target.?graphics.?version/ {- v = value($0)- if (gfx == "" && v ~ /^gfx[1-9][0-9a-z][0-9a-z][0-9a-z]?$/) gfx = v- next- }- END { flush() }- '-}-# ── GPU detection summary (mirrors install.ps1 step "gpu" block) ──if _has_usable_nvidia_gpu; thenstep "gpu" "NVIDIA GPU detected"@@ -5214,6 +5352,12 @@ if [ "$_MIGRATED" = true ]; thenif [ -z "$_has_hip" ]; thensubstep "repairing ROCm torch (overwritten by dependency resolution)..."_install_torch_default_index --force-reinstall+ elif [ "$_gfx_rocm64_target" = true ] && \+ _venv_torch_rocm_below "$_VENV_PY" "$_gfx_rocm64_floor_maj" "$_gfx_rocm64_floor_min"; then+ # A migrated venv keeps its hip torch, but a wheel below this arch's floor has no+ # kernels for it. The SAME floor the reroute used, so an adequate wheel is left alone.+ substep "reinstalling torch from $_torch_index_leaf (the migrated wheels have no kernels for this GPU)..."+ _install_torch_default_index --force-reinstallfi_gfx906_bnb_prunefidiff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 11b88f968a2..bf338f43b6c 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -2741,6 +2741,11 @@ _GENERIC_WHEEL_GFX_MIN_ROCM: "dict[str, tuple[int, int]]" = {"gfx950": (7, 0),"gfx1150": (7, 0),"gfx1151": (7, 0),+ # gfx1102 (Navi 33 / RX 7600): rocm6.3 is the first family whose rocBLAS / hipBLASLt+ # Tensile libraries carry it (rocm6.0-6.2 stop at gfx1030/gfx1100/gfx1101). Without an+ # entry here the tag check reads "support unknown" and leaves an RX 7600 on a wheel that+ # has no kernels for it.+ "gfx1102": (6, 3),"gfx1200": (6, 4),"gfx1201": (6, 4),}diff --git a/studio/setup.sh b/studio/setup.shindex a8cb8d54b1c..10425c990e5 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -2767,10 +2767,8 @@ _setup_rocminfo_gpu_records() {# side reads the same field in utils/hardware/amd.py get_hip_id_by_gpu_index.# Keep in sync with install.sh._setup_amd_smi_hip_order() {- # POSIX awk forbids a physical newline in a -v value (gawk --posix makes it fatal),- # so the records arrive on stdin ahead of the map, separated by a sentinel. The first- # output line reports which index space the records came back in; the caller needs to- # know, because a mask cannot be applied to an untranslated list of unlike adapters.+ # POSIX awk forbids a newline in a -v value (fatal under gawk --posix), so records arrive+ # on stdin before the map, sentinel-separated. Line 1 names the index space.{ printf '%s\n' "$1"; echo "@@hip-map@@"; cat; } | awk 'function value(line, v) {v = line@@ -2787,9 +2785,7 @@ _setup_amd_smi_hip_order() {next}END {- # All or nothing, like get_hip_id_by_gpu_index: an older CLI rejects -e, and- # hip_id reads N/A when the library cannot reach a KFD node. A partial or- # colliding map is not a 1:1 device mapping, so keep discovery order.+ # All or nothing, like get_hip_id_by_gpu_index: a partial or colliding map is not 1:1.if (r == 0 || n != r) { keep(); exit }for (i = 1; i <= n; i++) {if (hip[i] < 0 || hip[i] >= r || (hip[i] in used)) { keep(); exit }@@ -2818,9 +2814,14 @@ _setup_amd_smi_gpu_records() {if (started) print gfx "|" mktgfx = ""; mkt = ""}- # amd-smi upper-cases every key (amdsmi_logger.py _capitalize_keys): MARKET_NAME,- # TARGET_GRAPHICS_VERSION. Matched case-folded so older spellings work too.- /^[[:space:]]*GPU:[[:space:]]*[0-9]/ { flush(); started = 1; next }+ # amd-smi upper-cases every key (amdsmi_logger.py _capitalize_keys), so match+ # case-folded. Two header shapes: `GPU: 0` opens a keyed block with the arch later,+ # `GPU[0] : gfx1100` IS the record. Matching only the first answered no arch at all.+ /^[[:space:]]*GPU[[:space:]]*[:\[][[:space:]]*[0-9]/ {+ flush(); started = 1+ if (match($0, /gfx[1-9][0-9a-z][0-9a-z][0-9a-z]?/)) gfx = substr($0, RSTART, RLENGTH)+ next+ }!started { next }tolower($0) ~ /market.?name/ { if (mkt == "") mkt = value($0); next }tolower($0) ~ /target.?graphics.?version/ {diff --git a/tests/sh/test_rocminfo_gpu_name_7307.sh b/tests/sh/test_rocminfo_gpu_name_7307.shindex a04ed232e1d..e4aab1b6ab2 100755--- a/tests/sh/test_rocminfo_gpu_name_7307.sh+++ b/tests/sh/test_rocminfo_gpu_name_7307.sh@@ -13,6 +13,12 @@ _FUNC_FILE=$(mktemp)sed -n '/^_rocminfo_gpu_records()/,/^}/p' "$INSTALL_SH"echo ""sed -n '/^_setup_rocminfo_gpu_records()/,/^}/p' "$SETUP_SH"+ echo ""+ sed -n '/^_amd_smi_gpu_records()/,/^}/p' "$INSTALL_SH"+ echo ""+ sed -n '/^_gfx_arch_slots()/,/^}/p' "$INSTALL_SH"+ echo ""+ sed -n '/^_amd_smi_hip_order()/,/^}/p' "$INSTALL_SH"} > "$_FUNC_FILE"# shellcheck disable=SC1090. "$_FUNC_FILE"@@ -299,6 +305,140 @@ assert_eq "falls back to the first marketing name with no arch" \"|AMD Ryzen 7 5700U with Radeon Graphics" "$(printf '%s\n' "$APU" | _rocminfo_gpu_records)"assert_eq "empty input yields nothing" "" "$(printf '' | _rocminfo_gpu_records)"+# Two amd-smi header shapes: `GPU: N` opens a keyed block with the arch later, `GPU[N] :+# gfx...` is the whole record. Matching only the first left an rocminfo-less host with no+# arch at all, so a gfx1200 box on ROCm 6.1 kept kernel-less wheels instead of rocm6.4.+SMI_BRACKET="GPU[0] : gfx1100+GPU[1] : gfx1100+GPU[2] : gfx1200"+SMI_KEYED="GPU: 0+ ASIC:+ MARKET_NAME: AMD Radeon RX 9070 XT+ TARGET_GRAPHICS_VERSION: gfx1201"+echo "=== amd-smi headers ==="+assert_eq "the bracketed one-line form keeps its arch, one record per device" \+ "gfx1100| gfx1100| gfx1200|" \+ "$(printf '%s\n' "$SMI_BRACKET" | _amd_smi_gpu_records | tr '\n' ' ' | sed 's/ $//')"+assert_eq "the keyed form still pairs arch with name" \+ "gfx1201|AMD Radeon RX 9070 XT" \+ "$(printf '%s\n' "$SMI_KEYED" | _amd_smi_gpu_records)"+assert_eq "a header with no arch stays empty rather than borrowing the next device's" \+ "|" "$(printf 'GPU: 0\n BDF: 0000:03:00.0\n' | _amd_smi_gpu_records)"++# A mask indexes the arch list, so an unreadable adapter keeps its slot: dropping it shifts+# every later device and hands the mask the next card's arch.+echo "=== arch slots ==="+assert_eq "an unreadable adapter keeps its ordinal instead of shifting the list" \+ "unknown gfx1151" \+ "$(printf '%s\n' "|Unknown adapter+gfx1151|Radeon 8060S" | _gfx_arch_slots | tr '\n' ' ' | sed 's/ $//')"+assert_eq "and in the last slot, where command substitution used to eat it" \+ "gfx1151 unknown" \+ "$(printf '%s\n' "gfx1151|Radeon 8060S+|Unknown adapter" | _gfx_arch_slots | tr '\n' ' ' | sed 's/ $//')"+assert_eq "no arch anywhere prints nothing, so the caller tries the next probe" \+ "" "$(printf '%s\n' "|A+|B" | _gfx_arch_slots)"+assert_eq "a fully readable list is unchanged" "gfx1100 gfx1200" \+ "$(printf '%s\n' "gfx1100|A+gfx1200|B" | _gfx_arch_slots | tr '\n' ' ' | sed 's/ $//')"++# Arch routing indexes with a HIP/ROCR ordinal, but amd-smi enumerates in discovery order,+# so it has to translate first or say it cannot.+HIP_MAP="GPU: 0+ HIP_ID: 1+GPU: 1+ HIP_ID: 0"+MIXED="gfx90a|AMD Instinct MI210+gfx1200|AMD Radeon RX 9070"+echo "=== amd-smi to HIP order ==="+assert_eq "a full HIP_ID map reorders the records and says so" \+ "hip gfx1200|AMD Radeon RX 9070 gfx90a|AMD Instinct MI210" \+ "$(printf '%s\n' "$HIP_MAP" | _amd_smi_hip_order "$MIXED" | tr '\n' ' ' | sed 's/ $//')"+assert_eq "no map at all keeps discovery order and says THAT" \+ "discovery gfx90a|AMD Instinct MI210 gfx1200|AMD Radeon RX 9070" \+ "$(printf '' | _amd_smi_hip_order "$MIXED" | tr '\n' ' ' | sed 's/ $//')"+assert_eq "HIP_ID: N/A is not a map either" \+ "discovery" \+ "$(printf 'GPU: 0\n HIP_ID: N/A\nGPU: 1\n HIP_ID: N/A\n' \+ | _amd_smi_hip_order "$MIXED" | head -n 1)"++# GPU probing runs at install.sh top level, so a helper defined below its first call is not+# in scope: the caller's `|| true` swallows the command-not-found and the probe answers+# nothing. It shipped that way once. Pin the order, not the line numbers, which move.+echo "=== helpers are defined before they are called ==="+for _fn in _rocminfo_gpu_records _amd_smi_gpu_records _gfx_arch_slots _amd_smi_hip_order; do+ _def=$(grep -n "^$_fn() {" "$INSTALL_SH" | head -n 1 | cut -d: -f1)+ # Calls only, never the definition line and never a comment.+ _first_use=$(grep -n "[|( ]$_fn\b" "$INSTALL_SH" \+ | grep -v "^[0-9]*: *#" | head -n 1 | cut -d: -f1)+ if [ -z "$_first_use" ]; then+ echo " FAIL: $_fn is defined but never called"; FAIL=$((FAIL + 1)); continue+ fi+ if [ "$_def" -lt "$_first_use" ]; then+ echo " PASS: $_fn defined at $_def, first called at $_first_use"; PASS=$((PASS + 1))+ else+ echo " FAIL: $_fn is called at $_first_use but not defined until $_def"+ FAIL=$((FAIL + 1))+ fi+done++echo "=== the ROCr layer and the HIP layer compose, they do not shadow ==="+# rocminfo output is already the ROCr survivors; the HIP layer (HIP_VISIBLE_DEVICES or its+# alias CUDA_VISIBLE_DEVICES) then selects among THOSE. ROCR=2,1 leaves gfx1200 then+# gfx1100, so CUDA=1 names gfx1100. Mirrors _HIP_LAYER_MASKS in install_python_stack.py.+_mask_case() {+ # $1 = env assignments, $2 = expected arch+ _got=$(env -u HIP_VISIBLE_DEVICES -u ROCR_VISIBLE_DEVICES -u CUDA_VISIBLE_DEVICES \+ sh -c "+ $1+ _gfx_probe=rocminfo+ _gfx_all='gfx1200+gfx1100'+ $(sed -n '/# first-set-wins, mirroring _pick_visible_index/,/^ _idx=0$/p' "$INSTALL_SH")+ if [ -n \"\$_vis\" ] && [ \"\$_vis\" != \"-1\" ]; then+ _first=\${_vis%%,*}+ case \"\$_first\" in ''|*[!0-9]*) _idx=0 ;; *) _idx=\$_first ;; esac+ fi+ printf '%s\\n' \"\$_gfx_all\" | awk -v idx=\"\$_idx\" 'NF { v[n++]=\$0 } END { if (idx<0||idx>=n) idx=0; if (n>0) print v[idx] }'+ " 2>/dev/null)+ if [ "$_got" = "$2" ]; then+ echo " PASS: [$1] -> $2"; PASS=$((PASS + 1))+ else+ echo " FAIL: [$1] expected $2, got '$_got'"; FAIL=$((FAIL + 1))+ fi+}+_mask_case "export ROCR_VISIBLE_DEVICES=2,1" "gfx1200"+_mask_case "export ROCR_VISIBLE_DEVICES=2,1; export CUDA_VISIBLE_DEVICES=1" "gfx1100"+_mask_case "export ROCR_VISIBLE_DEVICES=2,1; export HIP_VISIBLE_DEVICES=1" "gfx1100"+_mask_case "export HIP_VISIBLE_DEVICES=0" "gfx1200"++# `amd-smi list` on ROCm 6.x answers ids only (GPU, BDF, UUID, KFD_ID); the arch lives in+# `static --asic`. A record with an empty arch column is not an answer and must not stop+# that fallback, or an rocminfo-less host routes to the generic wheel.+echo "=== amd-smi list without an arch falls through to static --asic ==="+_smi_bin=$(mktemp -d)+cat > "$_smi_bin/amd-smi" <<'EOF'+#!/bin/sh+case "${1:-} ${2:-}" in+ "list ") printf 'GPU: 0\n BDF: 0000:c3:00.0\n' ;;+ "static --asic") printf 'GPU: 0\n ASIC:\n MARKET_NAME: AMD Radeon Graphics\n TARGET_GRAPHICS_VERSION: gfx1151\n' ;;+ *) exit 1 ;;+esac+EOF+chmod +x "$_smi_bin/amd-smi"+_fallback=$(sed -n '/_gfx_records=$(amd-smi list 2>\/dev\/null | _amd_smi_gpu_records/,/_gfx_probe=amd-smi$/p' "$INSTALL_SH")+[ -n "$_fallback" ] || { echo "FATAL: no amd-smi fallback found in $INSTALL_SH" >&2; exit 1; }+{+ sed -n '/^_amd_smi_gpu_records()/,/^}/p' "$INSTALL_SH"+ sed -n '/^_gfx_arch_slots()/,/^}/p' "$INSTALL_SH"+ sed -n '/^_amd_smi_hip_order()/,/^}/p' "$INSTALL_SH"+ printf '%s\n' "_gfx_all=''; _gfx_probe=''; _gfx_space=hip" "$_fallback" fi 'printf "%s" "$_gfx_all"'+} > "$_smi_bin/run.sh"+assert_eq "an arch-less amd-smi list still reaches static --asic" "gfx1151" \+ "$(PATH="$_smi_bin:$PATH" sh "$_smi_bin/run.sh" 2>/dev/null)"+rm -rf "$_smi_bin"+echo ""echo "Results: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ]diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.pyindex 41c8563e54c..44cf0ad7d2b 100644--- a/tests/studio/install/test_rocm_support.py+++ b/tests/studio/install/test_rocm_support.py@@ -93,6 +93,23 @@ def _extract_sh_function_body(source: str, name: str) -> str:return source[start:]+def _gpu_record_helpers(source: str) -> str:+ """install.sh's per-device GPU helpers, for injecting into a probe block.++ A missing one fails silently: `|| true` swallows the command-not-found and the+ assertion runs against an empty arch list, so the test passes for the wrong reason.+ """+ return "\n".join(+ _extract_sh_function_body(source, name)+ for name in (+ "_rocminfo_gpu_records",+ "_amd_smi_gpu_records",+ "_gfx_arch_slots",+ "_amd_smi_hip_order",+ )+ )++# A dpkg-query -W stand-in that renders whichever showformat string it is handed,# so this tests how production ASKS for versions, not only how it parses answers._DPKG_QUERY_STUB = r"""#!/bin/sh@@ -1233,6 +1250,42 @@ Agent 4assert self._probe_gfx(flat, False) == ["gfx1100", "gfx1151"]assert self._probe_gfx(flat, True) == ["gfx1100", "gfx1151"]+ _AMD_SMI_ASIC = """GPU: 0+ ASIC:+ MARKET_NAME: Radeon RX 7900 XTX+ TARGET_GRAPHICS_VERSION: gfx1100+GPU: 1+ ASIC:+ MARKET_NAME: Radeon RX 7900 XTX+ TARGET_GRAPHICS_VERSION: gfx1100+GPU: 2+ ASIC:+ MARKET_NAME: Radeon RX 9060+ TARGET_GRAPHICS_VERSION: gfx1200+"""++ @staticmethod+ def _probe_gfx_amd_smi(out, dedup):+ which = lambda n: "/usr/bin/amd-smi" if n == "amd-smi" else None # noqa: E731+ with patch("shutil.which", side_effect = which):+ with patch.object(stack_mod, "_amd_smi_allowed", return_value = True):+ with patch("subprocess.run", return_value = MagicMock(returncode = 0, stdout = out)):+ return stack_mod._detect_amd_gfx_codes(dedup = dedup)++ def test_gfx_probe_splits_amd_smi_gpu_headers(self):+ """amd-smi heads each device with "GPU: N", so duplicate arches stay separate."""+ assert self._probe_gfx_amd_smi(self._AMD_SMI_ASIC, False) == [+ "gfx1100",+ "gfx1100",+ "gfx1200",+ ]+ assert self._probe_gfx_amd_smi(self._AMD_SMI_ASIC, True) == ["gfx1100", "gfx1200"]++ def test_gfx_probe_splits_amd_smi_bracket_headers(self):+ """The "GPU[N] : gfx" one-line form keeps its token on the header line."""+ bracket = "GPU[0] : gfx1100\nGPU[1] : gfx1100\nGPU[2] : gfx1200\n"+ assert self._probe_gfx_amd_smi(bracket, False) == ["gfx1100", "gfx1100", "gfx1200"]+def test_gfx_probe_records_which_tool_answered(self):# Only rocminfo is mask-filtered, and only by ROCR, so the reroute needs this.self._probe_gfx(self._ROCMINFO, False)@@ -1820,6 +1873,521 @@ class TestGfx906LegacyReroute:assert 'setdefault("UNSLOTH_COMPILE_DISABLE", "1")' in gate_body+# The floor is PER ARCH, from the Tensile library names in the published wheels: rocm6.3 is+# the first family carrying gfx1102/gfx1200/gfx1201, so gfx1102 floors at 6.3; gfx1200 and+# gfx1201 floor at 6.4 to match _GENERIC_WHEEL_GFX_MIN_ROCM and AMD's production matrix.+_GFX_FLOOR_TAG = {"gfx1102": "rocm6.3", "gfx1200": "rocm6.4", "gfx1201": "rocm6.4"}+++class TestGfx1102Rocm64Floor:+ """Navi 33 / RDNA 4 need a generic PyTorch ROCm family at or above their own floor."""++ @staticmethod+ def _ensure_for_gfx(+ gfx: str,+ monkeypatch,+ *,+ pinned: bool = False,+ rocm_ver: tuple = (6, 1),+ probe_stdout: str = "\n", # CPU torch -> repair+ ):+ m = stack_mod+ for name in (+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ "UNSLOTH_ROCM_GFX_ARCH",+ "UNSLOTH_TORCH_INDEX_FAMILY",+ "UNSLOTH_TORCH_INDEX_URL",+ ):+ monkeypatch.delenv(name, raising = False)+ if pinned:+ monkeypatch.setenv(+ "UNSLOTH_TORCH_INDEX_URL", "https://download.pytorch.org/whl/rocm6.1"+ )+ probe = MagicMock(returncode = 0, stdout = probe_stdout)+ with (+ patch.object(m, "IS_WINDOWS", False),+ patch.object(m, "IS_MACOS", False),+ patch.object(m, "_TORCH_RUNTIME_PROBE", None),+ patch.object(m, "_TORCH_BACKEND", ""),+ patch.object(m, "_LAST_AMD_GFX_PROBE", None),+ patch.object(m, "pip_install") as pip,+ patch.object(m, "pip_install_try", return_value = True),+ patch.object(m, "_has_usable_nvidia_gpu", return_value = False),+ patch.object(m, "_has_rocm_gpu", return_value = True),+ # These scenarios install GENERIC pytorch.org wheels, which do not pull+ # `rocm[libraries]`, so the per-arch family is None by construction. Left+ # unpatched these read the RUNNING interpreter's torch instead: on a gfx1151+ # Strix Halo runner holding 2.11.0+rocm7.13.0 the per-arch repick arm called+ # pip_install, failing the assert_not_called tests on hardware only.+ patch.object(m, "_torch_requires_rocm_sdk", return_value = False),+ patch.object(m, "_installed_rocm_wheel_family", return_value = None),+ patch.object(m, "_infer_linux_amd_gfx_arch", return_value = None),+ patch.object(m, "_detect_rocm_version", return_value = rocm_ver),+ patch.object(m, "_detect_amd_gfx_codes", return_value = [gfx]),+ patch("platform.machine", return_value = "x86_64"),+ patch("subprocess.run", return_value = probe),+ ):+ _ensure_rocm_torch()+ return pip++ def test_the_shared_kernel_table_knows_gfx1102(self):+ """The rocm6.0, rocm6.1 and rocm6.2 wheels carry no gfx1102 Tensile library.++ rocm6.3 is the first family that carries it. Without an entry here+ _generic_tag_lacks_kernels reads "support unknown" and leaves an RX 7600 stranded.+ """+ assert stack_mod._GENERIC_WHEEL_GFX_MIN_ROCM["gfx1102"] == (6, 3)+ assert stack_mod._generic_tag_lacks_kernels("gfx1102", (6, 0)) is True+ assert stack_mod._generic_tag_lacks_kernels("gfx1102", (6, 1)) is True+ assert stack_mod._generic_tag_lacks_kernels("gfx1102", (6, 2)) is True+ # rocm6.3 already has them, so a host there must not be moved.+ assert stack_mod._generic_tag_lacks_kernels("gfx1102", (6, 3)) is False+ assert stack_mod._generic_tag_lacks_kernels("gfx1102", (6, 4)) is False+ assert stack_mod._generic_tag_lacks_kernels("gfx1102", (7, 2)) is False++ def test_the_kernel_table_leaves_the_older_arches_alone(self):+ """gfx1030/gfx1100/gfx1101 are in every family measured, so they have no floor."""+ for unaffected in ("gfx1030", "gfx1100", "gfx1101", "gfx906"):+ assert unaffected not in stack_mod._GENERIC_WHEEL_GFX_MIN_ROCM+ assert stack_mod._generic_tag_lacks_kernels(unaffected, (6, 0)) is False++ def test_debian_split_gfx1100_keeps_rocm61(self, monkeypatch):+ """A Debian split host resolving rocm6.1 must leave gfx1100 on rocm6.1."""+ torch_call = str(self._ensure_for_gfx("gfx1100", monkeypatch).call_args_list[0])+ assert "rocm6.1" in torch_call+ assert "repo.amd.com" not in torch_call++ @pytest.mark.parametrize(+ "gfx, index",+ (+ ("gfx1102", "gfx110X-all"),+ ("gfx1200", "gfx120X-all"),+ ("gfx1201", "gfx120X-all"),+ ),+ )+ def test_debian_split_affected_gfx_leaves_the_kernel_less_generic_wheel(+ self, gfx, index, monkeypatch+ ):+ """A resolved Debian rocm6.1 host cannot install a kernel-less generic wheel.++ The per-arch route beats a newer generic family: repo.amd.com ships wheels built+ for exactly this arch.+ """+ torch_call = str(self._ensure_for_gfx(gfx, monkeypatch).call_args_list[0])+ assert index in torch_call+ assert "whl/rocm6.1" not in torch_call++ def test_a_gfx1102_host_already_on_rocm63_is_left_alone(self, monkeypatch):+ """rocm6.3 already carries gfx1102, so moving it anywhere would be churn."""+ torch_call = str(+ self._ensure_for_gfx("gfx1102", monkeypatch, rocm_ver = (6, 3)).call_args_list[0]+ )+ assert "whl/rocm6.3" in torch_call+ assert "repo.amd.com" not in torch_call++ def test_explicit_rocm61_pin_remains_authoritative(self, monkeypatch):+ """The narrow auto-floor never overwrites an explicit user index pin."""+ torch_call = str(+ self._ensure_for_gfx("gfx1102", monkeypatch, pinned = True).call_args_list[0]+ )+ assert "whl/rocm6.1" in torch_call+ assert "repo.amd.com" not in torch_call++ def test_installed_64_wheel_left_alone_on_newer_host(self, monkeypatch):+ """A wheel that already has the kernels must not be reinstalled."""+ pip = self._ensure_for_gfx(+ "gfx1200",+ monkeypatch,+ rocm_ver = (6, 4),+ probe_stdout = _MARK + "2.8.0+rocm6.4|6.4.43482|\n",+ )+ pip.assert_not_called()++ def test_unaffected_arch_not_repaired_on_newer_host(self, monkeypatch):+ """gfx1100 has kernels in the older families, so its wheel stays untouched."""+ pip = self._ensure_for_gfx(+ "gfx1100",+ monkeypatch,+ rocm_ver = (6, 4),+ probe_stdout = _MARK + "2.8.0+rocm6.1|6.1.40093|\n",+ )+ pip.assert_not_called()++ def test_install_sh_floors_resolved_rocm61_by_runtime_gfx(self):+ """Exercise install.sh's generic-routing block with a resolved leaf.++ The Debian split detector hands the resolved rocm6.1 leaf to arch routing:+ gfx1100 stays, gfx1102/RDNA4 move to the family that ships their kernels.+ """+ shell = shutil.which("bash")+ if not shell:+ pytest.skip("bash needed to execute install.sh architecture routing")+ source = _INSTALL_SH_PATH.read_text(encoding = "utf-8")+ leaf_helper = _extract_sh_function_body(source, "_rocm_leaf_below")+ start = source.find('case "$_torch_index_leaf" in\n rocm[0-9]*)')+ end = source.find("\nfi # _torch_index_pinned guard", start)+ assert leaf_helper and start >= 0 and end >= 0+ routing_block = source[start:end]+ floor_pos = routing_block.find("_amd_rocm64_base")+ pin_start = source.rfind('if [ "$_torch_index_pinned" = false ]; then', 0, start)+ assert floor_pos >= 0 and pin_start >= 0 and pin_start < start++ for gfx, expected in (+ ("gfx1100", "rocm6.1"),+ ("gfx1102", "rocm6.3"),+ ("gfx1200", "rocm6.4"),+ ("gfx1201", "rocm6.4"),+ ):+ script = (+ "set -euo pipefail\n"+ + leaf_helper+ + "\n"+ + 'TORCH_INDEX_URL="https://download.pytorch.org/whl/rocm6.1"\n'+ + '_torch_index_leaf="rocm6.1"\n'+ + "_torch_index_pinned=false\nSKIP_TORCH=false\n_amd_gpu_radeon=false\n"+ + f'UNSLOTH_ROCM_GFX_ARCH="{gfx}"\n'+ + "unset HSA_OVERRIDE_GFX_VERSION HIP_VISIBLE_DEVICES ROCR_VISIBLE_DEVICES UNSLOTH_PYTORCH_MIRROR\n"+ + routing_block+ + '\nprintf "URL:%s LEAF:%s\\n" "$TORCH_INDEX_URL" "$_torch_index_leaf"\n'+ )+ result = subprocess.run([shell, "-c", script], capture_output = True, text = True)+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip().endswith(f"/{expected} LEAF:{expected}"), result.stdout++ @staticmethod+ def _install_sh_routing_result(+ preamble: str,+ leaf: str = "rocm6.1",+ radeon_in: str = "false",+ ) -> tuple:+ """Run install.sh's architecture-routing block, returning (leaf, floor-target flag)."""+ shell = shutil.which("bash")+ if not shell:+ pytest.skip("bash needed to execute install.sh architecture routing")+ source = _INSTALL_SH_PATH.read_text(encoding = "utf-8")+ leaf_helper = _extract_sh_function_body(source, "_rocm_leaf_below")+ gfx_helper = _gpu_record_helpers(source)+ start = source.find('case "$_torch_index_leaf" in\n rocm[0-9]*)')+ end = source.find("\nfi # _torch_index_pinned guard", start)+ assert leaf_helper and gfx_helper and start >= 0 and end >= 0+ script = (+ "set -euo pipefail\n"+ + leaf_helper+ + "\n"+ + gfx_helper+ + "\n"+ + f'TORCH_INDEX_URL="https://download.pytorch.org/whl/{leaf}"\n'+ + f'_torch_index_leaf="{leaf}"\n'+ + f"_torch_index_pinned=false\nSKIP_TORCH=false\n_amd_gpu_radeon={radeon_in}\n"+ + "_gfx_rocm64_target=false\n"+ + "unset HSA_OVERRIDE_GFX_VERSION HIP_VISIBLE_DEVICES ROCR_VISIBLE_DEVICES\n"+ + "unset CUDA_VISIBLE_DEVICES UNSLOTH_ROCM_GFX_ARCH UNSLOTH_PYTORCH_MIRROR\n"+ + preamble+ + "\n"+ + source[start:end]+ + '\nprintf "LEAF:%s TARGET:%s RADEON:%s\\n" '+ '"$_torch_index_leaf" "$_gfx_rocm64_target" "$_amd_gpu_radeon"\n'+ )+ result = subprocess.run([shell, "-c", script], capture_output = True, text = True)+ assert result.returncode == 0, result.stderr+ tail = result.stdout.strip().rsplit("LEAF:", 1)[-1]+ _leaf, _rest = tail.split(" TARGET:")+ _target, _radeon = _rest.split(" RADEON:")+ return _leaf, _target, _radeon++ @classmethod+ def _run_install_sh_routing(cls, preamble: str) -> str:+ return cls._install_sh_routing_result(preamble)[0]++ @pytest.mark.parametrize(+ ("mask", "expected"),+ (+ ("CUDA_VISIBLE_DEVICES=1", "rocm6.4"),+ ("HIP_VISIBLE_DEVICES=1", "rocm6.4"),+ ("CUDA_VISIBLE_DEVICES=0", "rocm6.1"),+ # a set-but-empty hip mask selects no gpu instead of deferring to cuda+ ("HIP_VISIBLE_DEVICES= CUDA_VISIBLE_DEVICES=1", "rocm6.1"),+ ),+ )+ def test_install_sh_runtime_target_honors_cuda_visible_devices(self, mask, expected):+ """HIP exposes devices through CUDA_VISIBLE_DEVICES too, so it must select the target."""+ preamble = "rocminfo() { printf 'Name: gfx1100\\nName: gfx1200\\n'; }\n" + "".join(+ f"export {assignment}\n" for assignment in mask.split()+ )+ assert self._run_install_sh_routing(preamble) == expected++ @staticmethod+ def _rocminfo_stub(*arches: str) -> str:+ """A rocminfo stub whose agents repeat their gfx token across Name and ISA."""+ blocks = [+ "Agent 1",+ " Name: AMD Ryzen 9 7950X",+ " Device Type: CPU",+ ]+ for n, gfx in enumerate(arches, start = 2):+ blocks += [+ "*******",+ f"Agent {n}",+ "*******",+ f" Name: {gfx}",+ " Marketing Name: AMD Radeon Graphics",+ f" Name: amdgcn-amd-amdhsa--{gfx}",+ ]+ body = "\\n".join(blocks)+ return f"rocminfo() {{ printf '{body}\\n'; }}\n"++ @staticmethod+ def _amd_smi_stub(*arches, hip_ids = None):+ """An amd-smi that answers `list -e` separately from the ASIC listing.++ Without a HIP_ID map the routing block declines to index unlike adapters, so a+ test expecting the default leaf passes without exercising anything it names.+ Default `hip_ids` is the identity: HIP order == discovery order.+ """+ asic = "\\n".join(+ line+ for n, gfx in enumerate(arches)+ for line in (f"GPU: {n}", f" TARGET_GRAPHICS_VERSION: {gfx}")+ )+ hip_ids = range(len(arches)) if hip_ids is None else hip_ids+ hip_map = "\\n".join(+ line+ for n, hip in enumerate(hip_ids)+ for line in (f"GPU: {n}", f" HIP_ID: {hip}")+ )+ return (+ "amd-smi() {\n"+ ' case "$*" in\n'+ f" *'list -e'*) printf '{hip_map}\\n' ;;\n"+ f" *) printf '{asic}\\n' ;;\n"+ " esac\n"+ "}\n"+ )++ @pytest.mark.parametrize(+ ("mask", "expected"),+ (+ ("HIP_VISIBLE_DEVICES=2", "rocm6.4"),+ ("CUDA_VISIBLE_DEVICES=2", "rocm6.4"),+ ("HIP_VISIBLE_DEVICES=1", "rocm6.1"),+ ("HIP_VISIBLE_DEVICES=0", "rocm6.1"),+ ),+ )+ def test_install_sh_mask_indexes_devices_not_arches(self, mask, expected):+ """A visible-device mask is a device ordinal, so duplicate arches each count."""+ preamble = self._rocminfo_stub("gfx1100", "gfx1100", "gfx1200") + f"export {mask}"+ assert self._run_install_sh_routing(preamble) == expected++ @pytest.mark.parametrize(+ ("rocr", "arches", "expected"),+ (+ # rocminfo reports the rocr selection in runtime order, so index 0 is the target+ ("1,0", ("gfx1200", "gfx1100"), "rocm6.4"),+ ("1", ("gfx1200",), "rocm6.4"),+ ("0,1", ("gfx1100", "gfx1200"), "rocm6.1"),+ ),+ )+ def test_install_sh_does_not_reapply_a_rocr_mask_rocminfo_already_applied(+ self, rocr, arches, expected+ ):+ """rocminfo output is already filtered and ordered by ROCR_VISIBLE_DEVICES."""+ preamble = self._rocminfo_stub(*arches) + f"export ROCR_VISIBLE_DEVICES={rocr}"+ assert self._run_install_sh_routing(preamble) == expected++ @pytest.mark.parametrize(+ ("mask", "expected"),+ (("HIP_VISIBLE_DEVICES=2", "rocm6.4"), ("HIP_VISIBLE_DEVICES=1", "rocm6.1")),+ )+ def test_install_sh_splits_amd_smi_gpu_headers(self, mask, expected):+ """amd-smi heads each device with "GPU: N", so two gfx1100 cards stay two entries."""+ preamble = (+ "rocminfo() { return 1; }\n"+ + self._amd_smi_stub("gfx1100", "gfx1100", "gfx1200")+ + f"export {mask}"+ )+ assert self._run_install_sh_routing(preamble) == expected++ def test_install_sh_still_indexes_amd_smi_output_under_a_rocr_mask(self):+ """amd-smi ignores ROCR_VISIBLE_DEVICES, so its output still needs indexing."""+ preamble = (+ "rocminfo() { return 1; }\n"+ + self._amd_smi_stub("gfx1200", "gfx1100")+ + "export ROCR_VISIBLE_DEVICES=1"+ )+ assert self._run_install_sh_routing(preamble) == "rocm6.1"++ def test_install_sh_layers_rocr_under_hip_for_amd_smi(self):+ """ROCr decides which devices exist; HIP indexes the survivors, not the whole list."""+ preamble = (+ "rocminfo() { return 1; }\n"+ + self._amd_smi_stub("gfx1100", "gfx1200", "gfx1100")+ + "export ROCR_VISIBLE_DEVICES=1,0; export HIP_VISIBLE_DEVICES=1"+ )+ assert self._run_install_sh_routing(preamble) == "rocm6.1"++ def test_install_sh_declines_a_rocr_uuid_mask_over_unlike_amd_smi_adapters(self):+ """A UUID names a device but no position, so no survivor is known to be it."""+ preamble = (+ "rocminfo() { return 1; }\n"+ + self._amd_smi_stub("gfx1200", "gfx1100")+ + "export ROCR_VISIBLE_DEVICES=GPU-deadbeefdeadbeef"+ )+ assert self._run_install_sh_routing(preamble) == "rocm6.1"++ def test_install_sh_keeps_routing_on_a_rocr_uuid_mask_over_like_adapters(self):+ """One arch everywhere: whichever device the UUID names, the wheel is the same."""+ preamble = (+ "rocminfo() { return 1; }\n"+ + self._amd_smi_stub("gfx1200", "gfx1200")+ + "export ROCR_VISIBLE_DEVICES=GPU-deadbeefdeadbeef"+ )+ assert self._run_install_sh_routing(preamble) == "rocm6.4"++ def test_install_sh_declines_an_ordinal_when_amd_smi_gives_no_hip_map(self):+ """Without `list -e` there is no HIP order, so an ordinal names no known device.++ Same adapters and mask as the two above, map withheld: routing must decline and+ leave the caller's leaf alone rather than index a discovery-ordered list.+ """+ preamble = (+ "rocminfo() { return 1; }\n"+ "amd-smi() { printf 'GPU: 0\\n TARGET_GRAPHICS_VERSION: gfx1100\\n"+ "GPU: 1\\n TARGET_GRAPHICS_VERSION: gfx1200\\n'; }\n"+ "export HIP_VISIBLE_DEVICES=1"+ )+ assert self._run_install_sh_routing(preamble) == "rocm6.1"++ @pytest.mark.parametrize(+ ("gfx", "leaf", "expected_leaf", "expected_target"),+ (+ # already at or above the floor: no reroute, but the arch still needs it+ ("gfx1200", "rocm6.4", "rocm6.4", "true"),+ ("gfx1200", "rocm7.2", "rocm7.2", "true"),+ ("gfx1200", "rocm6.1", "rocm6.4", "true"),+ ("gfx1100", "rocm6.4", "rocm6.4", "false"),+ ("gfx1100", "rocm6.1", "rocm6.1", "false"),+ ),+ )+ def test_install_sh_marks_the_floor_target_independently_of_the_leaf(+ self, gfx, leaf, expected_leaf, expected_target+ ):+ """The migrated repair keys off the arch, so the flag cannot depend on a reroute."""+ result = self._install_sh_routing_result(f'export UNSLOTH_ROCM_GFX_ARCH="{gfx}"', leaf)+ assert result[:2] == (expected_leaf, expected_target)++ @pytest.mark.parametrize(+ ("gfx", "leaf", "expected_radeon"),+ (+ # The Radeon branch must not substitute repo.radeon.com wheels for the floor+ # index: rocm-rel-6.4's newest trio (torch 2.6.0+rocm6.4.0) has no gfx1102+ # Tensile libraries, and rocm-rel-7.2 carries neither gfx1102 nor gfx1100.+ ("gfx1102", "rocm6.1", "false"),+ ("gfx1200", "rocm6.1", "false"),+ ("gfx1201", "rocm6.1", "false"),+ # Cleared even when the leaf satisfies the floor and the reroute is a no-op.+ ("gfx1102", "rocm6.4", "false"),+ ("gfx1102", "rocm7.2", "false"),+ # Every other Radeon keeps the branch.+ ("gfx1100", "rocm6.1", "true"),+ ("gfx1101", "rocm6.4", "true"),+ ),+ )+ def test_install_sh_floor_arches_leave_the_radeon_branch(self, gfx, leaf, expected_radeon):+ """A floored arch must not be handed repo.radeon.com wheels lacking its kernels."""+ result = self._install_sh_routing_result(+ f'export UNSLOTH_ROCM_GFX_ARCH="{gfx}"', leaf, radeon_in = "true"+ )+ assert result[2] == expected_radeon, result++ @staticmethod+ def _run_migrated_rocm_repair(+ torch_version: str,+ hip: str,+ gfx_target: str,+ floor: "tuple[int, int]" = (6, 4),+ ) -> str:+ """Execute install.sh's migrated-environment ROCm repair with a stubbed venv torch."""+ shell = shutil.which("bash")+ if not shell:+ pytest.skip("bash needed to execute the migrated repair block")+ source = _INSTALL_SH_PATH.read_text(encoding = "utf-8")+ start = source.find(" # Repair ROCm torch if overwritten during migrated install")+ end = source.find(" _gfx906_bnb_prune", start)+ assert start >= 0 and end >= 0+ with tempfile.TemporaryDirectory() as d:+ venv_py = os.path.join(d, "python")+ with open(venv_py, "w", encoding = "utf-8") as fh:+ fh.write(+ "#!/bin/sh\n"+ f'exec {sys.executable} -c "\n'+ "import sys, types\n"+ "t = types.ModuleType('torch')\n"+ f"t.__version__ = '{torch_version}'\n"+ "v = types.ModuleType('torch.version')\n"+ f"v.hip = '{hip}'\n"+ "t.version = v\n"+ "sys.modules['torch'] = t\n"+ "sys.modules['torch.version'] = v\n"+ "exec(sys.argv[1])\n"+ '" "$2"\n'+ )+ os.chmod(venv_py, 0o755)+ script = (+ "set -euo pipefail\n"+ + _extract_sh_function_body(source, "_rocm_leaf_below")+ + "\n"+ + _extract_sh_function_body(source, "_venv_torch_rocm_below")+ + "\n"+ + "substep() { :; }\n"+ + '_install_torch_default_index() { printf "REINSTALL\\n"; }\n'+ + f'_VENV_PY="{venv_py}"\n'+ + f"_gfx_rocm64_target={gfx_target}\n"+ + f"_gfx_rocm64_floor_maj={floor[0]}\n_gfx_rocm64_floor_min={floor[1]}\n"+ + f'_torch_index_leaf="rocm{floor[0]}.{floor[1]}"\n'+ + source[start:end]+ + '\nprintf "DONE\\n"\n'+ )+ r = subprocess.run([shell, "-c", script], capture_output = True, text = True)+ assert r.returncode == 0, r.stderr+ return r.stdout++ @pytest.mark.parametrize(+ ("torch_version", "hip", "gfx_target", "floor", "reinstalls"),+ (+ # the gap: a migrated venv keeps its hip torch, so an older wheel survived+ ("2.5.1+rocm6.1", "6.1.40093", "true", (6, 4), True),+ ("2.7.0+rocm6.3", "6.3.42131", "true", (6, 4), True),+ ("2.8.0+rocm6.4", "6.4.43482", "true", (6, 4), False),+ ("2.11.0+rocm7.13.0", "7.13.0", "true", (6, 4), False),+ # gfx1102 floors at 6.3, so a 6.3 wheel already has its kernels.+ ("2.5.1+rocm6.1", "6.1.40093", "true", (6, 3), True),+ ("2.7.0+rocm6.3", "6.3.42131", "true", (6, 3), False),+ ("2.8.0+rocm6.4", "6.4.43482", "true", (6, 3), False),+ # not a floor arch: never repaired on the wheel family alone+ ("2.5.1+rocm6.1", "6.1.40093", "false", (6, 4), False),+ # no hip at all: the pre-existing repair owns this, floor or no floor+ ("2.5.1+cpu", "", "false", (6, 4), True),+ ),+ )+ def test_install_sh_migrated_repair_honors_the_rocm64_floor(+ self, torch_version, hip, gfx_target, floor, reinstalls+ ):+ out = self._run_migrated_rocm_repair(torch_version, hip, gfx_target, floor)+ assert "DONE" in out, out+ assert ("REINSTALL" in out) is reinstalls, out++ @pytest.mark.parametrize(+ "override",+ ("gfx1200:xnack-", "GFX1200:XNACK-", " gfx1200 ", "gfx1201:sramecc+:xnack-"),+ )+ def test_install_sh_normalizes_gcn_arch_name_override(self, override):+ """UNSLOTH_ROCM_GFX_ARCH copied from a HIP gcnArchName still matches the floor."""+ preamble = f'export UNSLOTH_ROCM_GFX_ARCH="{override}"'+ assert self._run_install_sh_routing(preamble) == "rocm6.4"++# TEST: install_python_stack.py -- torch-index MARKER mechanism (PR #6692)@@ -6140,7 +6708,7 @@ class TestStrixRocm71Override:assert not below(leaf), f"{leaf} must NOT reroute (>= floor or non-rocm)"def test_gfx_probe_survives_no_match_under_set_e(self):- """A gfx probe whose grep finds no match must not abort install.sh under+ """A gfx probe that finds no match must not abort install.sh underset -euo pipefail before the amd-smi fallback runs. The reroute case nowmatches every rocm* index, so this would break ordinary 6.x/7.2 installswith a flaky rocminfo. Executed with shimmed tools, not a text match."""@@ -6155,14 +6723,27 @@ class TestStrixRocm71Override:)assert block, "could not extract the gfx-detection block"with tempfile.TemporaryDirectory() as d:- # rocminfo emits no gfx token; amd-smi supplies gfx1151 (the fallback)- for name, out in (("rocminfo", "no gpu here"), ("amd-smi", "GPU: gfx1151")):+ # rocminfo emits no gfx token; amd-smi supplies gfx1151. `list` carries no arch+ # on a real host, so the shim keeps the subcommands distinct to prove that+ # `static --asic` is the one that answers.+ amd_smi = (+ '#!/bin/sh\ncase "$1" in\n'+ ' list) printf "GPU: 0\\n BDF: 0000:03:00.0\\n" ;;\n'+ ' *) printf "GPU: 0\\n TARGET_GRAPHICS_VERSION: gfx1151\\n" ;;\n'+ "esac\n"+ )+ for name, body in (+ ("rocminfo", '#!/bin/sh\ncat <<"EOT"\nno gpu here\nEOT\n'),+ ("amd-smi", amd_smi),+ ):p = os.path.join(d, name)with open(p, "w", encoding = "utf-8") as f:- f.write(f'#!/bin/sh\ncat <<"EOT"\n{out}\nEOT\n')+ f.write(body)os.chmod(p, 0o755)script = ('set -euo pipefail\nHIP_VISIBLE_DEVICES=""\nROCR_VISIBLE_DEVICES=""\n'+ + _gpu_record_helpers(source)+ + "\n"+ block.group(0)+ '\nprintf "OK:%s\\n" "$_gfx_all"\n')@@ -6205,7 +6786,11 @@ class TestStrixRocm71Override:f.write(body)os.chmod(p, 0o755)script = (- "set -euo pipefail\n" + block.group(0) + '\nprintf "OK:%s\\n" "$_runtime_gfx"\n'+ "set -euo pipefail\n"+ + _gpu_record_helpers(source)+ + "\n"+ + block.group(0)+ + '\nprintf "OK:%s\\n" "$_runtime_gfx"\n')def run(**extra):