Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

fix(studio/rocm): don't install for a shadowing iGPU on mixed AMD hosts (#7776) (#7778)

Tai An0c12d6473f95
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.py
index dda8c28099e..cc9ed6e73f6 100644
--- a/studio/install_llama_prebuilt.py
+++ b/studio/install_llama_prebuilt.py
@@ -92,6 +92,21 @@ WINDOWS_HIP_PREBUILT_GFX_TARGETS = frozenset(
# Family labels forwarded by update markers / --rocm-gfx (gfx110X.zip assets).
WINDOWS_ROCM_FAMILY_GFX_LABELS = frozenset({"gfx103x", "gfx110x", "gfx120x"})
+# APUs that lead HIP enumeration and shadow a discrete card (#7776). Mirrors
+# install_python_stack.py / setup.ps1 (TestShadowingIntegratedGfxParity keeps them in step);
+# duplicated rather than imported because this module is vendored standalone into the backend.
+SHADOWING_INTEGRATED_GFX = frozenset(
+ {
+ "gfx90c", # Renoir / Cezanne
+ "gfx1013", # Cyan Skillfish
+ "gfx1033", # Van Gogh
+ "gfx1035", # Rembrandt
+ "gfx1036", # Raphael / Mendocino
+ "gfx1103", # Phoenix / Hawk Point
+ "gfx1153", # Krackan Point 2
+ }
+)
+
# Exactly ggml-org release.yml's windows-hip "radeon" gpu_targets. The set above adds the
# fork-only bundles (gfx1034, gfx1103, gfx908, gfx90a), served only against the fork.
UPSTREAM_WINDOWS_HIP_GFX_TARGETS = frozenset(
@@ -2714,9 +2729,9 @@ def _apply_host_overrides(
)
gfx = _normalize_forwarded_gfx(override_rocm_gfx)
if gfx:
- # setup.ps1's pick is not fully visible-device aware (neither branch reads
- # CUDA_VISIBLE_DEVICES; amd-smi matches a bare integer only, so "1,0" falls back to
- # GPU 0), while _pick_rocm_gfx_target() honours all three vars with HIP's semantics.
+ # setup.ps1 resolves all three masks via Resolve-VisibleGpuIndex, but also applies the
+ # shadowing-iGPU preference (#7776) that _pick_rocm_gfx_target() does not, so the two
+ # can name different GPUs on a mixed APU + dGPU host.
# So keep a probed active arch when the forward is only advisory, else
# _should_auto_vulkan_for_amd_windows() reads a HIP-supported GPU the user masked
# off and installs an unusable HIP bundle instead of Vulkan. Advisory means:
@@ -2731,6 +2746,18 @@ def _apply_host_overrides(
_physical = _host_rocm_gfx_targets(host)
_active = _active_rocm_gfx_target(host)
_advisory = gfx in _physical or gfx in WINDOWS_ROCM_FAMILY_GFX_LABELS
+ # Except when setup deliberately skipped a shadowing APU for the discrete card (#7776):
+ # unmasked, _pick_rocm_gfx_target() still reads that APU as device 0, so discarding the
+ # forward would give torch the dGPU and llama.cpp the iGPU bundle. Unmasked only, since
+ # the repick must never override a pin.
+ if (
+ _advisory
+ and _active in SHADOWING_INTEGRATED_GFX
+ and gfx in _physical
+ and gfx not in SHADOWING_INTEGRATED_GFX
+ and not _hip_visible_device_mask_set()
+ ):
+ _advisory = False
if gfx != _manual and _active and gfx != _active and _advisory:
return dataclasses_replace(host, has_rocm = True)
return dataclasses_replace(
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 7f0fcf5ccc3..6818c86a794 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -633,11 +633,53 @@ def _detect_rocm_version() -> tuple[int, int] | None:
return None
-def _pick_visible_index(num_tokens: int) -> int:
- """Resolve HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES to an index into a
- list of length num_tokens. Returns 0 (first GPU) for unset, empty, '-1',
- UUID-style, or out-of-range values."""
- for _env in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+# APU gfx arches whose board commonly also carries a discrete Radeon. HIP often
+# enumerates the APU first, so an index-0 pick installs wheels for the iGPU and the
+# dGPU is never used (#7776: gfx1036 Raphael shadowing a gfx1200 RX 9060 XT). Excludes
+# the Strix arches (gfx1150/1151/1152): first-class training targets, left untouched.
+_SHADOWING_INTEGRATED_GFX: "frozenset[str]" = frozenset(
+ {
+ "gfx90c", # Renoir / Cezanne
+ "gfx1013", # Cyan Skillfish
+ "gfx1033", # Van Gogh
+ "gfx1035", # Rembrandt
+ "gfx1036", # Raphael / Mendocino
+ "gfx1103", # Phoenix / Hawk Point
+ "gfx1153", # Krackan Point 2
+ }
+)
+
+
+def _visible_devices_pinned() -> bool:
+ """True when the user selected devices via HIP_VISIBLE_DEVICES /
+ ROCR_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES.
+
+ First-set-wins, and ANY value counts -- including "" and "-1", which select
+ *no* GPU rather than meaning "unset". The ROCm runtime stores an explicitly
+ empty var as " " (clr `flags.cpp`) and then picks the HIP mask whenever its
+ first byte is not NUL (`paldevice.cpp` / `rocdevice.cpp`), so an empty
+ HIP_VISIBLE_DEVICES shadows CUDA_VISIBLE_DEVICES instead of deferring to it;
+ `parseRequestedDeviceList` then surfaces zero devices for " " and "-1", which
+ ROCR states outright. Whatever the user selected is honoured verbatim, so the
+ iGPU-shadowing preference below never overrides a deliberate choice. Same
+ precedence as `_pick_rocm_gfx_target` in install_llama_prebuilt.py."""
+ for _env in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ if os.environ.get(_env) is not None:
+ return True
+ return False
+
+
+def _pick_visible_index(num_tokens: int, warn: bool = True) -> int:
+ """Resolve HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES
+ to an index into a list of length num_tokens. Returns 0 (first GPU) for
+ unset, empty, '-1', UUID-style, or out-of-range values.
+
+ First-set-wins, matching `_visible_devices_pinned()` and
+ `_pick_rocm_gfx_target` in install_llama_prebuilt.py. Falling through to the
+ next var on "" / "-1" would contradict the runtime: an empty HIP mask
+ shadows CUDA_VISIBLE_DEVICES rather than deferring to it, and selects no GPU
+ at all."""
+ for _env in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
_val = os.environ.get(_env)
if _val is None:
continue
@@ -649,8 +691,22 @@ def _pick_visible_index(num_tokens: int) -> int:
_idx = int(_first)
if 0 <= _idx < num_tokens:
return _idx
+ # Say so rather than silently installing for GPU 0, which on a mixed host
+ # is the iGPU the user tried to mask off (setup.ps1's Resolve-VisibleGpuIndex
+ # warns the same). Callers with a deduplicated list pass warn=False: there the
+ # index space is arches, not devices, so out of range is normal.
+ if warn:
+ print(
+ f" [WARN] {_env}={_first} is out of range ({num_tokens} GPU(s) "
+ f"detected); defaulting to GPU 0 for arch selection."
+ )
except ValueError:
- pass
+ if warn:
+ print(
+ f" [WARN] {_env}={_val} is not a device index; defaulting to "
+ f"GPU 0 for arch selection. Use UNSLOTH_ROCM_GFX_ARCH to choose "
+ f"the arch directly."
+ )
return 0
return 0
@@ -664,20 +720,81 @@ def _detect_windows_gfx_arch() -> str | None:
return early and `studio update` cannot repair a CPU-only venv.
On multi-GPU hosts, detected gfx tokens are deduplicated (preserving
- enumeration order) and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES picks
- which to install for. The first GPU is used when no env var is set.
+ enumeration order) and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES /
+ CUDA_VISIBLE_DEVICES picks which to install for. Without a mask, the
+ first GPU is used -- except when it is a shadowing iGPU leading the
+ enumeration, in which case the discrete GPU is preferred (issue #7776).
"""
# 1. Explicit override (matches PowerShell installer's env-var path).
_override = os.environ.get("UNSLOTH_ROCM_GFX_ARCH")
if _override and _override.strip():
return _override.strip().lower()
- def _dedup_pick(tokens: list[str]) -> "str | None":
+ def _dedup_pick(
+ tokens: list[str],
+ mask_resolved: bool = False,
+ warn: bool = True,
+ ) -> "str | None":
if not tokens:
return None
- # Index into the full ordered list so HIP_VISIBLE_DEVICES addresses
- # GPU N on mixed-arch hosts, then return that arch.
- return tokens[_pick_visible_index(len(tokens))]
+ # Index into the full ordered list so the mask addresses GPU N on mixed-arch
+ # hosts. mask_resolved probes already did that: hipinfo is itself a HIP
+ # application, so under a mask it enumerates only the VISIBLE devices,
+ # renumbered from 0. Indexing that again applies the mask twice, so
+ # CUDA_VISIBLE_DEVICES=1,0 would read token 1 (the iGPU) on a host whose mask
+ # put the dGPU first. amd-smi and WMI list every GPU, so those keep the index.
+ _pick = tokens[0 if mask_resolved else _pick_visible_index(len(tokens), warn = warn)]
+ _distinct = list(dict.fromkeys(tokens))
+ if len(_distinct) < 2 or _visible_devices_pinned():
+ # A pin is honoured verbatim, but say so when it selected a card with no AMD
+ # Windows wheels while another enumerated GPU has them: torch silently drops
+ # to CPU and the mask is the reason.
+ if (
+ len(_distinct) >= 2
+ and _windows_rocm_index_url(_pick) is None
+ and any(_windows_rocm_index_url(t) for t in _distinct)
+ ):
+ _usable = [t for t in _distinct if _windows_rocm_index_url(t)]
+ print(
+ f" [WARN] the pinned GPU is {_pick}, which has no AMD Windows "
+ f"wheels, so torch will be CPU-only. {', '.join(_usable)} on this "
+ f"host does have wheels -- clear the visible-device mask or point "
+ f"it at that GPU to use it."
+ )
+ return _pick
+ # Unpinned mixed-arch host: skip a leading shadowing iGPU so the discrete card
+ # decides the wheel family (#7776), and say so, since only enumeration order
+ # put the APU first and the user may still want a different device.
+ if _pick in _SHADOWING_INTEGRATED_GFX:
+ _others = [t for t in tokens if t not in _SHADOWING_INTEGRATED_GFX]
+ # Deposing the pick for a card with no Windows wheels (gfx1036 + an older
+ # gfx1010) resolves to no index and drops the host to CPU, so prefer a
+ # wheel-backed candidate; fall back only when the pick has no wheels either.
+ _withWheels = [t for t in _others if _windows_rocm_index_url(t) is not None]
+ _candidates = _withWheels or (
+ [] if _windows_rocm_index_url(_pick) is not None else _others
+ )
+ if _candidates:
+ _other = _candidates[0]
+ # Not always device 1: on gfx1036,gfx1010,gfx1200 it is device 2, and
+ # saying "mask 1" would expose the gfx1010 the wheels do not target.
+ _other_idx = tokens.index(_other)
+ print(
+ f" multiple AMD GPUs detected ({', '.join(_distinct)}); "
+ f"installing for {_other} instead of the integrated {_pick}."
+ )
+ print(
+ f" Run 'setx HIP_VISIBLE_DEVICES {_other_idx}' and reopen your "
+ f"terminal so Unsloth uses {_other} at runtime too, not just at "
+ f"install time."
+ )
+ return _other
+ print(
+ f" multiple AMD GPUs detected ({', '.join(_distinct)}); "
+ f"installing for {_pick}. Set HIP_VISIBLE_DEVICES to the GPU index "
+ f"you want (then rerun) to install for a different device."
+ )
+ return _pick
# 2. hipinfo via PATH, then HIP_PATH\bin / ROCM_PATH\bin.
hipinfo = shutil.which("hipinfo")
@@ -712,10 +829,14 @@ def _detect_windows_gfx_arch() -> str | None:
text = result.stdout.decode(errors = "replace")
# findall gets every gcnArchName line so multi-GPU hosts are
# enumerable and HIP_VISIBLE_DEVICES selects correctly.
+ # Split on ':' like setup.ps1: "gfx90a:sramecc+:xnack-" matches neither
+ # the wheel table nor the shadowing set.
_tokens = [
- t.strip().lower() for t in re.findall(r"(?im)^\s*gcnArchName\s*:\s*(\S+)", text)
+ t.split(":")[0].strip().lower()
+ for t in re.findall(r"(?im)^\s*gcnArchName\s*:\s*(\S+)", text)
]
- _pick = _dedup_pick(_tokens)
+ # hipinfo already applied the mask, so do not apply it again.
+ _pick = _dedup_pick(_tokens, mask_resolved = True)
if _pick:
return _pick
except Exception:
@@ -757,6 +878,12 @@ def _detect_windows_gfx_arch() -> str | None:
# (amd-smi does not exist on Windows at all), but the display driver
# always knows the GPU name. Mirrors setup.ps1's $nameArchTable so a
# standalone `studio update` can repair a CPU-only venv on such hosts.
+ #
+ # ConfigManagerErrorCode 0 is "working properly". WMI keeps listing adapters that
+ # are disabled or on a driver error, and _dedup_pick()'s shadowing skip would let
+ # one depose the working iGPU. Same filter setup.ps1 applies to $wmiGpus, incl. the
+ # AMD name match: the masks index AMD devices, so an Intel or NVIDIA adapter would
+ # shift every index away from what HIP_VISIBLE_DEVICES names.
try:
result = subprocess.run(
[
@@ -764,7 +891,9 @@ def _detect_windows_gfx_arch() -> str | None:
"-NoProfile",
"-NonInteractive",
"-Command",
- "(Get-CimInstance Win32_VideoController).Name",
+ "Get-CimInstance Win32_VideoController | Where-Object { "
+ "$_.Name -match 'AMD|Radeon' } | ForEach-Object { "
+ '"$($_.Name)|$($_.ConfigManagerErrorCode)" }',
],
stdout = subprocess.PIPE,
stderr = subprocess.DEVNULL,
@@ -772,15 +901,56 @@ def _detect_windows_gfx_arch() -> str | None:
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
if result.returncode == 0:
- _tokens = []
- for _name in result.stdout.decode(errors = "replace").splitlines():
- _arch = _gfx_arch_from_gpu_name(_name.strip())
- if _arch:
- _tokens.append(_arch)
- _pick = _dedup_pick(_tokens)
+ # Lines are "<name>|<ConfigManagerErrorCode>"; a bare name (older probe
+ # output, and the shape most tests use) counts as healthy.
+ _all_names, _healthy = [], []
+ for _line in result.stdout.decode(errors = "replace").splitlines():
+ _line = _line.strip()
+ if not _line:
+ continue
+ _nm, _sep, _code = _line.rpartition("|")
+ if not _sep:
+ _nm, _code = _line, "0"
+ _nm = _nm.strip()
+ # Re-apply the vendor filter rather than trusting the command string:
+ # everything below treats these as AMD devices, and a stray NVIDIA or
+ # Intel adapter would shift the mask index and warn at a non-AMD user.
+ if not _nm or not re.search(r"AMD|Radeon", _nm, re.IGNORECASE):
+ continue
+ _all_names.append(_nm)
+ if _code.strip() in ("", "0"):
+ _healthy.append(_nm)
+ # Drop adapters Windows flags as not working so one cannot depose a live card.
+ # If that leaves NOTHING, the filter alone made the host look GPU-less and
+ # returning None hands it CPU torch: code 45 ("not connected") is routine on
+ # muxless laptops with a parked dGPU. Fall back to the full list -- with no
+ # healthy peer there is nothing to depose.
+ _names = _healthy or _all_names
+ _tokens = [_a for _a in map(_gfx_arch_from_gpu_name, _names) if _a]
+ # Resolve the mask over the ADAPTER list (setup.ps1's $nameIdx): a name the
+ # table does not know drops out of _tokens, and indexing that shortened list
+ # would name a different card.
+ _sel = _pick_visible_index(len(_names)) if _names else 0
+ _named = _gfx_arch_from_gpu_name(_names[_sel]) if _names else None
+ # Borrow another adapter's arch only when unpinned: under a mask,
+ # substituting installs for a GPU the user masked away.
+ if not _named and not _visible_devices_pinned() and _tokens:
+ _named = _tokens[0]
+ # Repick only when every AMD adapter mapped: an unknown name may BE the
+ # discrete card, so skipping the iGPU could pick the wrong one and the index
+ # would count arches, not devices. warn=False since the mask was already
+ # resolved and reported against the adapter list above.
+ _pick = _dedup_pick(_tokens, warn = False) if len(_tokens) == len(_names) else _named
if _pick:
print(f" gfx arch inferred from GPU name (WMI): {_pick}")
return _pick
+ if _names and not _pick:
+ # No arch means CPU-only torch; name the adapter instead of failing silently.
+ 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:
pass
return None
@@ -964,6 +1134,57 @@ def _windows_rocm_index_url(gfx_arch: str | None) -> str | None:
return f"{_ROCM_WINDOWS_INDEX_BASE}/{arch_family}/"
+def _rocm_family_token(text: str) -> "str | None":
+ """Family out of a 'rocm-sdk-libraries-<family>' name or requirement string."""
+ _m = re.search(r"rocm[-_]sdk[-_]libraries[-_]([A-Za-z0-9][A-Za-z0-9._-]*)", text, re.IGNORECASE)
+ if not _m:
+ return None
+ # Requirement strings carry a specifier and marker: "...-gfx120X-all==7.13.0; extra".
+ return re.split(r"[=<>!~;,\[\]()\s]", _m.group(1))[0].strip().lower().replace("_", "-")
+
+
+def _installed_rocm_wheel_family() -> str | None:
+ """The AMD per-arch family the installed torch actually runs on, normalized (e.g.
+ 'gfx120x-all'), or None when nothing on disk identifies it unambiguously.
+
+ torch.version.hip only says "some ROCm build", so it cannot tell a gfx103X wheel
+ from a gfx120X one. AMD's torch requires rocm[libraries], and that extra resolves
+ to the arch-specific rocm-sdk-libraries-<family> runtime, so the installed `rocm`
+ meta-package names the active family. Read it there rather than by scanning for a
+ rocm-sdk-libraries-* distribution: `rocm` is upgraded in place across a family
+ switch, but the previous arch-specific runtime keeps its own distribution name and
+ so is never uninstalled, and mistaking that orphan for the active family would
+ reinstall the multi-GB stack on every update.
+
+ None means "unknowable" -- an older wheel predating the split runtime, a pinned
+ index, or two runtimes with no `rocm` to arbitrate. Callers must leave the install
+ alone rather than guess.
+ """
+ try:
+ from importlib import metadata
+ for _req in metadata.requires("rocm") or []:
+ _fam = _rocm_family_token(_req)
+ if _fam:
+ return _fam
+ except Exception:
+ pass
+ # No `rocm` meta-package: fall back to the runtimes on disk, but only when exactly
+ # one is present, since with several there is nothing left to say which is active.
+ try:
+ from importlib import metadata
+
+ _found = set()
+ for _dist in metadata.distributions():
+ _fam = _rocm_family_token((_dist.metadata["Name"] or "").strip())
+ if _fam:
+ _found.add(_fam)
+ if len(_found) == 1:
+ return _found.pop()
+ except Exception:
+ return None
+ return None
+
+
def _detect_bnb_rocm_dll_ver() -> str | None:
"""Scan the installed bitsandbytes package for libbitsandbytes_rocm{VER}.dll.
@@ -1211,17 +1432,52 @@ def _has_usable_nvidia_gpu() -> bool:
return False
-def _detect_amd_gfx_codes() -> list[str]:
+# Which probe answered the last _detect_amd_gfx_codes() call: only rocminfo is subject
+# to a visible-device mask, so the Strix reroute needs to know. None when stubbed, which
+# keeps the plain indexing behaviour.
+_LAST_AMD_GFX_PROBE: "str | None" = None
+
+
+def _detect_amd_gfx_codes(dedup: bool = True) -> list[str]:
"""Return the AMD gfx ISA strings visible to ROCm (e.g. ['gfx1151']).
Probes rocminfo, then falls back to ``amd-smi list`` and ``amd-smi
static --asic`` for runtime-only Radeon hosts that ship amd-smi but no
rocminfo. Returns an empty list when no probe yields a gfx target.
+
+ dedup=False keeps one entry per DEVICE instead of one per arch, which a
+ caller resolving HIP_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES needs: those
+ mask values are device ordinals, so indexing a deduplicated list reads the
+ wrong card whenever the host has two GPUs of the same arch. rocminfo prints
+ the same token several times per agent (Name, ISA, marketing name), so split
+ on agent headers first, exactly as _list_rocm_gfx_targets() does, or one GPU
+ contributes several entries and every ordinal after it is wrong.
+
+ Records the answering probe in _LAST_AMD_GFX_PROBE, since only rocminfo is
+ filtered by a visible-device mask (and only by ROCR_VISIBLE_DEVICES).
"""
+ global _LAST_AMD_GFX_PROBE
+ _LAST_AMD_GFX_PROBE = None
def _extract(text: str) -> list[str]:
- codes = re.findall(r"gfx([1-9][0-9a-z]{2,3})", text.lower())
- return list(dict.fromkeys(f"gfx{c}" for c in codes))
+ if dedup:
+ codes = [f"gfx{c}" for c in re.findall(r"gfx([1-9][0-9a-z]{2,3})", text.lower())]
+ return list(dict.fromkeys(codes))
+ # One entry per agent section; fall back to dedup for flat output.
+ _sections = re.split(
+ r"(?mi)^\s*\*+\s*$\s*agent\s+\d+\s*$|\bagent\s+\d+\b|\bdevice\s*#\s*\d+\b",
+ text,
+ )
+ if len(_sections) > 1:
+ _per_device = []
+ for _sec in _sections[1:]:
+ _m = re.search(r"gfx[1-9][0-9a-z]{2,3}", _sec.lower())
+ if _m:
+ _per_device.append(_m.group(0))
+ if _per_device:
+ return _per_device
+ _raw = [f"gfx{c}" for c in re.findall(r"gfx([1-9][0-9a-z]{2,3})", text.lower())]
+ return list(dict.fromkeys(_raw))
probes: list[list[str]] = []
if shutil.which("rocminfo"):
@@ -1246,10 +1502,19 @@ def _detect_amd_gfx_codes() -> list[str]:
continue
codes = _extract(result.stdout)
if codes:
+ _LAST_AMD_GFX_PROBE = cmd[0]
return codes
return []
+def _first_set_visible_mask() -> "str | None":
+ """Name of the visible-device variable in force, first-set-wins, or None."""
+ for _env in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ if os.environ.get(_env) is not None:
+ return _env
+ return None
+
+
# Set by _ensure_rocm_torch() on success; suppresses the post-install AMD warning.
_rocm_windows_torch_installed: bool = False
@@ -2322,6 +2587,19 @@ def _ensure_rocm_torch() -> None:
_torch_already_rocm = True
except (OSError, subprocess.TimeoutExpired):
pass
+ # "Is ROCm" is not "is the RIGHT ROCm": wheels are per-family, so a host whose arch
+ # now resolves elsewhere (dGPU added, or the #7776 repick) would keep the old family
+ # forever. setup.ps1 force-reinstalls every run, so this only bites standalone
+ # `studio update`. Act only on a family read back positively, never on a guess.
+ if _torch_already_rocm and _win_rocm_pin is None:
+ _want = (_GFX_TO_AMD_INDEX_ARCH.get(gfx_arch or "") or "").lower()
+ _have = _installed_rocm_wheel_family()
+ if _want and _have and _have != _want:
+ print(
+ f" installed ROCm torch is the {_have} build but {gfx_arch} needs "
+ f"{_want} -- reinstalling for this GPU"
+ )
+ _torch_already_rocm = False
if not _torch_already_rocm:
index_url = _win_rocm_pin or _windows_rocm_index_url(gfx_arch)
if index_url is None:
@@ -2500,13 +2778,29 @@ def _ensure_rocm_torch() -> None:
and _explicit_rocm_torch_index_url() is None
and not _gfx906_arch_override
):
- gfx_codes = _detect_amd_gfx_codes()
+ # One entry per DEVICE: the mask names a device ordinal, so a deduplicated list
+ # picks the wrong card when two GPUs share an arch (gfx1100,gfx1100,gfx1151
+ # would read index 1 as the Strix).
+ gfx_devices = _detect_amd_gfx_codes(dedup = False)
+ gfx_codes = list(dict.fromkeys(gfx_devices))
_strix_gfx = {"gfx1151", "gfx1150", "gfx1152"}
_detected_strix = _strix_gfx.intersection(gfx_codes)
if _detected_strix:
- # Runtime-visible GPU (HIP_VISIBLE_DEVICES index into gfx_codes, else first);
- # skip the override unless it's Strix.
- _runtime_gfx = gfx_codes[_pick_visible_index(len(gfx_codes))] if gfx_codes else None
+ # rocminfo links HSA/ROCr directly and never loads HIP, so only
+ # ROCR_VISIBLE_DEVICES filters and renumbers its output; HIP_VISIBLE_DEVICES
+ # and CUDA_VISIBLE_DEVICES (a HIP-layer alias) do not touch it. Re-indexing an
+ # already-ROCR-filtered list applies the mask twice, while skipping the index
+ # for the other two would ignore the pin. amd-smi reads the driver and is
+ # filtered by none of them, so it always indexes.
+ _rocr_applied = (
+ _LAST_AMD_GFX_PROBE == "rocminfo"
+ and _first_set_visible_mask() == "ROCR_VISIBLE_DEVICES"
+ )
+ _runtime_gfx = (
+ gfx_devices[0 if _rocr_applied else _pick_visible_index(len(gfx_devices))]
+ if gfx_devices
+ else None
+ )
if _runtime_gfx in _strix_gfx:
_selected_gfx = _runtime_gfx
_amd_mirror = (
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index e043ed4f3b9..1ef26a3311e 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -1742,7 +1742,115 @@ function Invoke-AmdSmiNoElevate {
$HasROCm = $false
$HipSdkInstalled = $false # HIP SDK binary found (independent of device accessibility)
$ROCmGpuLabel = $null
+$script:ROCmGpuLabels = @() # every AMD adapter name WMI reported (shadowing-aware inference)
$script:ROCmGfxArch = $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
+# _SHADOWING_INTEGRATED_GFX in studio/install_python_stack.py. The Strix arches
+# (gfx1150/1151/1152) are deliberately absent: first-class training targets, untouched.
+$script:ShadowingIntegratedGfx = @(
+ "gfx90c", # Renoir / Cezanne
+ "gfx1013", # Cyan Skillfish
+ "gfx1033", # Van Gogh
+ "gfx1035", # Rembrandt
+ "gfx1036", # Raphael / Mendocino
+ "gfx1103", # Phoenix / Hawk Point
+ "gfx1153" # Krackan Point 2
+)
+
+# gfx arch -> AMD per-arch wheel index family. Defined here, not beside $ROCmIndexUrl,
+# because Resolve-ShadowingGfxPick runs during detection, long before the install block,
+# and must know which arches AMD ships Windows wheels for. In sync with
+# _GFX_TO_AMD_INDEX_ARCH (test_rocm_arch_table_parity.py).
+$archFamilyMap = @{
+ "gfx1201" = "gfx120X-all"; "gfx1200" = "gfx120X-all" # RDNA 4
+ "gfx1151" = "gfx1151"; "gfx1150" = "gfx1150" # RDNA 3.5 (Strix Halo/Point)
+ "gfx1152" = "gfx1152" # RDNA 3.5 (Krackan Point)
+ "gfx1103" = "gfx110X-all"; "gfx1102" = "gfx110X-all" # RDNA 3
+ "gfx1101" = "gfx110X-all"; "gfx1100" = "gfx110X-all"
+ "gfx1036" = "gfx103X-all"; "gfx1035" = "gfx103X-all" # RDNA 2 (RX 6000)
+ "gfx1034" = "gfx103X-all"; "gfx1033" = "gfx103X-all"
+ "gfx1032" = "gfx103X-all"; "gfx1031" = "gfx103X-all"
+ "gfx1030" = "gfx103X-all"
+ "gfx90a" = "gfx90a"; "gfx908" = "gfx908" # MI200/MI100
+}
+
+
+# True when any of the three masks is set. Mirrors _visible_devices_pinned(): ANY value
+# is a deliberate selection, "" and "-1" included -- those select NO GPU rather than
+# meaning "unset".
+function Test-VisibleDevicesPinned {
+ foreach ($visEnv in @($env:HIP_VISIBLE_DEVICES, $env:ROCR_VISIBLE_DEVICES, $env:CUDA_VISIBLE_DEVICES)) {
+ if ($null -ne $visEnv) { return $true }
+ }
+ return $false
+}
+
+# The one mask -> index resolver for every pick site below; the sites used to inline
+# their own expressions and disagreed (hipinfo rejected " 1 ", amd-smi rejected "1,0"),
+# and a mask Resolve-ShadowingGfxPick honours but the index ignores lands on GPU 0, the
+# very iGPU this preference exists to skip. Mirrors _pick_visible_index(): first-set-wins
+# (the runtime lets an empty HIP mask shadow CUDA_VISIBLE_DEVICES rather than defer to
+# it), and an unparseable or out-of-range value falls back to GPU 0.
+function Resolve-VisibleGpuIndex {
+ param([int]$Count)
+ foreach ($visEnv in @($env:HIP_VISIBLE_DEVICES, $env:ROCR_VISIBLE_DEVICES, $env:CUDA_VISIBLE_DEVICES)) {
+ if ($null -eq $visEnv) { continue }
+ $val = $visEnv.Trim()
+ if ($val -eq "" -or $val -eq "-1") { return 0 }
+ $first = ($val -split ',')[0].Trim()
+ # TryParse, not [int]: '2147483648' overflows and .NET's \d also matches full-width
+ # digits, and either cast throws a TERMINATING error under this script's
+ # $ErrorActionPreference = "Stop", aborting the install where nothing catches it.
+ [int]$parsed = 0
+ if ([int]::TryParse($first, [ref]$parsed)) {
+ if ($parsed -ge 0 -and $parsed -lt $Count) { return $parsed }
+ substep "[WARN] HIP/ROCR/CUDA_VISIBLE_DEVICES index $first is out of range ($Count GPU(s) detected); defaulting to GPU 0 for arch selection" "Yellow"
+ }
+ return 0
+ }
+ return 0
+}
+
+# Mirrors _dedup_pick(). setup.ps1 resolves the arch and builds $ROCmIndexUrl from it
+# before ever invoking the Python stack installer, so the shadowing-iGPU skip has to
+# happen here too or a fresh install still pulls the iGPU's wheel family. Returns $Picked
+# unchanged when pinned, when only one distinct arch exists, or when no discrete arch is.
+function Resolve-ShadowingGfxPick {
+ param([AllowNull()][string]$Picked, [AllowNull()][string[]]$AllArches)
+ if (-not $Picked) { return $Picked }
+ # Only arches in $archFamilyMap have an AMD Windows wheel index.
+ function Test-GfxHasWheels { param([AllowNull()][string]$Arch) return [bool]($Arch -and $archFamilyMap.ContainsKey($Arch)) }
+ # A selected device is honoured verbatim; never repick over the user.
+ if (Test-VisibleDevicesPinned) { return $Picked }
+ if ($script:ShadowingIntegratedGfx -notcontains $Picked) { return $Picked }
+ $distinctArches = @($AllArches | Select-Object -Unique)
+ if ($distinctArches.Count -lt 2) { return $Picked }
+ # Deposing a supported APU for a discrete card with no Windows wheels (gfx1036 + an
+ # older gfx1010) resolves to no index and drops the host to CPU, worse than the
+ # shadowing itself. So prefer a wheel-backed discrete card, and fall back to an
+ # unsupported one only when the pick has no wheels either: taking the first
+ # non-integrated arch instead sent gfx90c,gfx1010,gfx1200 to CPU torch despite the
+ # supported gfx1200. Mirrors _dedup_pick()'s `_withWheels or (...)`.
+ $pickedHasWheels = Test-GfxHasWheels $Picked
+ $others = @($AllArches | Where-Object { $script:ShadowingIntegratedGfx -notcontains $_ })
+ $withWheels = @($others | Where-Object { Test-GfxHasWheels $_ })
+ $candidates = if ($withWheels.Count -gt 0) { $withWheels }
+ elseif (-not $pickedHasWheels) { $others }
+ else { @() }
+ $discreteArch = $candidates | Select-Object -First 1
+ if (-not $discreteArch) { return $Picked }
+ # Not always device 1: on gfx1036,gfx1010,gfx1200 the pick is device 2, and
+ # naming 1 would expose the gfx1010 the wheels do not target.
+ $discreteIdx = [array]::IndexOf(@($AllArches), $discreteArch)
+ if ($discreteIdx -lt 0) { $discreteIdx = 1 }
+ substep "multiple AMD GPUs detected ($($distinctArches -join ', ')); installing for the discrete $discreteArch instead of the integrated $Picked" "Cyan"
+ # HIP still enumerates the iGPU as device 0 at runtime, so the wheels alone do not
+ # steer training to the dGPU; setx makes the mask persist across sessions.
+ substep "Run 'setx HIP_VISIBLE_DEVICES $discreteIdx' and reopen your terminal so Unsloth uses $discreteArch at runtime too, not just at install time" "Cyan"
+ return $discreteArch
+}
if (-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.
@@ -1830,9 +1938,13 @@ if (-not $HasNvidiaSmi) {
# Once the arch is printed, keep the ROCm wheel path.
$HasROCm = $true
$_hipAllArches = @([regex]::Matches($hipOut, "(?im)^\s*gcnArchName\s*:\s*(\S+)") | ForEach-Object { ($_.Groups[1].Value -split ':')[0].Trim().ToLower() })
- $_hipVisIdx = if ($env:HIP_VISIBLE_DEVICES -match '^\d') { [int]($env:HIP_VISIBLE_DEVICES -split ',')[0] } elseif ($env:ROCR_VISIBLE_DEVICES -match '^\d') { [int]($env:ROCR_VISIBLE_DEVICES -split ',')[0] } else { 0 }
if ($_hipAllArches.Count -gt 0) {
- $script:ROCmGfxArch = if ($_hipVisIdx -lt $_hipAllArches.Count) { $_hipAllArches[$_hipVisIdx] } else { $_hipAllArches[0] }
+ # hipinfo is itself a HIP application, so under a mask it already
+ # enumerated only the visible devices, renumbered from 0; indexing it
+ # again applies the mask twice and lands on the wrong card. amd-smi and
+ # the WMI path below list every GPU, so they still index.
+ $script:ROCmGfxArch = $_hipAllArches[0]
+ $script:ROCmGfxArch = Resolve-ShadowingGfxPick $script:ROCmGfxArch $_hipAllArches
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
} else {
$ROCmGpuLabel = "AMD ROCm"
@@ -1885,27 +1997,25 @@ if (-not $HasNvidiaSmi) {
$allGfxArches = @([regex]::Matches($smiOut, '(?i)\b(gfx\d+[a-z]?)\b') |
ForEach-Object { $_.Groups[1].Value.ToLower() })
if ($allGfxArches.Count -gt 0) {
- # Resolve which GPU index is runtime-visible. When a single
- # integer index is set, use it; fall back to index 0 otherwise
- # (comma-separated lists or unset → first GPU, same as before).
- $visGpu = if ($env:HIP_VISIBLE_DEVICES) { $env:HIP_VISIBLE_DEVICES }
- elseif ($env:ROCR_VISIBLE_DEVICES) { $env:ROCR_VISIBLE_DEVICES }
- else { $null }
- $gpuIdx = 0
- if ($visGpu -match '^\s*(\d+)\s*$') { $gpuIdx = [int]$Matches[1] }
- if ($gpuIdx -ge $allGfxArches.Count) {
- substep "[WARN] HIP/ROCR_VISIBLE_DEVICES index $gpuIdx is out of range ($($allGfxArches.Count) GPU(s) detected); defaulting to GPU 0 for arch selection" "Yellow"
- $gpuIdx = 0
- }
- $script:ROCmGfxArch = $allGfxArches[$gpuIdx]
+ # amd-smi lists every GPU regardless of the masks, so resolve the
+ # index here, via the shared helper so a comma list or a padded
+ # value cannot select a different GPU than elsewhere.
+ $script:ROCmGfxArch = $allGfxArches[(Resolve-VisibleGpuIndex $allGfxArches.Count)]
+ $script:ROCmGfxArch = Resolve-ShadowingGfxPick $script:ROCmGfxArch $allGfxArches
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
} else {
# Attempt 2: 'static --asic' exposes ASIC details on ROCm 6+,
# including the GFX target needed for wheel index selection.
$smiAsicOut = ""
try { $smiAsicOut = Invoke-AmdSmiNoElevate $amdSmiExe.Source @('static','--asic') } catch {}
- if ($smiAsicOut -match "(?i)\b(gfx\d+[a-z]?)\b") {
- $script:ROCmGfxArch = $Matches[1].ToLower()
+ # Every token, not just the first: this branch is reached precisely
+ # when 'list' saw multiple GPUs but printed no arches, so a leading
+ # iGPU here reintroduces #7776.
+ $asicGfxArches = @([regex]::Matches($smiAsicOut, '(?i)\b(gfx\d+[a-z]?)\b') |
+ ForEach-Object { $_.Groups[1].Value.ToLower() })
+ if ($asicGfxArches.Count -gt 0) {
+ $script:ROCmGfxArch = $asicGfxArches[(Resolve-VisibleGpuIndex $asicGfxArches.Count)]
+ $script:ROCmGfxArch = Resolve-ShadowingGfxPick $script:ROCmGfxArch $asicGfxArches
$ROCmGpuLabel = "AMD ROCm ($script:ROCmGfxArch)"
} elseif ($smiAsicOut -match "(?im)Market.?Name\s*[:\|]\s*([^\r\n]+)") {
$ROCmGpuLabel = "AMD ROCm ($($Matches[1].Trim()))"
@@ -1924,10 +2034,24 @@ if (-not $HasNvidiaSmi) {
# so the name-based inference below can still attempt an arch lookup.
if (-not $HasROCm) {
try {
- $wmiGpu = Get-WmiObject Win32_VideoController -ErrorAction SilentlyContinue |
- Where-Object { $_.Name -match "AMD|Radeon" } |
- Select-Object -First 1
- if ($wmiGpu) { $ROCmGpuLabel = $wmiGpu.Name }
+ # 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
+ # under HIP (#7776), and the inference below runs the same preference over the
+ # whole list. ConfigManagerErrorCode 0 is "working properly": a disabled or
+ # driver-errored Radeon must not depose a working iGPU.
+ $amdGpus = @(Get-CimInstance Win32_VideoController -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -match "AMD|Radeon" })
+ $healthyGpus = @($amdGpus | Where-Object {
+ ($null -eq $_.ConfigManagerErrorCode) -or ($_.ConfigManagerErrorCode -eq 0) })
+ # If that leaves none, the filter alone made the host look GPU-less and the
+ # inference forwards nothing: code 45 ("not connected") is routine on a muxless
+ # laptop with a parked dGPU, and with no healthy peer there is nothing to
+ # depose. Mirrors the same fallback in install_python_stack.py's WMI path.
+ $wmiGpus = if ($healthyGpus.Count -gt 0) { $healthyGpus } else { $amdGpus }
+ if ($wmiGpus.Count -gt 0) {
+ $script:ROCmGpuLabels = @($wmiGpus | ForEach-Object { $_.Name })
+ $ROCmGpuLabel = $script:ROCmGpuLabels[0]
+ }
} catch {}
}
# ── Arch resolution: env-var override → name inference ──────────────────
@@ -1962,14 +2086,39 @@ if (-not $HasNvidiaSmi) {
@{ P = "RX 6650|RX 6600|PRO W6600|PRO W6650"; A = "gfx1032" } # RDNA 2 (Navi 23) -- gfx103X family
@{ P = "RX 6500|RX 6400|RX 6300|PRO W6400|PRO W6500"; A = "gfx1034" } # RDNA 2 (Navi 24) -- gfx103X family
)
- foreach ($row in $nameArchTable) {
- if ($ROCmGpuLabel -match $row.P) {
- $script:ROCmGfxArch = $row.A
- $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"
- break
- }
+ function Get-GfxArchFromGpuName {
+ param([AllowNull()][string]$Name, [object[]]$Table)
+ if (-not $Name) { return $null }
+ foreach ($row in $Table) { if ($Name -match $row.P) { return $row.A } }
+ return $null
+ }
+ # Only the WMI path carries more than one name; other callers left a single
+ # synthesized label, so default to it.
+ $gpuNames = if ($script:ROCmGpuLabels) { @($script:ROCmGpuLabels) } else { @($ROCmGpuLabel) }
+ # Index over the ADAPTER list, not the inferred arches: an unrecognised name
+ # drops out below, and indexing the shortened list would name the wrong card.
+ $nameIdx = Resolve-VisibleGpuIndex $gpuNames.Count
+ $nameArches = @()
+ foreach ($gpuName in $gpuNames) {
+ $inferred = Get-GfxArchFromGpuName -Name $gpuName -Table $nameArchTable
+ if ($inferred) { $nameArches += $inferred }
+ }
+ $pickedName = Get-GfxArchFromGpuName -Name $gpuNames[$nameIdx] -Table $nameArchTable
+ # Borrow another adapter's arch only when unpinned: an unmappable leading
+ # adapter is exactly the #7776 iGPU and the named discrete card should decide,
+ # but under a mask substituting installs wheels for a GPU they masked away.
+ if (-not $pickedName -and -not (Test-VisibleDevicesPinned) -and $nameArches.Count -gt 0) {
+ $pickedName = $nameArches[0]
+ }
+ if ($pickedName) {
+ # Repick only when every adapter mapped: an unknown name may BE the
+ # discrete card, so skipping the iGPU could pick the wrong one.
+ $script:ROCmGfxArch = if ($nameArches.Count -eq $gpuNames.Count) {
+ Resolve-ShadowingGfxPick -Picked $pickedName -AllArches $nameArches
+ } else { $pickedName }
+ $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"
}
}
}
@@ -3917,18 +4066,6 @@ $ROCmIndexUrl = $null
# ROCm install still falls back to CPU below, so this is safe.
if (-not $TorchIndexPinned -and ($HasROCm -or $ROCmGfxArch) -and $CuTag -eq "cpu") {
$amdIndexBase = if ($env:UNSLOTH_ROCM_WINDOWS_MIRROR) { $env:UNSLOTH_ROCM_WINDOWS_MIRROR.TrimEnd('/') } else { "https://repo.amd.com/rocm/whl" }
- $archFamilyMap = @{
- "gfx1201" = "gfx120X-all"; "gfx1200" = "gfx120X-all" # RDNA 4
- "gfx1151" = "gfx1151"; "gfx1150" = "gfx1150" # RDNA 3.5 (Strix Halo/Point)
- "gfx1152" = "gfx1152" # RDNA 3.5 (Krackan Point)
- "gfx1103" = "gfx110X-all"; "gfx1102" = "gfx110X-all" # RDNA 3
- "gfx1101" = "gfx110X-all"; "gfx1100" = "gfx110X-all"
- "gfx1036" = "gfx103X-all"; "gfx1035" = "gfx103X-all" # RDNA 2 (RX 6000)
- "gfx1034" = "gfx103X-all"; "gfx1033" = "gfx103X-all"
- "gfx1032" = "gfx103X-all"; "gfx1031" = "gfx103X-all"
- "gfx1030" = "gfx103X-all"
- "gfx90a" = "gfx90a"; "gfx908" = "gfx908" # MI200/MI100
- }
# gfx120X and Strix have a null _grouped_mm kernel on torch <2.11.0.
# Mirrors the $torchFloorMap in install.ps1 so both installers enforce
# the same floor and ceiling when pulling from AMD's per-arch index.
diff --git a/tests/studio/install/test_rocm_arch_table_parity.py b/tests/studio/install/test_rocm_arch_table_parity.py
index 40f6858f7e8..9429abe9a23 100644
--- a/tests/studio/install/test_rocm_arch_table_parity.py
+++ b/tests/studio/install/test_rocm_arch_table_parity.py
@@ -54,6 +54,7 @@ _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"
+_PREBUILT_PY = PACKAGE_ROOT / "studio" / "install_llama_prebuilt.py"
_SPOOF_PY = PACKAGE_ROOT / "tests" / "_zoo_rocm_spoof.py"
@@ -647,5 +648,44 @@ class TestTorch211PinAllowlistParity:
assert leaves == self._EXPECTED, f"studio/setup.ps1 pins {sorted(leaves)}"
+class TestShadowingIntegratedGfxParity:
+ """The shadowing-APU skip (#7776) exists twice: studio/setup.ps1 resolves the
+ arch and builds $ROCmIndexUrl before it ever invokes the Python stack
+ installer, so both copies of the list have to agree or one entry point keeps
+ installing the iGPU's wheel family."""
+
+ _STRIX = {"gfx1150", "gfx1151", "gfx1152"}
+
+ def _setup_ps1_list(self):
+ source = _SETUP_PS1.read_text(encoding = "utf-8")
+ m = re.search(r"\$script:ShadowingIntegratedGfx\s*=\s*@\(([^)]*)\)", source)
+ assert m, "$script:ShadowingIntegratedGfx not found in studio/setup.ps1"
+ return set(re.findall(r'"([^"]+)"', m.group(1)))
+
+ def _prebuilt_list(self):
+ tree = ast.parse(_PREBUILT_PY.read_text(encoding = "utf-8"))
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and any(
+ getattr(t, "id", None) == "SHADOWING_INTEGRATED_GFX" for t in node.targets
+ ):
+ return set(ast.literal_eval(node.value.args[0]))
+ raise AssertionError("SHADOWING_INTEGRATED_GFX not found in install_llama_prebuilt.py")
+
+ def test_setup_ps1_matches_install_python_stack(self):
+ assert self._setup_ps1_list() == set(stack_mod._SHADOWING_INTEGRATED_GFX)
+
+ def test_install_llama_prebuilt_matches_install_python_stack(self):
+ # _apply_host_overrides() honours setup's repick only for these arches, so drift
+ # re-splits torch and llama.cpp across two GPUs on a mixed host.
+ assert self._prebuilt_list() == set(stack_mod._SHADOWING_INTEGRATED_GFX)
+
+ def test_strix_is_excluded_from_every_copy(self):
+ # Supported training targets, not shadowing APUs: listing them would silently
+ # redirect Strix hosts.
+ assert not (self._STRIX & set(stack_mod._SHADOWING_INTEGRATED_GFX))
+ assert not (self._STRIX & self._setup_ps1_list())
+ assert not (self._STRIX & self._prebuilt_list())
+
+
if __name__ == "__main__":
pytest.main([__file__, "-v"])
diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.py
index 51c2d6587c9..3bddd4188cb 100644
--- a/tests/studio/install/test_rocm_support.py
+++ b/tests/studio/install/test_rocm_support.py
@@ -1,6 +1,8 @@
"""AMD ROCm support tests across install pathways (all mocked, no AMD HW)."""
+import contextlib
import importlib.util
+import io
import json
import os
import re
@@ -678,6 +680,108 @@ class TestEnsureRocmTorch:
assert mock_pip.call_count == 1
assert "rocm7.1" in str(mock_pip.call_args_list[0])
+ @staticmethod
+ def _windows_repair(installed_family, gfx = "gfx1200"):
+ """Run the Windows ROCm repair with an already-ROCm torch on disk.
+
+ Returns the pip_install_try mock so callers can assert on the reinstall.
+ """
+ probe = MagicMock(returncode = 0, stdout = b"yes\n")
+ pip_try = MagicMock(return_value = True)
+ with patch.dict(os.environ, {}, clear = False):
+ os.environ.pop("UNSLOTH_ROCM_TORCH_INSTALLED", None)
+ with (
+ patch.object(stack_mod, "IS_WINDOWS", True),
+ patch.object(stack_mod, "IS_MACOS", False),
+ patch.object(stack_mod, "_TORCH_BACKEND", ""),
+ patch.object(stack_mod, "_explicit_rocm_torch_index_url", return_value = None),
+ patch.object(
+ stack_mod, "_explicit_unknown_family_torch_index_url", return_value = None
+ ),
+ patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = False),
+ patch.object(stack_mod, "_detect_windows_gfx_arch", return_value = gfx),
+ patch.object(
+ stack_mod, "_installed_rocm_wheel_family", return_value = installed_family
+ ),
+ patch.object(stack_mod, "_install_bnb_windows_rocm", return_value = True),
+ patch.object(stack_mod, "pip_install_try", pip_try),
+ patch("subprocess.run", return_value = probe),
+ ):
+ _ensure_rocm_torch()
+ return pip_try
+
+ def test_wheel_family_change_forces_a_reinstall(self):
+ # A host with gfx103X wheels for its APU keeps them forever once the #7776 repick
+ # moves it to the dGPU: torch.version.hip only says "ROCm", so the repair path saw
+ # a ROCm build and stopped. setup.ps1 force-reinstalls, so this is `studio update`.
+ pip_try = self._windows_repair("gfx103x-all")
+ assert pip_try.call_count == 1
+ assert "gfx120X-all" in str(pip_try.call_args)
+
+ def test_matching_wheel_family_is_left_alone(self):
+ # Negative control: the right family must not be re-downloaded on every update.
+ assert self._windows_repair("gfx120x-all").call_count == 0
+
+ def test_unknown_wheel_family_is_left_alone(self):
+ # Older wheels predate the split runtime, so the family is unreadable and
+ # guessing would force a multi-GB reinstall on every update.
+ assert self._windows_repair(None).call_count == 0
+
+ @staticmethod
+ def _dists(*names):
+ out = []
+ for n in names:
+ d = MagicMock()
+ d.metadata = {"Name": n}
+ out.append(d)
+ return out
+
+ def test_installed_wheel_family_reads_the_rocm_metapackage(self):
+ # AMD's torch requires rocm[libraries], and that extra names the arch-specific
+ # runtime, so the installed `rocm` meta-package is the authoritative record.
+ reqs = [
+ "rocm-sdk-core==7.13.0",
+ 'rocm-sdk-libraries-gfx120X-all==7.13.0; extra == "libraries"',
+ ]
+ with patch("importlib.metadata.requires", return_value = reqs):
+ assert stack_mod._installed_rocm_wheel_family() == "gfx120x-all"
+
+ def test_orphaned_runtime_does_not_masquerade_as_the_active_family(self):
+ # pip never uninstalls the old rocm-sdk-libraries-<family> on a switch (different
+ # distribution name), so reading the first one found would report the orphan and
+ # redownload the stack on every update.
+ reqs = ['rocm-sdk-libraries-gfx120X-all==7.13.0; extra == "libraries"']
+ dists = self._dists("rocm_sdk_libraries_gfx103X-all", "rocm_sdk_libraries_gfx120X-all")
+ with patch("importlib.metadata.requires", return_value = reqs):
+ with patch("importlib.metadata.distributions", return_value = dists):
+ assert stack_mod._installed_rocm_wheel_family() == "gfx120x-all"
+
+ def test_two_runtimes_without_a_metapackage_are_unknowable(self):
+ # No `rocm` to arbitrate between two runtimes on disk, so leave the install alone.
+ dists = self._dists("rocm_sdk_libraries_gfx103X-all", "rocm_sdk_libraries_gfx120X-all")
+ with patch("importlib.metadata.requires", return_value = None):
+ with patch("importlib.metadata.distributions", return_value = dists):
+ assert stack_mod._installed_rocm_wheel_family() is None
+
+ def test_single_runtime_without_a_metapackage_still_reads(self):
+ dists = self._dists("rocm_sdk_libraries_gfx1151")
+ with patch("importlib.metadata.requires", return_value = None):
+ with patch("importlib.metadata.distributions", return_value = dists):
+ assert stack_mod._installed_rocm_wheel_family() == "gfx1151"
+ with patch("importlib.metadata.requires", return_value = None):
+ with patch("importlib.metadata.distributions", return_value = []):
+ assert stack_mod._installed_rocm_wheel_family() is None
+
+ def test_switched_host_does_not_reinstall_on_every_update(self):
+ # End to end: after the gfx103X -> gfx120X switch the orphan is still installed
+ # and the next `studio update` must do nothing.
+ reqs = ['rocm-sdk-libraries-gfx120X-all==7.13.0; extra == "libraries"']
+ dists = self._dists("rocm_sdk_libraries_gfx103X-all", "rocm_sdk_libraries_gfx120X-all")
+ with patch("importlib.metadata.requires", return_value = reqs):
+ with patch("importlib.metadata.distributions", return_value = dists):
+ family = stack_mod._installed_rocm_wheel_family()
+ assert self._windows_repair(family).call_count == 0
+
@patch.object(stack_mod, "pip_install")
@patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = False)
@patch.object(stack_mod, "_has_rocm_gpu", return_value = True)
@@ -816,6 +920,133 @@ class TestEnsureRocmTorch:
assert "gfx1150" in torch_call
assert "torch>=2.11.0,<2.12.0" in torch_call
+ @patch.object(stack_mod, "IS_MACOS", False)
+ @patch("platform.machine", return_value = "x86_64")
+ @patch.object(stack_mod, "IS_WINDOWS", False)
+ @patch.object(stack_mod, "pip_install_try", return_value = True)
+ @patch.object(stack_mod, "pip_install")
+ @patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = False)
+ @patch.object(stack_mod, "_has_rocm_gpu", return_value = True)
+ @patch.object(stack_mod, "_detect_rocm_version", return_value = (7, 14))
+ @patch.object(
+ stack_mod, "_detect_amd_gfx_codes", return_value = ["gfx1100", "gfx1100", "gfx1151"]
+ )
+ def test_mask_indexes_devices_not_deduplicated_arches(
+ self, mock_gfx, mock_ver, mock_gpu, mock_nvidia, mock_pip, mock_pip_try, mock_machine
+ ):
+ # The mask names a device ordinal: on two gfx1100 plus a gfx1151, device 1 is the
+ # second gfx1100, but a deduplicated ['gfx1100','gfx1151'] reads index 1 as the
+ # Strix and routes the install to the Strix-only AMD index.
+ mock_probe = MagicMock()
+ mock_probe.returncode = 0
+ mock_probe.stdout = b"7.14.60850|2.11.0+rocm7.2\n"
+ buf = io.StringIO()
+ with patch.dict(os.environ, {"CUDA_VISIBLE_DEVICES": "1"}, clear = False):
+ for _v in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+ os.environ.pop(_v, None)
+ with contextlib.redirect_stdout(buf):
+ with patch("os.path.isdir", return_value = True):
+ with patch("subprocess.run", return_value = mock_probe):
+ _ensure_rocm_torch()
+ calls = str(mock_pip.call_args_list) + str(mock_pip_try.call_args_list)
+ assert "gfx1151" not in calls
+ assert "non-Strix runtime target (gfx1100)" in buf.getvalue()
+
+ @patch.object(stack_mod, "IS_MACOS", False)
+ @patch("platform.machine", return_value = "x86_64")
+ @patch.object(stack_mod, "IS_WINDOWS", False)
+ @patch.object(stack_mod, "pip_install_try", return_value = True)
+ @patch.object(stack_mod, "pip_install")
+ @patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = False)
+ @patch.object(stack_mod, "_has_rocm_gpu", return_value = True)
+ @patch.object(stack_mod, "_detect_rocm_version", return_value = (7, 14))
+ @patch.object(
+ stack_mod, "_detect_amd_gfx_codes", return_value = ["gfx1100", "gfx1100", "gfx1151"]
+ )
+ def test_mask_naming_the_strix_device_still_reroutes(
+ self, mock_gfx, mock_ver, mock_gpu, mock_nvidia, mock_pip, mock_pip_try, mock_machine
+ ):
+ # Negative control: device 2 really is the Strix, so the reroute must still fire.
+ mock_probe = MagicMock()
+ mock_probe.returncode = 0
+ mock_probe.stdout = b"7.14.60850|2.11.0+rocm7.2\n"
+ with patch.dict(os.environ, {"CUDA_VISIBLE_DEVICES": "2"}, clear = False):
+ for _v in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+ os.environ.pop(_v, None)
+ with patch("os.path.isdir", return_value = True):
+ with patch("subprocess.run", return_value = mock_probe):
+ _ensure_rocm_torch()
+ calls = str(mock_pip.call_args_list) + str(mock_pip_try.call_args_list)
+ assert "gfx1151" in calls
+
+ # rocminfo repeats the gfx token per agent (Name, ISA, marketing name), so a flat
+ # findall counts one GPU several times and every later ordinal is wrong.
+ _ROCMINFO = """
+*******
+Agent 1
+*******
+ Name: AMD Ryzen 9 7950X
+ Marketing Name: AMD Ryzen 9 7950X
+*******
+Agent 2
+*******
+ Name: gfx1100
+ Marketing Name: AMD Radeon RX 7900 XTX
+ ISA Info:
+ ISA 1
+ Name: amdgcn-amd-amdhsa--gfx1100
+*******
+Agent 3
+*******
+ Name: gfx1100
+ Marketing Name: AMD Radeon RX 7900 XTX
+ ISA Info:
+ ISA 1
+ Name: amdgcn-amd-amdhsa--gfx1100
+*******
+Agent 4
+*******
+ Name: gfx1151
+ Marketing Name: AMD Radeon 8060S
+ ISA Info:
+ ISA 1
+ Name: amdgcn-amd-amdhsa--gfx1151
+"""
+
+ @staticmethod
+ def _probe_gfx(out, dedup):
+ which = lambda n: "/usr/bin/rocminfo" if n == "rocminfo" else None # noqa: E731
+ with patch("shutil.which", side_effect = which):
+ with patch("subprocess.run", return_value = MagicMock(returncode = 0, stdout = out)):
+ return stack_mod._detect_amd_gfx_codes(dedup = dedup)
+
+ def test_gfx_probe_returns_one_entry_per_agent_not_per_token(self):
+ assert self._probe_gfx(self._ROCMINFO, False) == ["gfx1100", "gfx1100", "gfx1151"]
+ assert self._probe_gfx(self._ROCMINFO, True) == ["gfx1100", "gfx1151"]
+
+ def test_gfx_probe_falls_back_for_flat_output(self):
+ # amd-smi and test stubs emit no agent headers; those must still work.
+ flat = "Name: gfx1100\nName: gfx1100\nName: gfx1151\n"
+ assert self._probe_gfx(flat, False) == ["gfx1100", "gfx1151"]
+ assert self._probe_gfx(flat, True) == ["gfx1100", "gfx1151"]
+
+ 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)
+ assert stack_mod._LAST_AMD_GFX_PROBE == "rocminfo"
+
+ def test_first_set_visible_mask_is_first_set_wins(self):
+ with patch.dict(os.environ, {}, clear = False):
+ for _v in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ os.environ.pop(_v, None)
+ assert stack_mod._first_set_visible_mask() is None
+ os.environ["CUDA_VISIBLE_DEVICES"] = "1"
+ assert stack_mod._first_set_visible_mask() == "CUDA_VISIBLE_DEVICES"
+ os.environ["ROCR_VISIBLE_DEVICES"] = ""
+ assert stack_mod._first_set_visible_mask() == "ROCR_VISIBLE_DEVICES"
+ os.environ["HIP_VISIBLE_DEVICES"] = "0"
+ assert stack_mod._first_set_visible_mask() == "HIP_VISIBLE_DEVICES"
+
@patch.object(stack_mod, "IS_WINDOWS", False)
@patch.object(stack_mod, "pip_install_try", return_value = True)
@patch.object(stack_mod, "pip_install")
@@ -2962,6 +3193,261 @@ class TestDetectWindowsGfxArch:
result = stack_mod._detect_windows_gfx_arch()
assert result == "gfx1200"
+ def test_mixed_igpu_dgpu_prefers_discrete(self, monkeypatch):
+ # #7776: HIP enumerates the Raphael iGPU (gfx1036) before the discrete RX 9060 XT
+ # (gfx1200), so an index-0 pick installed gfx103X-all wheels and never used the dGPU.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1036\ngcnArchName : gfx1200\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1200"
+
+ def test_mixed_igpu_dgpu_reports_the_override_env_var(self, monkeypatch, capsys):
+ # The maintainer ask on #7776: say a second GPU is there and how to pick it.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1036\ngcnArchName : gfx1200\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ stack_mod._detect_windows_gfx_arch()
+ out = capsys.readouterr().out
+ assert "HIP_VISIBLE_DEVICES" in out
+ assert "gfx1036" in out and "gfx1200" in out
+
+ def test_explicit_visible_devices_still_wins_over_igpu_preference(self, monkeypatch):
+ # A user who pinned the iGPU on purpose must keep getting the iGPU.
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1036\ngcnArchName : gfx1200\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1036"
+
+ def test_strix_igpu_selection_is_unchanged(self, monkeypatch):
+ # gfx1151 is a supported training target, not a shadowing APU, so a Strix host
+ # must keep resolving to its own arch-specific wheels.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1151\ngcnArchName : gfx1200\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1151"
+
+ def test_single_igpu_host_is_unchanged(self, monkeypatch):
+ # Nothing to prefer: an APU-only box still installs for the APU.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1036\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1036"
+
+ def test_unsupported_discrete_does_not_depose_a_supported_igpu(self, monkeypatch):
+ # A supported APU next to a discrete card with no Windows wheels (gfx1010 is absent
+ # from _GFX_TO_AMD_INDEX_ARCH): preferring the dGPU purely for being discrete
+ # resolves to no index and falls back to CPU, worse than the shadowing itself.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ assert stack_mod._windows_rocm_index_url("gfx1010") is None
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1036\ngcnArchName : gfx1010\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1036"
+ assert stack_mod._windows_rocm_index_url(result) is not None
+
+ def test_unsupported_igpu_still_yields_to_the_discrete_card(self, monkeypatch):
+ # Mirror case: with neither pick wheel-backed the swap costs nothing, so the
+ # discrete card still wins and the guard is not over-tightened.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ assert stack_mod._windows_rocm_index_url("gfx1013") is None
+ assert stack_mod._windows_rocm_index_url("gfx1010") is None
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1013\ngcnArchName : gfx1010\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1010"
+
+ def test_cuda_visible_devices_also_pins_the_igpu(self, monkeypatch):
+ # HIP honours CUDA_VISIBLE_DEVICES with the same semantics as its own masks, so a
+ # host that exposed only GPU 0 that way keeps getting the iGPU.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1036\ngcnArchName : gfx1200\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1036"
+
+ def test_cuda_visible_devices_indexes_the_enumeration(self, monkeypatch):
+ # hipinfo is a HIP application, so a mask filters and renumbers its output before
+ # we see it: CUDA_VISIBLE_DEVICES=1 leaves the dGPU alone at logical 0. Re-indexing
+ # with the physical value applies the mask twice, which selected the #7776 iGPU.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1")
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1200\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1200"
+
+ def test_a_reordering_mask_is_not_applied_twice(self, monkeypatch):
+ # CUDA_VISIBLE_DEVICES=1,0 makes HIP expose [physical 1, physical 0], so hipinfo
+ # prints the dGPU first; indexing that again read token 1, the shadowing iGPU.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1,0")
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1200\ngcnArchName : gfx1036\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1200"
+
+ def test_cuda_visible_devices_index_matches_the_other_masks(self, monkeypatch):
+ # All three spellings resolve identically, comma-list and out-of-range included.
+ for _var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_var, raising = False)
+ for _value, _expected in (
+ ("1", 1),
+ ("1,0", 1),
+ ("7", 0),
+ ("-1", 0),
+ ("", 0),
+ ("GPU-abc", 0),
+ ):
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", _value)
+ assert stack_mod._pick_visible_index(2) == _expected, _value
+
+ @pytest.mark.parametrize("spelling", ["", "-1"])
+ def test_all_hiding_masks_count_as_a_selection(self, monkeypatch, spelling):
+ # "" and "-1" select NO GPU rather than meaning "unset": the runtime stores an
+ # empty var as " " (clr flags.cpp) and parseRequestedDeviceList then surfaces zero
+ # devices. So they are a deliberate choice and must suppress the shadowing skip.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", spelling)
+ assert stack_mod._visible_devices_pinned() is True
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"gcnArchName : gfx1036\ngcnArchName : gfx1200\n"
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ result = stack_mod._detect_windows_gfx_arch()
+ assert result == "gfx1036"
+
+ def _hipinfo_pick(self, arches):
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = "".join(f"gcnArchName : {a}\n" for a in arches).encode()
+ with patch("shutil.which", return_value = "/usr/bin/hipinfo"):
+ with patch("subprocess.run", return_value = mock_result):
+ return stack_mod._detect_windows_gfx_arch()
+
+ def test_an_all_hiding_hip_mask_shadows_a_later_cuda_mask(self, monkeypatch):
+ # clr picks the HIP mask whenever its first byte is not NUL and stores an empty var
+ # as " ", so an empty HIP_VISIBLE_DEVICES shadows CUDA_VISIBLE_DEVICES rather than
+ # deferring to it; falling through would resolve a device the runtime never exposes.
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ for _spelling in ("", "-1"):
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", _spelling)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1")
+ assert stack_mod._pick_visible_index(2) == 0
+ assert self._hipinfo_pick(["gfx1036", "gfx1200"]) == "gfx1036"
+
+ def test_gcn_arch_feature_suffix_is_stripped(self, monkeypatch):
+ # hipinfo can print "gfx90a:sramecc+:xnack-"; setup.ps1 splits on ':' and the
+ # unsplit token matched neither the wheel table nor the skip set.
+ for _m in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_m, raising = False)
+ assert self._hipinfo_pick(["gfx1036:xnack-", "gfx1200:xnack-"]) == "gfx1200"
+
+ def test_prefers_a_wheel_backed_discrete_over_an_unsupported_one(self, monkeypatch):
+ # gfx1010 has no Windows wheel index, so stopping at the first non-integrated
+ # token dropped a host with a perfectly good gfx1200 to CPU torch.
+ for _m in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_m, raising = False)
+ assert stack_mod._windows_rocm_index_url("gfx1010") is None
+ assert self._hipinfo_pick(["gfx1036", "gfx1010", "gfx1200"]) == "gfx1200"
+ # Same when the iGPU itself has no wheels: still prefer the supported card.
+ assert self._hipinfo_pick(["gfx1013", "gfx1010", "gfx1200"]) == "gfx1200"
+
+ def test_pinning_a_wheelless_gpu_says_why_torch_will_be_cpu(self, monkeypatch, capsys):
+ # The pin is honoured, but silently installing CPU torch while another enumerated
+ # GPU does have wheels hides that the mask caused it. A reordering mask puts the
+ # wheel-less card at logical 0 with both devices still visible to hipinfo.
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1,0")
+ assert self._hipinfo_pick(["gfx1010", "gfx1036"]) == "gfx1010"
+ out = capsys.readouterr().out
+ assert "no AMD Windows wheels" in out
+ assert "gfx1036" in out
+
+ def test_deduplicated_callers_do_not_get_a_bogus_range_warning(self, monkeypatch, capsys):
+ # _detect_amd_gfx_codes() dedupes, so on a dual same-arch Linux box the list is
+ # shorter than the device count and a valid index reads as out of range.
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "1")
+ assert stack_mod._pick_visible_index(1, warn = False) == 0
+ assert capsys.readouterr().out == ""
+ # The Windows arch-selection caller still warns.
+ assert stack_mod._pick_visible_index(1) == 0
+ assert "out of range" in capsys.readouterr().out
+
+ def test_advisory_names_the_selected_gpus_real_index(self, monkeypatch, capsys):
+ # Not always device 1: here it is device 2, and naming 1 would expose the
+ # gfx1010 the installed wheels do not target.
+ for _m in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_m, raising = False)
+ assert self._hipinfo_pick(["gfx1036", "gfx1010", "gfx1200"]) == "gfx1200"
+ out = capsys.readouterr().out
+ assert "HIP_VISIBLE_DEVICES 2" in out
+ assert "HIP_VISIBLE_DEVICES 1" not in out
+
+ def test_shadowing_set_holds_only_apu_arches(self):
+ # gfx1037 is not an AMDGPU target in LLVM, so no Windows tool emits it.
+ assert "gfx1037" not in stack_mod._SHADOWING_INTEGRATED_GFX
+ # gfx1033 (Van Gogh) has a wheel family, so omitting it let it pose as the
+ # "discrete" card and depose another APU.
+ assert "gfx1033" in stack_mod._SHADOWING_INTEGRATED_GFX
+ assert self._hipinfo_pick(["gfx1036", "gfx1033"]) == "gfx1036"
+
def test_returns_none_on_nonzero_returncode_without_gcnarchname(self):
# Non-zero exit without gcnArchName must return None (fall through to amd-smi/WMI).
mock_result = MagicMock()
@@ -3081,6 +3567,188 @@ class TestGfxArchNameFallback:
result = stack_mod._detect_windows_gfx_arch()
assert result is None
+ @staticmethod
+ def _wmi_arch(names, env):
+ """Drive the WMI fallback over `names`, emulating the probe's AMD filter."""
+ 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)
+ os.environ.update(env)
+ 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()
+
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "NVIDIA GeForce RTX 4090",
+ "Intel(R) Arc(TM) A770 Graphics",
+ "Microsoft Basic Display Adapter",
+ "Apple M3 Max",
+ ],
+ )
+ def test_non_amd_adapters_produce_no_amd_output(self, name):
+ # AMD-only path, so a CUDA or Intel user must never see it speak. The vendor filter
+ # lives in a PowerShell string, so Python re-applies it: a non-AMD adapter would
+ # shift the mask index and trigger ROCm advice on a host with no AMD GPU.
+ arch, out = self._wmi_arch([name], {"CUDA_VISIBLE_DEVICES": "0"})
+ assert arch is None
+ assert out == ""
+
+ @pytest.mark.parametrize("code", ["22", "45", "43", "1"])
+ def test_sole_unhealthy_adapter_still_yields_its_arch(self, code):
+ # The filter exists so a card Windows is not exposing cannot depose a live one.
+ # With one adapter there is nothing to depose, and filtering it out is the only
+ # reason the host looks GPU-less, handing a working Radeon CPU torch. Code 45
+ # ("not connected") is routine on muxless laptops.
+ arch, _ = self._wmi_arch([f"AMD Radeon RX 9060 XT|{code}"], {})
+ assert arch == "gfx1200"
+
+ def test_unhealthy_adapter_still_cannot_depose_a_healthy_one(self):
+ # Negative control: with a healthy iGPU present the disabled dGPU stays out, so
+ # the shadowing skip cannot install wheels for a GPU Windows never exposes.
+ arch, _ = self._wmi_arch(["AMD Radeon(TM) 780M Graphics|0", "AMD Radeon RX 9060 XT|22"], {})
+ assert arch == "gfx1103"
+
+ def test_mask_out_of_range_is_reported_once(self):
+ # _dedup_pick resolves the same masks again over its own list, so without
+ # warn=False the WMI path prints every out-of-range warning twice.
+ _, out = self._wmi_arch(["AMD Radeon RX 9060 XT|0"], {"HIP_VISIBLE_DEVICES": "1"})
+ assert out.count("is out of range") == 1
+
+ def test_wmi_probe_lists_only_amd_adapters(self):
+ # The masks index AMD devices, so an Intel or NVIDIA adapter ahead of the Radeon
+ # would shift every index. Same -match filter setup.ps1 applies to $wmiGpus.
+ source = _STACK_PATH.read_text(encoding = "utf-8")
+ assert "$_.Name -match 'AMD|Radeon'" in source
+ arch, _ = self._wmi_arch(
+ ["Intel(R) UHD Graphics", "AMD Radeon RX 9060 XT"], {"HIP_VISIBLE_DEVICES": "0"}
+ )
+ assert arch == "gfx1200"
+
+ def test_wmi_unmappable_adapter_suppresses_the_repick(self):
+ # A driver-only host can report a name the table does not know ("AMD Radeon
+ # Graphics"), which drops out of the arch list: skipping the iGPU could then land
+ # on the wrong card and the advisory would count arches, not GPUs. Like setup.ps1,
+ # repick only when every adapter mapped.
+ arch, out = self._wmi_arch(
+ ["AMD Radeon Graphics", "AMD Radeon 780M Graphics", "AMD Radeon RX 9060 XT"], {}
+ )
+ assert arch == "gfx1103"
+ assert "setx HIP_VISIBLE_DEVICES" not in out
+
+ def test_wmi_repicks_the_dgpu_when_every_adapter_maps(self):
+ # Negative control: fully mapped, the #7776 preference runs and the advisory
+ # names the dGPU's real index.
+ arch, out = self._wmi_arch(["AMD Radeon 780M Graphics", "AMD Radeon RX 9060 XT"], {})
+ assert arch == "gfx1200"
+ assert "setx HIP_VISIBLE_DEVICES 1" in out
+
+ def test_wmi_masked_unmappable_adapter_warns_instead_of_substituting(self):
+ # Under a mask the selected adapter is the user's choice, so another card's arch
+ # must not stand in (same rule as setup.ps1). That leaves no arch and torch goes
+ # CPU-only, which has to be said out loud.
+ arch, out = self._wmi_arch(
+ ["AMD Radeon Graphics", "AMD Radeon RX 9060 XT"], {"HIP_VISIBLE_DEVICES": "0"}
+ )
+ assert arch is None
+ assert "UNSLOTH_ROCM_GFX_ARCH" in out and "AMD Radeon Graphics" in out
+
+ def test_wmi_unpinned_unmappable_adapter_still_infers(self):
+ # Negative control: unpinned there is no choice to respect, so the adapter that
+ # did map still decides and the host keeps its wheels.
+ arch, _ = self._wmi_arch(["AMD Radeon Graphics", "AMD Radeon RX 9060 XT"], {})
+ assert arch == "gfx1200"
+
+ def test_wmi_mask_selects_the_adapter_it_names(self):
+ arch, _ = self._wmi_arch(
+ ["AMD Radeon 780M Graphics", "AMD Radeon RX 9060 XT"], {"HIP_VISIBLE_DEVICES": "0"}
+ )
+ assert arch == "gfx1103"
+
+ def test_wmi_fallback_skips_disabled_adapters(self):
+ # WMI keeps listing a Radeon that is disabled or on a driver error, and the
+ # shadowing skip would let one depose the working iGPU: a laptop with a live 780M
+ # and a disabled RX 9060 installed gfx120X-all wheels for a GPU Windows never
+ # exposes. setup.ps1 filters on ConfigManagerErrorCode, so this path does too.
+ captured = {}
+
+ ps_result = MagicMock()
+ ps_result.returncode = 0
+ ps_result.stdout = b"AMD Radeon(TM) 780M Graphics\r\n"
+
+ def _run(cmd, **kwargs):
+ if cmd and "powershell.exe" in str(cmd[0]).lower():
+ captured["cmd"] = cmd[-1]
+ return ps_result
+ raise FileNotFoundError(cmd[0])
+
+ 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 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()
+ assert result == "gfx1103"
+ assert "ConfigManagerErrorCode" in captured["cmd"]
+
+ @pytest.mark.skipif(shutil.which("pwsh") is None, reason = "pwsh not installed")
+ def test_wmi_adapter_filter_is_valid_powershell(self):
+ # The filter lives in a Python string, so nothing else checks it. Run the real
+ # expression over stand-ins: a null error code (absent on some drivers) and 0
+ # stay, anything else goes.
+ source = _STACK_PATH.read_text(encoding = "utf-8")
+ assert "ConfigManagerErrorCode" in source
+ script = """
+class FakeAdapter { [string]$Name; [object]$ConfigManagerErrorCode }
+$adapters = @(
+ [FakeAdapter]@{ Name = 'AMD Radeon(TM) 780M Graphics'; ConfigManagerErrorCode = 0 }
+ [FakeAdapter]@{ Name = 'AMD Radeon RX 9060 XT'; ConfigManagerErrorCode = 22 }
+ [FakeAdapter]@{ Name = 'AMD Radeon RX 7900 XTX'; ConfigManagerErrorCode = $null }
+)
+($adapters | Where-Object { ($null -eq $_.ConfigManagerErrorCode) -or (
+ $_.ConfigManagerErrorCode -eq 0) }).Name
+"""
+ out = subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],
+ check = True,
+ capture_output = True,
+ text = True,
+ ).stdout.split()
+ assert "9060" not in " ".join(out)
+ assert "780M" in " ".join(out) and "7900" in " ".join(out)
+
def test_stack_probes_venv_hipinfo(self):
"""venv Scripts hipInfo.exe (from AMD torch wheels) must be a probe candidate for driver-only hosts."""
source = _STACK_PATH.read_text(encoding = "utf-8")
@@ -3098,6 +3766,216 @@ class TestGfxArchNameFallback:
assert 'shutil.which("amd-smi") is None' in source
+class TestSetupPs1ShadowingParity:
+ """setup.ps1 resolves the arch and builds $ROCmIndexUrl itself, before the Python
+ stack installer ever runs, so both halves of the #7776 preference have to exist in
+ the PowerShell mirror too or a fresh Windows install still picks the iGPU."""
+
+ @staticmethod
+ def _setup_ps1() -> str:
+ return (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
+
+ def test_repick_is_wheel_aware(self):
+ # Mirrors _dedup_pick()'s guard: deposing a supported APU for a discrete card with
+ # no Windows wheels resolves to no index and drops the host to CPU.
+ source = self._setup_ps1()
+ body = source[source.index("function Resolve-ShadowingGfxPick") :]
+ body = body[: body.index("\n}\n")]
+ assert "archFamilyMap" in body, "repick must consult the wheel index map"
+ assert "pickedHasWheels" in body
+
+ def test_arch_family_map_precedes_the_repick(self):
+ # Consumed during detection now, not just at install time, so it must be
+ # defined before the function that reads it.
+ source = self._setup_ps1()
+ assert source.index("$archFamilyMap = @{") < source.index(
+ "function Resolve-ShadowingGfxPick"
+ )
+
+ def test_wmi_fallback_keeps_every_amd_adapter(self):
+ # WMI orders controllers as the driver stack enumerated them, so taking the first
+ # AMD match reintroduced #7776 on Adrenalin-only hosts (a 780M ahead of an RX
+ # 9060 XT inferred gfx1103 and installed gfx110X-all wheels).
+ source = self._setup_ps1()
+ block = source[source.index("$amdGpus = @(Get-CimInstance Win32_VideoController") :]
+ block = block[: block.index("$ROCmGpuLabel = $script:ROCmGpuLabels[0]")]
+ assert "Select-Object -First 1" not in block
+ # A disabled or driver-errored Radeon must not depose a working iGPU.
+ assert "ConfigManagerErrorCode" in block
+ # ... but when the filter would leave nothing, keep the parked card rather than
+ # reporting no AMD GPU (matches the Python WMI path).
+ assert "if ($healthyGpus.Count -gt 0) { $healthyGpus } else { $amdGpus }" in block
+
+ def test_index_picks_read_the_same_masks_as_the_pin_check(self):
+ # Resolve-ShadowingGfxPick honours CUDA_VISIBLE_DEVICES as a pin, so every site
+ # that turns a mask into an index must read it too, or the skip is suppressed
+ # while the index still resolves to GPU 0. One shared helper keeps them agreeing.
+ source = self._setup_ps1()
+ helper = source[source.index("function Resolve-VisibleGpuIndex") :]
+ helper = helper[: helper.index("\n}\n")]
+ for _mask in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ assert _mask in helper
+ # hipinfo, amd-smi list, amd-smi static --asic, WMI name inference.
+ assert (
+ source.count("Resolve-VisibleGpuIndex $") + source.count("Resolve-VisibleGpuIndex ")
+ >= 4
+ )
+ # No pick site may still resolve a mask on its own.
+ assert "$_hipVisIdx = if (" not in source
+ assert "$visGpu = if (" not in source
+
+ def test_hipinfo_is_not_reindexed(self):
+ # hipinfo already applied the mask; only amd-smi and WMI may call the index
+ # resolver, or the mask lands twice.
+ source = self._setup_ps1()
+ hipinfo = source[source.index("$_hipAllArches.Count -gt 0") :]
+ hipinfo = hipinfo[: hipinfo.index("Resolve-ShadowingGfxPick")]
+ assert "Resolve-VisibleGpuIndex" not in hipinfo
+ assert "$_hipAllArches[0]" in hipinfo
+
+ def test_unknown_selected_wmi_adapter_is_not_substituted(self):
+ # Borrowing another adapter's arch is right when nothing was selected, but under
+ # a mask it installs for a GPU the user masked away.
+ source = self._setup_ps1()
+ block = source[source.index("$pickedName = Get-GfxArchFromGpuName") :]
+ block = block[: block.index("if ($pickedName) {")]
+ assert "Test-VisibleDevicesPinned" in block
+
+ def test_name_inference_runs_the_shadowing_pick(self):
+ # Every AMD adapter name gets an arch, then the same preference chooses.
+ source = self._setup_ps1()
+ assert "Get-GfxArchFromGpuName" in source
+ infer = source[source.index("$nameArches = @()") :]
+ infer = infer[: infer.index("Tip: set UNSLOTH_ROCM_GFX_ARCH")]
+ assert "Resolve-ShadowingGfxPick" in infer
+
+
[email protected](shutil.which("pwsh") is None, reason = "pwsh not installed")
+class TestSetupPs1ShadowingBehaviour:
+ """Runs the real Resolve-ShadowingGfxPick / Resolve-VisibleGpuIndex. The parity
+ class above only greps text, so a rename fails it while a semantic bug passes.
+ Both helpers are sliced out by AST -- setup.ps1 is never dot-sourced."""
+
+ _HARNESS = r"""
+$ErrorActionPreference = "Stop"
+$errors = $null; $tokens = $null
+$ast = [System.Management.Automation.Language.Parser]::ParseFile($env:SETUP_PS1, [ref]$tokens, [ref]$errors)
+if ($errors -and $errors.Count -gt 0) { throw "setup.ps1 has $($errors.Count) parse errors" }
+function substep { param([string]$Message, [string]$Color = "DarkGray") }
+foreach ($n in @("Test-VisibleDevicesPinned", "Resolve-VisibleGpuIndex", "Resolve-ShadowingGfxPick")) {
+ $f = $ast.Find({ param($x) $x -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $x.Name -eq $n }, $true)
+ if (-not $f) { throw "$n not found" }
+ Invoke-Expression $f.Extent.Text
+}
+foreach ($v in @('$script:ShadowingIntegratedGfx', '$archFamilyMap')) {
+ $a = $ast.FindAll({ param($x) $x -is [System.Management.Automation.Language.AssignmentStatementAst] }, $true) |
+ Where-Object { $_.Left.Extent.Text -eq $v } | Select-Object -First 1
+ if (-not $a) { throw "$v not found" }
+ Invoke-Expression $a.Extent.Text
+}
+"""
+
+ def _run(
+ self,
+ body: str,
+ env: "dict[str, str] | None" = None,
+ ) -> str:
+ merged = {k: v for k, v in os.environ.items() if not k.endswith("_VISIBLE_DEVICES")}
+ merged["SETUP_PS1"] = str(PACKAGE_ROOT / "studio" / "setup.ps1")
+ merged.update(env or {})
+ out = subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", self._HARNESS + body],
+ check = True,
+ capture_output = True,
+ text = True,
+ env = merged,
+ )
+ return out.stdout.strip()
+
+ _MIXED = 'Resolve-ShadowingGfxPick -Picked "gfx1036" -AllArches @("gfx1036","gfx1200")'
+
+ def test_unpinned_mixed_host_picks_the_discrete_gpu(self):
+ assert self._run(self._MIXED) == "gfx1200"
+
+ def test_explicit_pin_is_honoured(self):
+ assert self._run(self._MIXED, {"HIP_VISIBLE_DEVICES": "0"}) == "gfx1036"
+
+ def test_strix_is_not_deposed(self):
+ body = 'Resolve-ShadowingGfxPick -Picked "gfx1151" -AllArches @("gfx1151","gfx1200")'
+ assert self._run(body) == "gfx1151"
+
+ def test_all_hiding_spellings_count_as_a_selection(self):
+ # "" / "-1" surface zero devices, so they are a deliberate choice and suppress
+ # the repick rather than invite it.
+ for _val in ("", "-1"):
+ assert self._run(self._MIXED, {"HIP_VISIBLE_DEVICES": _val}) == "gfx1036"
+
+ @pytest.mark.parametrize("mask", ["1", "1,0", " 1 "])
+ def test_index_resolves_every_mask_spelling(self, mask):
+ # A comma list and a padded value used to resolve differently per branch, so a
+ # pinned host silently landed on the iGPU at index 0.
+ for _var in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ assert self._run("Resolve-VisibleGpuIndex 2", {_var: mask}) == "1"
+
+ def test_out_of_range_and_unparseable_masks_fall_back_to_zero(self):
+ for _val in ("7", "GPU-abc123", "-1", ""):
+ assert self._run("Resolve-VisibleGpuIndex 2", {"HIP_VISIBLE_DEVICES": _val}) == "0"
+
+ def test_an_all_hiding_hip_mask_shadows_a_later_cuda_mask(self):
+ # First-set-wins, as in Python: an empty HIP mask shadows CUDA_VISIBLE_DEVICES
+ # in the runtime rather than deferring to it.
+ env = {"HIP_VISIBLE_DEVICES": "", "CUDA_VISIBLE_DEVICES": "1"}
+ assert self._run("Resolve-VisibleGpuIndex 2", env) == "0"
+
+ def test_wheelless_discrete_does_not_depose_a_supported_igpu(self):
+ body = 'Resolve-ShadowingGfxPick -Picked "gfx1036" -AllArches @("gfx1036","gfx1010")'
+ assert self._run(body) == "gfx1036"
+
+ def test_wheelless_igpu_still_prefers_a_wheel_backed_discrete(self):
+ # PowerShell mirror of test_prefers_a_wheel_backed_discrete_over_an_unsupported_one.
+ # gfx90c (Cezanne) has no wheel index, so the guard above is inactive and every
+ # discrete arch qualifies: taking the first landed on the wheel-less gfx1010,
+ # $ROCmIndexUrl stayed null, and the install went CPU-only despite the gfx1200.
+ for _igpu in ("gfx90c", "gfx1013", "gfx1153"):
+ body = (
+ f'Resolve-ShadowingGfxPick -Picked "{_igpu}" '
+ f'-AllArches @("{_igpu}","gfx1010","gfx1200")'
+ )
+ assert self._run(body) == "gfx1200", _igpu
+ # Not over-tightened: with nothing wheel-backed to move to, a wheel-less iGPU
+ # still yields to the discrete card, as _dedup_pick() does.
+ body = 'Resolve-ShadowingGfxPick -Picked "gfx90c" -AllArches @("gfx90c","gfx1010")'
+ assert self._run(body) == "gfx1010"
+
+ def test_advisory_names_the_selected_gpus_real_index(self):
+ body = (
+ '$null = Resolve-ShadowingGfxPick -Picked "gfx1036" '
+ '-AllArches @("gfx1036","gfx1010","gfx1200"); '
+ '($script:Msgs -join " ")'
+ )
+ harness = self._HARNESS.replace(
+ 'function substep { param([string]$Message, [string]$Color = "DarkGray") }',
+ 'function substep { param([string]$Message, [string]$Color = "DarkGray") '
+ "$script:Msgs += $Message }\n$script:Msgs = @()",
+ )
+ merged = {k: v for k, v in os.environ.items() if not k.endswith("_VISIBLE_DEVICES")}
+ merged["SETUP_PS1"] = str(PACKAGE_ROOT / "studio" / "setup.ps1")
+ out = subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", harness + body],
+ check = True,
+ capture_output = True,
+ text = True,
+ env = merged,
+ ).stdout
+ assert "HIP_VISIBLE_DEVICES 2" in out
+ assert "HIP_VISIBLE_DEVICES 1" not in out
+
+ def test_degenerate_inputs_do_not_throw(self):
+ for _all in ("$null", "@()", '@("gfx1036")'):
+ body = f'Resolve-ShadowingGfxPick -Picked "gfx1036" -AllArches {_all}'
+ assert self._run(body) == "gfx1036"
+
+
# TEST: install_python_stack.py -- _install_bnb_windows_rocm
@@ -4847,9 +5725,9 @@ class TestApplyHostOverrides:
assert out.rocm_gfx_target == "gfx1200"
def test_forwarded_gfx_does_not_clobber_probed_arch(self, monkeypatch):
- # setup.ps1's pick is not fully visible-device aware (ignores CUDA_VISIBLE_DEVICES,
- # amd-smi branch drops comma masks), so when it resolved the host's OTHER physical
- # GPU it must not replace the arch detect_host() picked for the visible one.
+ # setup.ps1's pick is not fully visible-device aware (its amd-smi branch drops comma
+ # masks), so when it resolved the host's OTHER physical GPU it must not replace the
+ # arch detect_host() picked for the visible one.
monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
host = rocm_host(rocm_gfx_target = "gfx1010", rocm_gfx_targets = ["gfx1100", "gfx1010"])
out = _apply_host_overrides(host, override_rocm_gfx = "gfx1100")
@@ -4857,6 +5735,37 @@ class TestApplyHostOverrides:
assert out.rocm_gfx_targets == ["gfx1100", "gfx1010"]
assert out.has_rocm is True
+ def test_shadowing_igpu_does_not_veto_the_forwarded_dgpu(self, monkeypatch):
+ # #7776: unmasked, setup skips a leading APU for the discrete card, but
+ # _pick_rocm_gfx_target() still reads that APU as device 0. Discarding the forward
+ # as "advisory" would give torch gfx120X and llama.cpp the gfx1103 iGPU bundle.
+ monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
+ for _v in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_v, raising = False)
+ host = rocm_host(rocm_gfx_target = "gfx1103", rocm_gfx_targets = ["gfx1103", "gfx1200"])
+ out = _apply_host_overrides(host, override_rocm_gfx = "gfx1200")
+ assert out.rocm_gfx_target == "gfx1200"
+ assert out.rocm_gfx_targets == ["gfx1103", "gfx1200"]
+
+ def test_masked_host_still_keeps_the_probed_arch(self, monkeypatch):
+ # Negative control: the repick never overrides a pin, so under a mask a differing
+ # forward is a mispick again and the probe's pick survives.
+ monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
+ monkeypatch.setenv("HIP_VISIBLE_DEVICES", "0")
+ host = rocm_host(rocm_gfx_target = "gfx1103", rocm_gfx_targets = ["gfx1103", "gfx1200"])
+ out = _apply_host_overrides(host, override_rocm_gfx = "gfx1200")
+ assert out.rocm_gfx_target == "gfx1103"
+
+ def test_shadowing_exception_needs_a_probed_dgpu(self, monkeypatch):
+ # The exception only covers a card the probe saw; a family label is a bundle
+ # name, so gfx103X over a gfx1033 APU stays advisory as before.
+ monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
+ for _v in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_v, raising = False)
+ host = rocm_host(rocm_gfx_target = "gfx1033", rocm_gfx_targets = ["gfx1033"])
+ out = _apply_host_overrides(host, override_rocm_gfx = "gfx103X")
+ assert out.rocm_gfx_target == "gfx1033"
+
def test_forwarded_gfx_absent_from_host_stays_authoritative(self, monkeypatch):
# An arch no probe here ever reported is not a setup mispick: it is an explicit
# --rocm-gfx for a host whose probe is wrong or stale, so it must still win.