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
Studio: install torch from an index that has kernels for the user's AMD GPU (#9829)
oobabooga38440ee330ef
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 36e4c168640..1c61531b374 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -116,9 +116,12 @@ def _strix_needs_amd_arch_index(ver: tuple[int, int]) -> bool:"""True when Strix's generic pytorch.org index sits below the AMD arch floor(7.13), so gfx1150/1151 must use repo.amd.com's per-arch wheels. Mirrorsinstall.sh _rocm_leaf_below: reroute any generic rocm index (6.x/7.0/7.2 and a- future 7.3+), never one at/above the floor."""+ future 7.3+), never one at/above the floor.++ A version below every tag (what an unreadable one reads as, on a bundled-runtime host)+ resolves no generic index at all, so the per-arch index is the only route left."""key = next((k for k in sorted(_ROCM_TORCH_INDEX, reverse = True) if ver >= k), None)- return key is not None and key < _ROCM_ARCH_INDEX_FLOOR+ return key is None or key < _ROCM_ARCH_INDEX_FLOOR# MI50 / Radeon VII (gfx906, Vega 20): rocm6.4+/7.x wheels bundle ROCm libraries@@ -147,12 +150,31 @@ def _runtime_target_is_gfx906() -> bool:on a mixed host, so a non-gfx906 selection is never mis-identified as gfx906(and downgraded to rocm6.3). Mixed gfx906+dGPU hosts opt in with the env var."""+ # A mask hiding every GPU must not buy a force-reinstall onto an OLDER tag, minus+ # bitsandbytes, for the card the user hid. No probe below is filtered by a HIP mask, so+ # without this a container over a populated /sys/class/kfd is downgraded anyway. Above+ # the override, as in _runtime_gfx_target: hiding every GPU is a statement about this run.+ if _visible_masks_select_no_gpu():+ return False# Normalize a copied HIP gcnArchName (gfx906:sramecc-:xnack- -> gfx906) so the# feature-flag suffix does not defeat the exact comparison (mirrors device_type.py).override = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower().split(":")[0]if override:return override == "gfx906"- return set(_detect_amd_gfx_codes()) == {"gfx906"}+ # Unmasked: "the SOLE arch" is a question about the machine. ROCR_VISIBLE_DEVICES filters+ # rocminfo before it answers, so a mask naming the MI50 on a mixed host would present it+ # as the only card and unlock the downgrade the sole-arch rule exists to withhold there.+ return set(_detect_amd_gfx_codes(ignore_visible_masks = True)) == {"gfx906"}+++def _torch_below_211(installed_ver: str) -> bool:+ """True when an installed torch version string is readable and below 2.11.++ Unreadable reads as NOT below: this gates a --force-reinstall of a multi-GB stack, and+ a version string no regex can parse is not evidence the build is the broken one.+ """+ _m = re.match(r"\s*(\d+)\.(\d+)", installed_ver or "")+ return bool(_m) and (int(_m.group(1)), int(_m.group(2))) < (2, 11)# AMD per-arch leaves needing the torch 2.11 floor (the _grouped_mm <2.11 bug).@@ -189,6 +211,13 @@ _WINDOWS_ROCM_TORCH_PKG_SPECS: dict[str, tuple[str, str, str]] = {"gfx1150": _ROCM_TORCH_PKG_SPECS["rocm7.2"],"gfx1152": _ROCM_TORCH_PKG_SPECS["rocm7.2"],}+# Bound companion versions for ABI compatibility while retaining older per-arch mirror builds.+_ROCM_ARCH_INDEX_TORCH_PKG_SPEC: tuple[str, str, str] = (+ "torch>=2.4,<2.12.0",+ "torchvision>=0.19,<0.27.0",+ "torchaudio>=2.4,<2.12.0",+)+_PYTORCH_WHL_BASE = (os.environ.get("UNSLOTH_PYTORCH_MIRROR") or "https://download.pytorch.org/whl").rstrip("/")@@ -511,9 +540,12 @@ def _repair_bad_anyio() -> None:# AMD Windows ROCm wheels (repo.amd.com/rocm/whl/{arch_family}/).# Override with UNSLOTH_ROCM_WINDOWS_MIRROR for air-gapped/mirror installs.+# Kept verbatim: _index_url_join trims the path head, and only the path head. Trimming the+# whole URL eats a trailing "/" belonging to a query token, and "/" is in the base64+# alphabet. The Linux mirror passes its raw env value for the same reason._ROCM_WINDOWS_INDEX_BASE = (os.environ.get("UNSLOTH_ROCM_WINDOWS_MIRROR") or "https://repo.amd.com/rocm/whl"-).rstrip("/")+)# gfx arch → AMD index arch-family suffix; each family is a separate# pip index on repo.amd.com.@@ -781,7 +813,11 @@ def _visible_devices_pinned() -> bool:return False-def _pick_visible_index(num_tokens: int, warn: bool = True) -> int:+def _pick_visible_index(+ num_tokens: int,+ warn: bool = True,+ masks: "tuple[str, ...] | None" = None,+) -> int:"""Resolve HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICESto an index into a list of length num_tokens. Returns 0 (first GPU) forunset, empty, '-1', UUID-style, or out-of-range values.@@ -790,8 +826,11 @@ def _pick_visible_index(num_tokens: int, warn: bool = True) -> int:`_pick_rocm_gfx_target` in install_llama_prebuilt.py. Falling through to thenext var on "" / "-1" would contradict the runtime: an empty HIP maskshadows 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"):+ at all.++ ``masks`` narrows which layers are consulted. Callers that have already applied+ the ROCr layer themselves pass _HIP_LAYER_MASKS so it is not applied twice."""+ for _env in masks if masks is not None else _VISIBLE_DEVICE_MASKS:_val = os.environ.get(_env)if _val is None:continue@@ -1298,6 +1337,46 @@ def _infer_linux_amd_gfx_arch() -> "str | None":return _linux_amd_gfx_from_lspci()+# Mirrors already named, so a repeated repair does not repeat the notice.+_WARNED_QUERY_INDEX_BASES: "set[str]" = set()+++def _warn_query_index_unusable(base: str) -> None:+ """Say so when a mirror carries its credential in the query or fragment.++ pip joins each project URL as text (``posixpath.join(index_url, name)``), so+ ".../gfx1151/?token=x" asks the index ROOT with the name buried in the token, and a+ fragment never reaches the server. No URL shape makes pip send both a path leaf and a+ query, so the join below cannot repair this -- but a mirror that resolves nothing+ should say why rather than 404 per package.+ """+ if ("?" not in base and "#" not in base) or base in _WARNED_QUERY_INDEX_BASES:+ return+ _WARNED_QUERY_INDEX_BASES.add(base)+ _safe_print(+ " The ROCm mirror carries its credential in the URL query or fragment. pip\n"+ " appends the package name to the index URL as text, so the name lands inside\n"+ " the credential and no package resolves. Put the credential in the URL itself\n"+ " (https://user:token@host/path/), or in ~/.netrc, instead.\n"+ )+++def _index_url_join(base: str, leaf: str) -> str:+ """Append a path segment to a wheel index URL, keeping any query / fragment.++ rstrip + concat would bury the leaf in a token instead: "https://m/whl?token=x" ++ "gfx110X-all" asks for /whl with the arch inside the token. Splits on the FIRST of "?"+ or "#", so a URL carrying both keeps them in order. The lesser of two corruptions, not+ a working index: see _warn_query_index_unusable.+ """+ _warn_query_index_unusable(base)+ _cuts = [base.index(_c) for _c in "?#" if _c in base]+ _head, _sep, _tail = (+ (base[: min(_cuts)], base[min(_cuts)], base[min(_cuts) + 1 :]) if _cuts else (base, "", "")+ )+ return f"{_head.rstrip('/')}/{leaf}/{_sep}{_tail}"++def _amd_arch_index_url(gfx_arch: str | None) -> str | None:"""Return the AMD per-arch pip index URL for a gfx arch (Linux + Windows).@@ -1311,10 +1390,8 @@ def _amd_arch_index_url(gfx_arch: str | None) -> str | None:arch_family = _GFX_TO_AMD_INDEX_ARCH.get(gfx_arch or "")if arch_family is None:return None- base = (os.environ.get("UNSLOTH_AMD_ROCM_MIRROR") or "https://repo.amd.com/rocm/whl").rstrip(- "/"- )- return f"{base}/{arch_family}/"+ base = os.environ.get("UNSLOTH_AMD_ROCM_MIRROR") or "https://repo.amd.com/rocm/whl"+ return _index_url_join(base, arch_family)def _windows_rocm_index_url(gfx_arch: str | None) -> str | None:@@ -1322,7 +1399,7 @@ def _windows_rocm_index_url(gfx_arch: str | None) -> str | None:arch_family = _GFX_TO_AMD_INDEX_ARCH.get(gfx_arch or "")if arch_family is None:return None- return f"{_ROCM_WINDOWS_INDEX_BASE}/{arch_family}/"+ return _index_url_join(_ROCM_WINDOWS_INDEX_BASE, arch_family)def _rocm_family_token(text: str) -> "str | None":@@ -1376,6 +1453,31 @@ def _installed_rocm_wheel_family() -> str | None:return None+def _torch_requires_rocm_sdk() -> bool:+ """Whether the INSTALLED torch is an AMD per-arch build, i.e. torch itself pulls in the+ `rocm` SDK meta-package that names the family.++ _installed_rocm_wheel_family() reads that family off `rocm`, but pip leaves an orphan+ `rocm` behind when a generic ROCm torch is force-reinstalled over a per-arch one+ (measured 2026-08-27: 2.11.0+rocm7.13.0 -> 2.10.0+rocm7.1 dropped `rocm[libraries]`+ while `rocm` kept naming rocm-sdk-libraries-gfx110X-all). torch.version.hip is set on+ both, so a caller that SKIPS work on a family match must ask this too or the orphan+ hides the repair. One that reinstalls on a mismatch is fail-safe.+ """+ try:+ from importlib import metadata+ for _req in metadata.requires("torch") or []:+ # The distribution named exactly `rocm` ("rocm[libraries]==7.13.0"), anchored so+ # rocm-sdk-core and triton-rocm do not match. Case-insensitive: Requires-Dist+ # keeps the author's spelling while pip compares normalized, and reading+ # "ROCm[libraries]" as absent would call a per-arch build generic.+ if re.match(r"\s*rocm\s*(?:\[|[=<>!~;,]|$)", _req, re.IGNORECASE):+ return True+ except Exception:+ pass+ return False++def _detect_bnb_rocm_dll_ver() -> str | None:"""Scan the installed bitsandbytes package for libbitsandbytes_rocm{VER}.dll.@@ -1668,9 +1770,12 @@ def _detect_amd_gfx_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.+ # One entry per agent / GPU section; fall back to dedup for flat output. amd-smi+ # names no agent and heads each device with a line-leading "GPU: N" (or "GPU[N]");+ # without that header two cards of one arch collapse and later ordinals read wrong._sections = re.split(- r"(?mi)^\s*\*+\s*$\s*agent\s+\d+\s*$|\bagent\s+\d+\b|\bdevice\s*#\s*\d+\b",+ r"(?mi)^\s*\*+\s*$\s*agent\s+\d+\s*$|\bagent\s+\d+\b|\bdevice\s*#\s*\d+\b"+ r"|^[ \t]*gpu\s*[:\[]\s*\d+",text,)if len(_sections) > 1:@@ -1732,6 +1837,315 @@ def _detect_amd_gfx_codes(_HSA_SPOOFABLE_PHYSICAL_GFX: frozenset[str] = frozenset({"gfx1151", "gfx1150", "gfx1152"})+# Arches the generic pytorch.org ROCm wheels carry, from torch.cuda.get_arch_list() on+# 2026-08-27. Identical across every generic wheel the pins below resolve (2.10.0+rocm7.0,+# 2.10.0+rocm7.1, 2.11.0+rocm7.1, 2.11.0+rocm7.2). The rocm6.3 wheel carries a subset,+# without gfx1150/gfx1151, which the Strix reroute covers. torch 2.13.0+rocm7.1 DOES add+# gfx1103, so raising the <2.11 cap in _ROCM_TORCH_PKG_SPECS["_default"] means rechecking.+_GENERIC_ROCM_WHEEL_GFX: frozenset[str] = frozenset(+ {+ "gfx900",+ "gfx906",+ "gfx908",+ "gfx90a",+ "gfx942",+ "gfx950",+ "gfx1030",+ "gfx1100",+ "gfx1101",+ "gfx1102",+ "gfx1150",+ "gfx1151",+ "gfx1200",+ "gfx1201",+ }+)+++# Arches whose only wheel route is unreachable once a second GPU is present, so they must+# never depose an integrated card. gfx906's rocm6.3 route is gated on it being the sole+# detected arch (_runtime_target_is_gfx906), which no mixed host satisfies.+_MIXED_HOST_UNROUTABLE: "frozenset[str]" = frozenset({"gfx906"})+++def _gfx_route_on_host(gfx: "str | None", host_codes: "list[str] | None" = None) -> bool:+ """Whether an index can serve ``gfx`` ON THIS HOST, not on some host.++ _gfx_has_a_wheel_route asks it in the abstract, and gfx906 answers yes on the generic+ union while its only usable route -- the rocm6.3 legacy tag -- opens solely when gfx906+ is the one arch on the machine. ``host_codes`` is that machine BEFORE the ROCr layer, to+ match _runtime_target_is_gfx906's unfiltered probe: judging by the survivors would call+ a masked gfx906 alone, demote, then be refused the tag by a function seeing both cards.+ """+ return _gfx_has_a_wheel_route(gfx) and not (+ gfx in _MIXED_HOST_UNROUTABLE and len(set(host_codes or ())) > 1+ )+++def _gfx_has_a_wheel_route(gfx: "str | None") -> bool:+ """Whether ANY index this installer can pick carries kernels for ``gfx``.++ Either the generic pytorch.org wheel serves it or AMD publishes a per-arch index. An arch+ in neither (gfx1010 / RDNA 1) cannot be fixed by picking a different index, so it must+ never depose a card that can.+ """+ return bool(gfx) and (gfx in _GENERIC_ROCM_WHEEL_GFX or gfx in _GFX_TO_AMD_INDEX_ARCH)+++# _GENERIC_ROCM_WHEEL_GFX was measured on the tags the pins resolve (rocm7.0 and up), but+# _ROCM_TORCH_INDEX also maps ROCm 6.0-6.4, whose wheels predate some of these arches. A host+# can resolve an old tag while the KERNEL names a new card (a current amdgpu beside a stale+# /opt/rocm), leaving that wheel with no kernels for it. AMD's matrices put production+# gfx1200/gfx1201 at ROCm 6.4. gfx1150/gfx1151 need an entry despite the Strix reroute, which+# is gated on a ROCm VERSION and so inactive on a bundled-runtime host reading 0.0; rocm7.0+# is the oldest tag measured to carry them.+_GENERIC_WHEEL_GFX_MIN_ROCM: "dict[str, tuple[int, int]]" = {+ # gfx950 (MI350X / MI355X) dates to ROCm 7.0 and its ISA is genuinely new. It has no+ # _GFX_TO_AMD_INDEX_ARCH entry, so the reroute question still answers no for it: this+ # entry is read by the tag choice, which can pick a generic tag that does carry it.+ "gfx950": (7, 0),+ "gfx1150": (7, 0),+ "gfx1151": (7, 0),+ "gfx1200": (6, 4),+ "gfx1201": (6, 4),+}+++def _generic_rocm_wheel_lacks_kernels(+ gfx: "str | None", ver: "tuple[int, int] | None" = None+) -> bool:+ """Whether only an available AMD per-arch index carries kernels for ``gfx``.++ ``ver`` is the host ROCm version, when the caller has read one. Support belongs to the+ wheel a version resolves to, not to the generic index as a whole, so passing it lets an+ arch the OLD tags predate be rerouted rather than installed without kernels. Omitting it+ keeps the union reading, for callers with no version to key on.+ """+ if not gfx or gfx not in _GFX_TO_AMD_INDEX_ARCH:+ return False+ if gfx not in _GENERIC_ROCM_WHEEL_GFX:+ return True+ return ver is not None and _generic_tag_lacks_kernels(gfx, ver)+++def _generic_tag_lacks_kernels(gfx: "str | None", ver: "tuple[int, int]") -> bool:+ """Whether the generic wheel ``ver`` resolves to predates ``gfx``.++ The tag question alone, with no reroute attached, so it also answers for the arches+ _generic_rocm_wheel_lacks_kernels declines: that one chooses between indexes and stays+ silent with no AMD leaf to move to, while a TAG has a second answer -- take a newer one.+ """+ _min = _GENERIC_WHEEL_GFX_MIN_ROCM.get(gfx or "")+ if _min is None:+ return False+ # The tag the version selects, not the version: a 6.3.9 host takes the rocm6.3 wheel.+ # Below the oldest known index nothing resolves, and a wheel older than every tag this+ # installer knows predates the arches those tags were measured to add; reading that as+ # "support unknown" preserves exactly the build that cannot run.+ _tag_key = next((k for k in sorted(_ROCM_TORCH_INDEX, reverse = True) if ver >= k), None)+ return _tag_key is None or _tag_key < _min+++def _generic_only_target_below_floor(gfx: "str | None", ver: "tuple[int, int] | None") -> bool:+ """Whether a target with NO per-arch index is on a generic tag that predates it.++ The repair question for gfx950 and the other parts with no per-arch leaf.+ _generic_rocm_wheel_lacks_kernels answers False for them by design (it decides between+ INDEXES, and there is no second index), so callers asking only that read them as healthy+ on a wheel with no code for them. Their repair is a newer generic tag instead.++ An unreadable version answers True: that is the absence of a reading, not a reading that+ the tag clears the floor, and these parts run on hosts whose ROCm version does not read.+ """+ if not gfx or gfx in _GFX_TO_AMD_INDEX_ARCH or gfx not in _GENERIC_WHEEL_GFX_MIN_ROCM:+ return False+ return ver is None or _generic_tag_lacks_kernels(gfx, ver)+++def _runtime_gfx_target(+ inferred_linux_gfx: "str | None",+) -> "tuple[str | None, list[str], str | None, list[str]]":+ """Return the selected gfx target, detected arches, corrected physical arch, and the+ machine as the probes saw it before any ROCr filtering.++ Sources, strongest first: the ROCm userland probes, then KFD topology sysfs, then the+ explicit UNSLOTH_ROCM_GFX_ARCH / inferred product arch. Only the first can be renumbered+ by a visible-device mask, so it leads and the rest answer only when it says nothing. They+ matter because a runtime-only ROCm install ships neither rocminfo nor amd-smi, and with+ no target the callers keep a wheel with no kernels for this GPU.+ """+ # An empty (or "-1") mask selects NO GPU, deliberately, per _visible_devices_pinned.+ # Decided before any probe runs, because no probe is filtered the way the reroutes need:+ # only ROCR_VISIBLE_DEVICES reaches rocminfo, and amd-smi and KFD sysfs are filtered by+ # nothing. _pick_visible_index would then map the no-GPU mask onto index 0 and reinstall+ # a multi-GB stack for the card the user hid. A mask naming a device is unaffected.+ if _visible_masks_select_no_gpu():+ return None, [], None, []+ # An explicit arch outranks the probes, not merely the cases where they say nothing.+ # install.sh, _runtime_target_is_gfx906 and _detect_windows_gfx_arch all read it first;+ # resolving it last here made this the one place the escape hatch could be overruled by+ # the hardware it exists to override. The masks stay above it: hiding every GPU is a+ # statement about this run, while the arch names what to build for. Split on ":" as the+ # probe normalization does, or a copied gcnArchName ("gfx1151:sramecc-:xnack-") keys+ # no routing table.+ _explicit_gfx = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower().split(":", 1)[0]+ if _explicit_gfx:+ # Returning early skips _hsa_spoofed_physical_gfx, so answer the spoof here:+ # HSA_OVERRIDE_GFX_VERSION=11.0.0 is the workaround half these hosts carry, and+ # leaving it set while installing per-arch wheels is #7331 exactly (ROCr keeps+ # handing torch a gfx1100 agent the gfx1151 wheels have no code for). Only when the+ # override names a DIFFERENT arch: naming the arch you spoofed TO is deliberate.+ _spoofed = _explicit_gfx if _hsa_spoof_contradicts(_explicit_gfx) else None+ return _explicit_gfx, [_explicit_gfx], _spoofed, [_explicit_gfx]+ gfx_devices = _detect_amd_gfx_codes(dedup = False)+ # Keyed to the userland probe: ROCr spoofs that reading and no other.+ physical_gfx = _hsa_spoofed_physical_gfx(inferred_linux_gfx, gfx_devices)+ if physical_gfx is not None:+ gfx_devices = [physical_gfx]+ if not gfx_devices:+ # The kernel's own topology: one entry per GPU node, in node order.+ gfx_devices = _kfd_gfx_targets()+ # With no userland reading to distrust the spoof check above declined, but the+ # runtime is still spoofed and the reroutes install code for the physical arch alone+ # (#7331). amdkfd writes gfx_target_version and ROCr never touches it, so a+ # single-arch kernel reading the override contradicts IS the corroborated spoof.+ if physical_gfx is None and len(set(gfx_devices)) == 1:+ _override_arch = _hsa_override_gfx_arch(os.environ.get("HSA_OVERRIDE_GFX_VERSION"))+ if _override_arch is not None and _override_arch != gfx_devices[0]:+ physical_gfx = gfx_devices[0]+ if not gfx_devices and inferred_linux_gfx:+ # Nothing enumerated a device, so #7305's precedence (a runtime-visible arch outranks+ # the product name) has nothing left to protect. One guess is not a device list, so+ # an ordinal past its only entry indexes nothing, while _pick_visible_index's+ # out-of-range rule would answer with the guess and commit a per-arch reinstall to+ # it. Decline, unless the arch was named outright. Probed against a length nothing+ # can exceed, so a real ordinal comes back as itself rather than folding onto 0.+ if not (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip() and _pick_visible_index(+ _INDEX_PROBE_LEN, warn = False, masks = _HIP_LAYER_MASKS+ ):+ _safe_print(+ f" {_first_set_visible_mask()} selects a GPU past the only architecture\n"+ f" this host could name ({inferred_linux_gfx}, inferred from the product\n"+ f" name with no ROCm runtime to enumerate devices); which GPU it means\n"+ f" cannot be read here, so the AMD per-gfx index is left alone.\n"+ f" Set UNSLOTH_ROCM_GFX_ARCH to the arch you want wheels for.\n"+ )+ return None, [], None, []+ gfx_devices = [inferred_linux_gfx]+ # The machine as the probes saw it, before the ROCr layer reduces it to a lone survivor.+ # _gfx_route_on_host needs that shape, and "before the ROCr layer" holds only for a probe+ # ROCr does not filter: rocminfo runs on the ROCm user-mode stack, so a mask-selected MI50+ # beside a dGPU would read as single-architecture, the one premise _MIXED_HOST_UNROUTABLE+ # denies, and be granted the rocm6.3 tag -- a persistent downgrade of a shared install on+ # the strength of one session's mask. Ask the whole machine instead. Provenance is read+ # once, up here: the re-probe rewrites it, and the ROCr composition below asks about the+ # probe that produced ``gfx_devices``, not the extra one asked on its behalf.+ _probe_source = _LAST_AMD_GFX_PROBE+ if _probe_source == "rocminfo" and "ROCR_VISIBLE_DEVICES" in os.environ:+ try:+ _unmasked = _detect_amd_gfx_codes(dedup = False, ignore_visible_masks = True)+ except Exception:+ _unmasked = []+ host_codes = list(dict.fromkeys(_unmasked or gfx_devices))+ else:+ host_codes = list(dict.fromkeys(gfx_devices))+ # The two mask layers COMPOSE: ROCr filters first and HIP indexes the survivors (AMD's+ # GPU isolation guide: "the ROCR env var is processed first, which then reduces the+ # number of GPUs that HIP can select from"). Only rocminfo is renumbered by ROCr, whenever+ # ROCR_VISIBLE_DEVICES is set and not only when it is the first mask. amd-smi and KFD+ # sysfs are filtered by nothing, so for those the ROCr layer is applied here first --+ # indexing the unfiltered list picks a GPU the runtime never exposes.+ rocr_applied = _probe_source == "rocminfo" and "ROCR_VISIBLE_DEVICES" in os.environ+ _unlike_adapters = len(set(gfx_devices)) > 1+ if not rocr_applied:+ # amd-smi enumerates in DISCOVERY order over its KFD view, while the masks index+ # HIP/ROCr order from the KFD node id. The two disagree on real hardware (MI350X+ # SPX/NPS1), which is why setup.sh translates through `amd-smi list -e`'s HIP_ID map+ # and declines when it is unavailable or not 1:1. No such map is read here, so on+ # unlike adapters an untranslated ordinal names another card's arch. An UNSET mask is+ # no safer: it still selects HIP ordinal 0, and discovery-order 0 can be the other+ # card. Like adapters are unaffected either way, every ordinal giving the same arch.+ _discovery_ordered = _probe_source == "amd-smi"+ if _discovery_ordered and _unlike_adapters:+ # Discovery order is unusable, the kernel's topology is not: KFD nodes ARE the+ # order HIP and ROCr index. Reading them swaps an ordering no ordinal fits for one+ # that does, rather than declining the repair the reported shape needs (#9396: a+ # Ryzen APU beside a dGPU, with amd-smi installed). Only on an equal device count+ # -- a KFD list of another length is a different view of the machine.+ _kfd_ordered = _kfd_gfx_targets()+ if len(_kfd_ordered) == len(gfx_devices):+ gfx_devices = _kfd_ordered+ _unlike_adapters = len(set(gfx_devices)) > 1+ _discovery_ordered = False+ gfx_devices, _rocr_unresolved = _rocr_visible_subset(gfx_devices)+ # A UUID names a device this cannot place. Judged against the list BEFORE the mask+ # was applied: dropping the tokens that did resolve can leave one arch standing and+ # hide the very ambiguity the UUID created, and "0,GPU-..." is a form AMD documents.+ if (_rocr_unresolved or _discovery_ordered) and _unlike_adapters:+ # The message below offers UNSLOTH_ROCM_GFX_ARCH as the way through, so honour it:+ # naming the arch outright is the one reading no ordinal or UUID contradicts. Read+ # from the environment, not inferred_linux_gfx, which also carries the product+ # guess -- weaker than the probe, and not for a host the probe left open.+ _named_gfx = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower()+ if _named_gfx:+ # The named arch leads the returned set. Stacked masks can leave a list it is+ # not in (ROCr keeps the gfx1200, the user names the gfx1103), and the caller+ # reads that set to decide which arch lacks kernels, so a target missing from+ # it is selected and then never repaired.+ return (+ _named_gfx,+ list(dict.fromkeys([_named_gfx, *gfx_devices])),+ physical_gfx,+ host_codes,+ )+ _why = (+ "ROCR_VISIBLE_DEVICES names a GPU by UUID"+ if _rocr_unresolved+ else "amd-smi reports GPUs in discovery order, which is not the order the\n"+ " visible-device masks index,"+ )+ _safe_print(+ f" {_why} and this host has more than one\n"+ f" architecture ({', '.join(dict.fromkeys(gfx_devices))}); which one is\n"+ f" selected cannot be read here, so the AMD per-gfx index is left alone.\n"+ f" Set UNSLOTH_ROCM_GFX_ARCH to the arch you want wheels for.\n"+ )+ return None, [], None, host_codes+ runtime_gfx = (+ gfx_devices[_pick_visible_index(len(gfx_devices), masks = _HIP_LAYER_MASKS)]+ if gfx_devices+ else None+ )+ if runtime_gfx in _SHADOWING_INTEGRATED_GFX and not _visible_devices_pinned():+ # Unpinned mixed host: only enumeration order put the integrated GPU first, and the+ # wheel family is picked for ONE arch, so letting the APU decide strands the discrete+ # card. Same #7776 preference _detect_windows_gfx_arch applies, stopping at a set mask+ # for the same reason -- a pin is the user naming a device. gfx906 is excluded as a+ # candidate because its only route runs through _runtime_target_is_gfx906, which no+ # mixed host satisfies: naming it installs a rocm7.x wheel whose BLAS has no gfx906+ # kernels and strands BOTH cards. It keeps its UNSLOTH_ROCM_GFX_ARCH opt-in.+ _others = [+ g+ for g in gfx_devices+ if g not in _SHADOWING_INTEGRATED_GFX and g not in _MIXED_HOST_UNROUTABLE+ ]+ # Prefer a discrete card the installer can serve: deposing a routable APU for one no+ # index carries (an RDNA 1 dGPU beside a gfx1103) trades a repairable GPU for nothing.+ # Same shape as _detect_windows_gfx_arch's _withWheels guard.+ _routable = [g for g in _others if _gfx_has_a_wheel_route(g)]+ _candidates = _routable or ([] if _gfx_has_a_wheel_route(runtime_gfx) else _others)+ _discrete = _candidates[0] if _candidates else None+ if _discrete is not None:+ _safe_print(+ f" multiple AMD GPUs detected "+ f"({', '.join(dict.fromkeys(gfx_devices))}); installing for {_discrete}\n"+ f" instead of the integrated {runtime_gfx}. Set HIP_VISIBLE_DEVICES to the\n"+ f" GPU index you want (then rerun) to install for a different device.\n"+ )+ runtime_gfx = _discrete+ return runtime_gfx, list(dict.fromkeys(gfx_devices)), physical_gfx, host_codes++def _hsa_override_gfx_arch(value: "str | None") -> "str | None":"""gfx arch named by an HSA_OVERRIDE_GFX_VERSION value, or None if unreadable.@@ -1895,6 +2309,17 @@ def _hsa_spoofed_physical_gfx(return _confirm(list(dict.fromkeys(reprobed)), "rocminfo with HSA_OVERRIDE_GFX_VERSION unset")+def _hsa_spoof_contradicts(gfx: "str | None") -> bool:+ """True when HSA_OVERRIDE_GFX_VERSION names an arch other than ``gfx``.++ Every branch installing per-arch wheels has to ask: those wheels carry one arch's code+ objects and ROCr builds the agent's ISA name from this variable. An override naming the+ SAME arch is not a spoof; a different one is left alone only where ``gfx`` is untrusted.+ """+ _override_arch = _hsa_override_gfx_arch(os.environ.get("HSA_OVERRIDE_GFX_VERSION"))+ return bool(gfx) and _override_arch is not None and _override_arch != gfx++def _clear_confirmed_hsa_spoof(physical_gfx: str) -> None:"""Drop a CONFIRMED HSA_OVERRIDE_GFX_VERSION spoof from this process's env.@@ -1924,6 +2349,64 @@ def _clear_confirmed_hsa_spoof(physical_gfx: str) -> None:# First-set-wins order, as _pick_visible_index documents below._VISIBLE_DEVICE_MASKS = ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")+# The HIP layer alone. CUDA_VISIBLE_DEVICES is HIP's alias on AMD, so both name the same+# layer and stay first-set-wins between themselves; ROCR_VISIBLE_DEVICES is the layer+# BENEATH and is applied separately by _rocr_visible_subset.+_HIP_LAYER_MASKS = ("HIP_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")++# A device count no host reaches, for asking what index a mask NAMES rather than which entry+# of a real list it selects: any ordinal below it resolves to itself, not to the 0 fallback.+_INDEX_PROBE_LEN = 1 << 20+++def _rocr_visible_subset(gfx_devices: "list[str]") -> "tuple[list[str], bool]":+ """Apply the ROCr layer to a device list no probe filtered.++ Returns the surviving devices and whether any token could NOT be resolved to one.++ ROCR_VISIBLE_DEVICES is processed below HIP, deciding which devices exist at all before+ any HIP index resolves. Neither amd-smi (driver) nor KFD sysfs (kernel) is filtered by it,+ so a HIP index resolved against their whole-machine list names a GPU the runtime does not+ expose. The mask takes indices or UUIDs and may MIX them ("0,GPU-DEADBEEFDEADBEEF"); a+ probe reporting arches names no UUID, so those tokens resolve to no position and are+ reported unresolved rather than guessed at. An empty or "-1" mask never reaches here:+ _visible_masks_select_no_gpu already refused the host.+ """+ _raw = (os.environ.get("ROCR_VISIBLE_DEVICES") or "").strip()+ if not _raw or not gfx_devices:+ return gfx_devices, False+ _kept: "list[str]" = []+ _unresolved = False+ for _tok in _raw.split(","):+ _tok = _tok.strip()+ try:+ _idx = int(_tok)+ except ValueError:+ _unresolved = True # a UUID: this names a device, but not a position+ continue+ if 0 <= _idx < len(gfx_devices):+ _kept.append(gfx_devices[_idx])+ # An out-of-range index keeps the whole list, deliberately: _pick_visible_index warns and+ # falls back to GPU 0 for that value (matching setup.ps1's Resolve-VisibleGpuIndex), and a+ # stricter rule here would split the two. ROCR_VISIBLE_DEVICES=1 on a one-GPU box is a+ # typo, and reading it as "no GPU" withdraws the repair from the hosts this exists for.+ return (_kept or gfx_devices), _unresolved+++def _visible_masks_select_no_gpu() -> bool:+ """True when a set visible-device mask exposes NO GPU, at either layer.++ ROCr filters BENEATH HIP, so an empty or -1 mask on either one leaves nothing to target+ however the other reads: HIP_VISIBLE_DEVICES=0 over ROCR_VISIBLE_DEVICES=-1 still exposes+ no device. CUDA_VISIBLE_DEVICES is the HIP alias and is read only when HIP itself is unset.+ """+ _hip = "HIP_VISIBLE_DEVICES" if "HIP_VISIBLE_DEVICES" in os.environ else "CUDA_VISIBLE_DEVICES"+ return any(+ (os.environ.get(_mask) or "").strip() in ("", "-1")+ for _mask in ("ROCR_VISIBLE_DEVICES", _hip)+ if _mask in os.environ+ )+def _first_set_visible_mask() -> "str | None":"""Name of the visible-device variable in force, first-set-wins, or None."""@@ -2224,10 +2707,27 @@ def _rocm_pin_family_mismatch(pin_url: str, installed_ver: str) -> bool:)if leaf.startswith("gfx"):+ # A repin BETWEEN per-arch leaves (gfx1151 -> gfx120X-all, the swapped-card case)+ # keeps every shape the version string carries: both are torch 2.11 with a three-part+ # +rocmA.B.C tag. Judged on that alone the pin the user just edited reads as satisfied+ # and is dropped in silence. The installed `rocm` meta-package names the family+ # outright; None means unknowable, so this can only ADD a mismatch, never talk one away.+ _family = _installed_rocm_wheel_family()+ if _family is not None and _family != leaf:+ return True# 2.11-allowlist arches expect the AMD per-arch wheel (three-part +rocmA.B.C,- # torch 2.11+); a generic or pre-2.11 build is a mismatch.+ # torch 2.11+); a generic or pre-2.11 build is a mismatch. Asked before the family+ # can settle it, because these leaves have a FLOOR: a matching family on a 2.10 build+ # is the _grouped_mm bug, which is the one thing the pin has to keep repairing.if leaf in _ROCM_GFX_TORCH211_LEAVES:return not (_inst_is_211 and _inst_is_perarch)+ # Decisive the other way too, on leaves with no floor. The heuristic below reads any+ # 2.11 build as a mismatch, since that is what a build from some OTHER index looks+ # like -- but these leaves serve 2.11 as well, and the family says this one came from+ # the pinned index. Without it a correctly pinned gfx110X host force-reinstalls under+ # the legacy torch<2.11 cap on every update.+ if _family is not None and _inst_is_perarch:+ return False# Non-2.11 gfx leaf (<2.11 specs): mismatch on an untagged wheel or torch 2.11+.return (not _inst_has_rocm) or _inst_is_211@@ -3356,32 +3856,50 @@ def _amd_torch_needs_dependency_pass() -> bool:return Falseif _has_usable_nvidia_gpu():return False- # ROCr filters beneath HIP, so a hidden layer either side leaves no target to- # classify. CUDA_VISIBLE_DEVICES is the HIP alias, read only when HIP is unset.- _hip_mask = (- "HIP_VISIBLE_DEVICES" if "HIP_VISIBLE_DEVICES" in os.environ else "CUDA_VISIBLE_DEVICES"- )- if any(- (os.environ.get(_mask) or "").strip() in ("", "-1")- for _mask in ("ROCR_VISIBLE_DEVICES", _hip_mask)- if _mask in os.environ- ):+ # A hidden layer either side leaves no target to classify. Same reading the routing+ # guard uses, so the two can never drift.+ if _visible_masks_select_no_gpu():return False# Match the repair's two host signals: a visible GPU or an inferred/named arch._inferred_gfx = _infer_linux_amd_gfx_arch()_rocm_visible = _has_rocm_gpu()if not _rocm_visible and not _inferred_gfx:return False- # Probe and runtime mask indexing can disagree on mixed-arch hosts.- if len(set(_detect_amd_gfx_codes())) > 1:+ # A mixed-arch host used to end it here, because probe and mask order could disagree+ # with nothing to resolve it. _runtime_gfx_target now composes both mask layers and+ # returns no target ONLY when the selection is genuinely unreadable, so gate on its+ # answer, not the shape of the host: a mixed box with HIP_VISIBLE_DEVICES naming a+ # card is not ambiguous, and its generic wheel can still lack kernels for it.+ _selected_gfx, _, _selected_spoof, _selected_host = _runtime_gfx_target(_inferred_gfx)+ if _selected_gfx is None:return False+ # Every arm below is about the wheel. A corroborated spoof is not: the family can be+ # perfect while ROCr presents an ISA those wheels have no code for, and only+ # _ensure_rocm_torch clears the variable (#7331).+ if _selected_spoof is not None:+ return True+ _pre_ran, _pre_imp, _pre_ver, _pre_hip, _pre_cuda = _probe_torch_runtime()+ _pre_torch = (_pre_ver or "").lower() if (_pre_ran and _pre_imp) else ""+ # The compatibility reroutes have no version floor either, so a host whose ROCm+ # version will not read must not be turned away before they are asked. Only with a+ # torch that reads back: an unreadable one is not evidence its wheels are wrong.+ if _pre_torch and _rocm_compat_reroute_pending(+ _selected_gfx, _detect_rocm_version() or (0, 0), _pre_torch+ ):+ return True# The inferred per-arch repair can run without a readable ROCm version._inferred_arm = (bool(_inferred_gfx)and bool((os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip() or not _rocm_visible)and _amd_arch_index_url(_inferred_gfx) is not None)- if not _inferred_arm:+ # Both per-arch repairs are version-independent, and the host with no readable+ # version is the one they exist for: a bundled-runtime install has no system ROCm+ # to read. Requiring a version here refuses them at the door.+ _family_repair_arm = _rocm_torch_family_needs_repair(+ _selected_gfx, _detect_rocm_version(), _selected_host+ )+ if not _inferred_arm and not _family_repair_arm:# Other repair arms need a readable version with a published wheel family._ver = _detect_rocm_version()if _ver is None or _generic_pytorch_rocm_tag(_ver) is None:@@ -3392,7 +3910,133 @@ def _amd_torch_needs_dependency_pass() -> bool:if not (_ran and _importable) or not _version:return False# The +rocm tag covers builds that omit torch.version.hip.- return not (_hip or "rocm" in _version.lower())+ if not (_hip or "rocm" in _version.lower()):+ return True+ # Torch IS a ROCm build, which used to end it. The per-arch repairs act on exactly those+ # hosts, so keeping the fast path makes them unreachable from `studio update`: a swapped+ # card, or the reported gfx1103 on a generic wheel, would be repaired on a fresh install+ # and never again. The pass costs a dependency resolution, not a reinstall, since+ # _ensure_rocm_torch still keeps a family that matches. So ask only what it asks, only+ # where it would act, and not under a pin, which commits to an index regardless.+ _pin = _explicit_rocm_torch_index_url()+ if _pin is not None:+ # A pin skips the hardware questions, but not its own: _ensure_rocm_torch reinstalls+ # when the installed local tag names a different family than the pin, and returning+ # here unconditionally meant a changed UNSLOTH_TORCH_INDEX_URL never reached it.+ return _rocm_pin_family_mismatch(_pin, _version.lower())+ _tail_gfx, _, _tail_spoof, _tail_host = _runtime_gfx_target(_infer_linux_amd_gfx_arch())+ _tail_ver = _detect_rocm_version() or (0, 0)+ # A corroborated HSA spoof is cleared by _ensure_rocm_torch and only by it: the family can+ # match perfectly while ROCr presents an ISA the wheels have no code for (#7331), so the+ # wheel question alone keeps the fast path and the variable stays set.+ if _tail_spoof is not None:+ return True+ # The two compatibility reroutes are repairs like any other, and asking only the+ # missing-kernel question skipped both on update: Strix on a generic wheel below the AMD+ # floor still needs the 7.13 fixes, and a sole gfx906 above rocm6.3 has no BLAS kernels.+ if _rocm_compat_reroute_pending(_tail_gfx, _tail_ver, _version.lower()):+ return True+ return _rocm_torch_family_needs_repair(_tail_gfx, _detect_rocm_version(), _tail_host)+++def _already_on_amd_arch_leaf(leaf: "str | None", installed_ver: str) -> bool:+ """True when the installed torch already IS the AMD per-arch build for ``leaf``.++ The family is the direct reading. A family that will not read back is not evidence of the+ wrong wheels, so the local tag is accepted too: only the AMD index ships a rocm tag at or+ above the arch floor, and re-downloading a multi-GB stack each update to re-establish what+ the tag already says is the cost this guard avoids.+ """+ if _torch_below_211(installed_ver):+ return False+ _family = _installed_rocm_wheel_family() if _torch_requires_rocm_sdk() else None+ if _family is not None:+ # A family that reads back is the answer, whichever way it points: an AMD build for+ # ANOTHER arch sits at the same floor tag and carries none of this one's kernels.+ return _family == (leaf or "").lower()+ _tag = re.search(r"\+rocm(\d+)\.(\d+)", installed_ver or "")+ return bool(_tag) and (int(_tag.group(1)), int(_tag.group(2))) >= _ROCM_ARCH_INDEX_FLOOR+++def _rocm_compat_reroute_pending(+ runtime_gfx: "str | None", ver: "tuple[int, int]", installed_ver: str+) -> bool:+ """Whether a compatibility reroute _ensure_rocm_torch performs has not been applied yet.++ Neither reroute is about missing kernels, so neither is visible to the wheel-family+ question: Strix wants AMD's 7.13 build over any generic one below the floor, and gfx906+ wants the last tag whose BLAS still carries it. Both compare against what is installed,+ so a host already on the right wheels keeps the fast path.+ """+ if not runtime_gfx:+ return False+ if runtime_gfx in _HSA_SPOOFABLE_PHYSICAL_GFX and _strix_needs_amd_arch_index(ver):+ return not _already_on_amd_arch_leaf(_GFX_TO_AMD_INDEX_ARCH.get(runtime_gfx), installed_ver)+ if _runtime_target_is_gfx906() and _gfx906_needs_legacy_index(ver):+ return _GFX906_LEGACY_TAG not in installed_ver+ return False+++def _installed_generic_rocm_tag() -> "tuple[int, int] | None":+ """(major, minor) of the ROCm tag the INSTALLED torch names, or None if it names none.++ Generic pytorch.org wheels carry it in the local version ("2.9.1+rocm6.3"). AMD per-arch+ builds are read by _installed_rocm_wheel_family instead, so their tag is not wanted here.+ """+ _ran, _importable, _ver, _hip, _cuda = _probe_torch_runtime()+ if not (_ran and _importable):+ return None+ _m = re.search(r"\+rocm(\d+)\.(\d+)", (_ver or "").lower())+ return (int(_m.group(1)), int(_m.group(2))) if _m else None+++def _rocm_torch_family_needs_repair(+ runtime_gfx: "str | None",+ ver: "tuple[int, int] | None" = None,+ host_codes: "list[str] | None" = None,+) -> bool:+ """Whether the installed ROCm torch carries no kernels for ``runtime_gfx``.++ Reads the same two signals _ensure_rocm_torch's arms read, in the same order, so the+ preflight cannot promise a repair the repair declines. A per-arch install names its+ family, and any family other than this target's is stale. A generic build names none (and+ _torch_requires_rocm_sdk rejects a stale `rocm` orphan beside one), so it is judged on+ whether the generic wheels carry kernels at all. An unknowable family answers False:+ leave the install alone rather than guess.+ """+ _owns_sdk = _torch_requires_rocm_sdk()+ _family = _installed_rocm_wheel_family() if _owns_sdk else None+ if _family is not None:+ _leaf = (_GFX_TO_AMD_INDEX_ARCH.get(runtime_gfx or "") or "").lower()+ if _family != _leaf:+ # Only when some index can serve the target ON THIS HOST: a gfx1010, or a+ # mask-selected gfx906 beside another card, has a real mismatch and nowhere to go.+ # _ensure_rocm_torch declines on the same question, and promising a repair it+ # refuses buys a dependency pass on EVERY update and never a working torch.+ return _gfx_route_on_host(runtime_gfx, host_codes)+ # The right SHAPE, not necessarily a working build: below the 2.11 floor these leaves+ # carry the _grouped_mm bug, and answering False on a 2.10 build would keep the fast+ # path and leave it in place on every update.+ _ran, _importable, _ver, _hip, _cuda = _probe_torch_runtime()+ return _leaf in _ROCM_GFX_TORCH211_LEAVES and _torch_below_211(+ (_ver or "").lower() if (_ran and _importable) else ""+ )+ if _owns_sdk:+ # A per-arch install whose family will not read back. _ensure_rocm_torch cannot skip+ # on a family it never read, so it would reinstall the stack on EVERY update once the+ # fast path stops hiding it. Leave it alone.+ return False+ # Which arches a generic wheel carries belongs to THAT wheel, so read the tag off the+ # installed torch when it states one; ``ver`` is the HOST's, and the two part company (pin+ # rocm6.3 once, or upgrade /opt/rocm, and a gfx1200 box on 2.9.1+rocm6.3 looks healthy+ # forever). Both readings of "no code for this card" are needed: the reroute question, and+ # the tag floor for a target with no index to be rerouted TO. Asking only the first kept+ # the fast path on a gfx950 on rocm6.3, so the install path's floor was never reached from+ # `studio update` -- repaired once on a fresh install and never again.+ _installed_tag = _installed_generic_rocm_tag() or ver+ return _generic_rocm_wheel_lacks_kernels(+ runtime_gfx, _installed_tag+ ) or _generic_only_target_below_floor(runtime_gfx, _installed_tag)def _ensure_rocm_torch() -> None:@@ -3527,7 +4171,28 @@ def _ensure_rocm_torch() -> None:ver = _detect_rocm_version()if ver is None:- if _rocm_pin is None and not _inferred_linux_gfx:+ # A host running the wheels' own bundled ROCm has no system version to read, and is+ # the same host the missing-kernel route exists for. That route has no version floor,+ # so returning here on an arch the generic wheel cannot serve refuses the repair at+ # the door. The second target resolution is confined to this branch.+ _unknown_ver_gfx, _, _, _unknown_ver_host = _runtime_gfx_target(None)+ _uv_ran, _uv_imp, _uv_ver, _uv_hip, _uv_cuda = _probe_torch_runtime()+ _unknown_ver_torch = (_uv_ver or "").lower() if (_uv_ran and _uv_imp) else ""+ # A per-arch install can also outlive the GPU it was made for: swap a gfx1200 card+ # into a box on gfx110X-all wheels and the generic index would serve it, so the clause+ # above lets the exit stand while those wheels carry no gfx1200 kernels. A matching+ # family below its 2.11 floor is the same story. This is the reading the setup+ # preflight uses, so anything narrower lets the pass run and then declines it.+ if (+ _rocm_pin is None+ and not _inferred_linux_gfx+ and not _generic_rocm_wheel_lacks_kernels(_unknown_ver_gfx)+ and not _rocm_torch_family_needs_repair(_unknown_ver_gfx, None, _unknown_ver_host)+ # The Strix reroute has no version floor to fail: with no tag resolving, the+ # per-arch index is the only route these arches have, and exiting here left a+ # visible Strix host on whatever non-ROCm torch it already had.+ and not _rocm_compat_reroute_pending(_unknown_ver_gfx, (0, 0), _unknown_ver_torch)+ ):_safe_print(" ROCm detected but version unreadable -- skipping torch reinstall")return# Explicit pin or inferred gfx: the index drives the install.@@ -3562,11 +4227,16 @@ def _ensure_rocm_torch() -> None:# install.sh): a visible GPU with an unreadable/unsupported ROCm version must# not silently discard the user's named arch and leave CPU torch in place._gfx_override_env = (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower()+ _inferred_arch_installed = Falseif (_inferred_linux_gfxand not has_hip_torchand _rocm_pin is Noneand (_gfx_override_env or not _has_rocm_gpu())+ # This branch installs for the inferred arch without asking the mask layers, so an+ # ordinal the guess cannot account for reaches the wheel the preflight already+ # declines. An explicit arch is exempt above, and no ordinal contradicts it.+ and (_gfx_override_env or _runtime_gfx_target(_inferred_linux_gfx)[0] is not None)):index_url = _amd_arch_index_url(_inferred_linux_gfx)if index_url is not None:@@ -3591,6 +4261,13 @@ def _ensure_rocm_torch() -> None:constrain = False,)rocm_torch_ready = True+ _inferred_arch_installed = True+ # The same reconciliation the reroutes below make: these wheels carry+ # _inferred_linux_gfx code objects alone, and a spoof naming another arch has ROCr+ # hand them a device none of it matches (#7331). The install is already committed+ # to that arch, so declining here only guarantees it is unusable.+ if _hsa_spoof_contradicts(_inferred_linux_gfx):+ _clear_confirmed_hsa_spoof(_inferred_linux_gfx)# An explicit UNSLOTH_ROCM_GFX_ARCH=gfx906 pins the runtime target to the# MI50 / Radeon VII path; it must win over the Strix probe-order detection@@ -3600,54 +4277,47 @@ def _ensure_rocm_torch() -> None:":")[0] == "gfx906"- # Strix Halo / Point (gfx1151 / gfx1150) need torch from AMD's per-gfx index- # (2.11+rocm7.13); any generic pytorch.org rocm index lacks the fixes (ROCm 7.1- # segfaults in _grouped_mm). See _strix_needs_amd_arch_index for the floor gate.- _strix_override_url: "str | None" = None- _strix_override_pkgs: "tuple[str, str, str] | None" = None- # An explicit ROCm pin is authoritative: never auto-reroute it.+ # Where the two AMD per-gfx reroutes below deposit their choice. Strix Halo / Point+ # (gfx1151 / gfx1150) need AMD's per-gfx index (2.11+rocm7.13) because every generic+ # pytorch.org index lacks the fixes (ROCm 7.1 segfaults in _grouped_mm); see+ # _strix_needs_amd_arch_index for that floor. The second reroute has no floor and fires+ # for an arch the generic wheel carries no kernels for at all.+ _arch_index_url: "str | None" = None+ _arch_index_pkgs: "tuple[str, str, str] | None" = None+ # An explicit ROCm pin wins; otherwise both reroutes share one hardware probe. Skipped+ # once the inferred-arch install above has run: it resolves the same index, so re-deriving+ # it here only force-reinstalls what was just downloaded.if (- _strix_needs_amd_arch_index(ver)- and _explicit_rocm_torch_index_url() is None+ _explicit_rocm_torch_index_url() is Noneand not _gfx906_arch_override+ and not _inferred_arch_installed):- # 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)- # HSA_OVERRIDE_GFX_VERSION=11.0.0 (the circulated Strix workaround) makes ROCr- # hand rocminfo the SPOOFED ISA, so a gfx1151 host reports gfx1100 and every- # check below misses it (unslothai#7331). Correct the reading back to the- # physical arch first, only in the narrow shape that cannot be a real mixed host.- _physical_gfx = _hsa_spoofed_physical_gfx(_inferred_linux_gfx, gfx_devices)- if _physical_gfx is not None:- gfx_devices = [_physical_gfx]- gfx_codes = list(dict.fromkeys(gfx_devices))+ _runtime_gfx, gfx_codes, _physical_gfx, _host_codes = _runtime_gfx_target(+ _inferred_linux_gfx+ )_strix_gfx = {"gfx1151", "gfx1150", "gfx1152"}- _detected_strix = _strix_gfx.intersection(gfx_codes)+ # Only the Strix reroute has a ROCm-version floor.+ _detected_strix = (+ _strix_gfx.intersection(gfx_codes) if _strix_needs_amd_arch_index(ver) else set()+ )if _detected_strix:- # 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:+ if _runtime_gfx in _strix_gfx and _already_on_amd_arch_leaf(+ _GFX_TO_AMD_INDEX_ARCH.get(_runtime_gfx), _installed_torch_ver+ ):+ # Already the build this branch would fetch. It force-reinstalls a multi-GB+ # stack and _ensure_rocm_torch runs twice per install, so acting on the arch+ # alone re-downloads it on every install and every later update.+ _safe_print(+ f" torch already runs on the AMD {_runtime_gfx} wheels; keeping it.\n"+ )+ if _physical_gfx is not None:+ _clear_confirmed_hsa_spoof(_runtime_gfx)+ elif _runtime_gfx in _strix_gfx:_selected_gfx = _runtime_gfx- _amd_mirror = (- os.environ.get("UNSLOTH_AMD_ROCM_MIRROR") or "https://repo.amd.com/rocm/whl"- ).rstrip("/")- _strix_override_url = f"{_amd_mirror}/{_selected_gfx}/"- _strix_override_pkgs = (+ # One owner for the mirror env var and the arch-to-leaf map, shared with+ # the inferred-arch install above and the missing-kernel route below.+ _arch_index_url = _amd_arch_index_url(_selected_gfx)+ _arch_index_pkgs = ("torch>=2.11.0,<2.12.0",# Pin companions to the 2.11.x range: the exclusive --index-url could# otherwise resolve a build for a different torch major (ABI mismatch).@@ -3658,9 +4328,9 @@ def _ensure_rocm_torch() -> None:f" {_selected_gfx} (AMD Strix) is the runtime target with ROCm "f"{ver[0]}.{ver[1]}.\n"f" Routing torch install to AMD's arch-specific index\n"- f" ({_strix_override_url}) which serves torch 2.11.0+rocm7.13.0\n"- f" with AMD's gfx1150/gfx1151 fixes (more reliable than the generic\n"- f" pytorch.org rocm7.2 index on ROCm 7.3+ hosts).\n"+ f" ({_strip_index_url_credentials(_arch_index_url)}) which serves torch\n"+ f" 2.11.0+rocm7.13.0 with AMD's gfx1150/gfx1151 fixes (more reliable than\n"+ f" the generic pytorch.org rocm7.2 index on ROCm 7.3+ hosts).\n")# Only on this branch: these wheels carry _selected_gfx kernels, so# the runtime must stop reporting the spoofed arch or they have no@@ -3676,13 +4346,200 @@ def _ensure_rocm_torch() -> None:f" skipping AMD per-gfx index override.\n")+ # If the generic wheel lacks the runtime target, replace it from AMD's per-arch index.+ # No ROCm-version floor here: whichever generic index a host's ROCm version picks,+ # its wheel carries no kernels for these targets (see _GENERIC_ROCM_WHEEL_GFX).+ if _arch_index_url is None:+ # Judged by the installed wheel when it is a generic build naming its own tag,+ # since ``ver`` is the HOST's. ``ver`` still chooses the tag for a reinstall+ # below, which IS a question about the host.+ _kernel_ver = (+ has_hip_torch and not _torch_requires_rocm_sdk() and _installed_generic_rocm_tag()+ ) or ver+ _missing_kernels = {+ g for g in gfx_codes if _generic_rocm_wheel_lacks_kernels(g, _kernel_ver)+ }+ # A sub-2.11 build of a floor leaf is broken wherever it came from, and several of+ # those leaves (gfx120X-all, and gfx1150/gfx1151 when an unreadable ROCm version+ # leaves the Strix arm inactive) serve GPUs the generic wheel DOES list. Gating+ # the floor on missing generic kernels never reaches them, so the preflight forces+ # a pass this block declines. The floor belongs to the family, not to the visit.+ _runtime_leaf = _GFX_TO_AMD_INDEX_ARCH.get(_runtime_gfx or "")+ _below_floor_on_leaf = (+ _runtime_leaf is not None+ and _runtime_leaf.lower() in _ROCM_GFX_TORCH211_LEAVES+ and has_hip_torch+ and _torch_requires_rocm_sdk()+ and _installed_rocm_wheel_family() == _runtime_leaf.lower()+ and _torch_below_211(_installed_torch_ver)+ )+ if _missing_kernels or _below_floor_on_leaf:+ _leaf = (+ _runtime_leaf+ if (+ _generic_rocm_wheel_lacks_kernels(_runtime_gfx, _kernel_ver)+ or _below_floor_on_leaf+ )+ else None+ )+ # Already running on this family's wheels. The reroute below is a+ # --force-reinstall --no-cache-dir of the multi-GB stack and _ensure_rocm_torch+ # runs twice per install, so a leaf derived from hardware alone re-downloads+ # it twice per install and again on every update. Act only on a family read+ # back positively: an unknowable one is None here and reinstalls, as does a+ # CPU/CUDA torch, and _torch_requires_rocm_sdk rejects a stale `rocm` orphan.+ # The right SHAPE is not a working build -- on these leaves a sub-2.11 wheel+ # carries the _grouped_mm bug, and skipping on family alone preserves it+ # forever. An unreadable ROCm version routes gfx1152 here rather than through+ # the Strix branch, so this is the only floor it meets.+ _already_on_leaf = (+ _leaf is not None+ and has_hip_torch+ and _torch_requires_rocm_sdk()+ and _installed_rocm_wheel_family() == _leaf.lower()+ and not (+ _leaf.lower() in _ROCM_GFX_TORCH211_LEAVES+ and _torch_below_211(_installed_torch_ver)+ )+ )+ if _already_on_leaf:+ _safe_print(+ f" torch already runs on the {_leaf} wheels {_runtime_gfx} needs; "+ f"keeping it.\n"+ )+ # Keeping the wheels is not keeping the status quo: they carry the+ # PHYSICAL arch alone, so a spoof left set has the runtime keep reporting+ # the one arch they have no code for (#7331). The skip needs the clear as+ # much as the reinstall arm does.+ if _physical_gfx is not None:+ _clear_confirmed_hsa_spoof(_runtime_gfx)+ elif _leaf is not None:+ _arch_index_url = _amd_arch_index_url(_runtime_gfx)+ # Keep older per-arch builds valid while bounding companion versions,+ # except on the leaves whose sub-2.11 builds carry the _grouped_mm bug.+ # gfx1152 reaches this branch rather than the Strix one when an unreadable+ # ROCm version reads as 0.0, below the Strix floor.+ _arch_index_pkgs = (+ _ROCM_TORCH_PKG_SPECS["rocm7.2"]+ if _leaf.lower() in _ROCM_GFX_TORCH211_LEAVES+ else _ROCM_ARCH_INDEX_TORCH_PKG_SPEC+ )+ _safe_print(+ f" {_runtime_gfx} is the runtime target, and no pytorch.org ROCm wheel\n"+ f" carries kernels for it -- torch would load but fault on its first\n"+ f" GPU operation. Routing the torch install to AMD's arch-specific\n"+ f" index, which does:\n"+ f" {_strip_index_url_credentials(_arch_index_url)}\n"+ )+ # Let the runtime report the native target carried by these wheels.+ if _physical_gfx is not None:+ _clear_confirmed_hsa_spoof(_runtime_gfx)+ else:+ _gfx_str = ", ".join(sorted(_missing_kernels))+ _safe_print(+ f" GPU without generic-wheel kernels ({_gfx_str}) present, but the\n"+ f" selected runtime target is {_runtime_gfx}; keeping the generic index.\n"+ )+ elif (+ _physical_gfx is not None+ and _runtime_leaf is not None+ and has_hip_torch+ and _torch_requires_rocm_sdk()+ and _installed_rocm_wheel_family() == _runtime_leaf.lower()+ ):+ # Nothing to reroute -- the installed per-arch wheels are the target's own+ # family, which is why neither condition above fires. The spoof is still+ # exported and these wheels carry the PHYSICAL arch alone, so the runtime+ # keeps asking them for code they do not have (#7331). Every arm that KEEPS+ # matching wheels clears it; this one kept them and reached no arm at all.+ # Judged on a family read back from a torch that owns it, never the target.+ _clear_confirmed_hsa_spoof(_runtime_gfx)++ # A per-arch install can outlive the GPU it was made for: add a dGPU, or point+ # HIP_VISIBLE_DEVICES at one, and the target moves to an arch those wheels carry no+ # kernels for. torch.version.hip still reads ROCm, so rocm_torch_ready would stop the+ # generic fallback and the wrong family would survive every update. Same repick+ # _detect_windows_gfx_arch's caller does for #7776, on a family read back positively.+ if _arch_index_url is None and rocm_torch_ready and _runtime_gfx is not None:+ _have = _installed_rocm_wheel_family() if _torch_requires_rocm_sdk() else None+ _want = (_GFX_TO_AMD_INDEX_ARCH.get(_runtime_gfx) or "").lower()+ # A target no index can serve (gfx1010 / RDNA 1) has an empty _want, which reads+ # as "every family is wrong" and spends a multi-GB reinstall on a wheel that+ # cannot carry kernels for it either. Demote only when there is somewhere to go,+ # and ask that of THIS host: gfx906's only route is the rocm6.3 tag, unlocked+ # solely when it is the one detected arch, so demoting a mask-selected MI50 beside+ # another card downloads a second unusable torch (_MIXED_HOST_UNROUTABLE).+ if (+ _have is not None+ and _have != _want+ and _gfx_route_on_host(_runtime_gfx, _host_codes)+ ):+ _safe_print(+ f" installed ROCm torch is the {_have} build, which carries no\n"+ f" {_runtime_gfx} kernels -- reinstalling for this GPU.\n"+ )+ rocm_torch_ready = False+ # Demoting alone hands the job to the generic fallback, which resolves NO tag+ # when the ROCm version is unreadable, as it is on a bundled-runtime host: the+ # branch would announce the reinstall, install nothing, and keep the family it+ # just called incompatible. The AMD index needs no host version, so use it.+ _tag = _generic_pytorch_rocm_tag(ver)+ if _want:+ if _tag is None:+ _arch_index_url = _amd_arch_index_url(_runtime_gfx)+ if _arch_index_url is not None:+ _arch_index_pkgs = (+ _ROCM_TORCH_PKG_SPECS["rocm7.2"]+ if _want in _ROCM_GFX_TORCH211_LEAVES+ else _ROCM_ARCH_INDEX_TORCH_PKG_SPEC+ )+ elif _runtime_gfx in _GENERIC_ROCM_WHEEL_GFX and (+ _tag is None or _generic_tag_lacks_kernels(_runtime_gfx, ver)+ ):+ # The replacement GPU has no AMD per-arch index at all: gfx942, gfx950 and+ # the other datacentre parts live only on the generic one. With no+ # readable host version there is no tag either, so the branch would leave+ # the stale per-arch wheels in place. A tag that RESOLVES can be as+ # useless, a stale /opt/rocm putting gfx950 on rocm6.3. Both take the+ # newest generic index this installer knows, which does carry the target.+ ver = max(_ROCM_TORCH_INDEX)+ elif _have is None and _generic_only_target_below_floor(+ _runtime_gfx, _installed_generic_rocm_tag() or ver+ ):+ # A GENERIC build whose own tag predates the target: no family to compare and+ # no per-arch index to move to, so both arms above decline and+ # torch.version.hip keeps the fallback from running. A gfx950 pinned to+ # rocm6.3 once stays on a wheel with no kernels for it through every update.+ # Demoting is the whole repair (the floor below picks the tag), and the+ # preflight forces the pass for this state, so declining never repairs it.+ _safe_print(+ f" installed ROCm torch is a generic build whose own tag predates\n"+ f" {_runtime_gfx} -- reinstalling from an index that carries it.\n"+ )+ rocm_torch_ready = False++ # The floor above is reached only by a host already on ROCm wheels that was demoted.+ # A fresh install, or a CPU/CUDA build, walks past it to the generic fallback, where a+ # stale /opt/rocm puts gfx950 on rocm6.3 the same way with no per-arch index to fall+ # back to. Which tag carries an arch is a fact about the arch, not about the install.+ if (+ _arch_index_url is None+ and not rocm_torch_ready+ and _runtime_gfx in _GENERIC_ROCM_WHEEL_GFX+ and _generic_tag_lacks_kernels(_runtime_gfx, ver)+ ):+ ver = max(_ROCM_TORCH_INDEX)+# gfx906 (MI50 / Radeon VII): is this the runtime GPU target? Used below to skip# the generic bitsandbytes wheel (no gfx906 kernels). This must hold even under# an explicit torch-index pin: a gfx906 host that pins rocm6.3 (without also# setting UNSLOTH_ROCM_GFX_ARCH) would otherwise reinstall the prebuilt bnb wheel# over the user's source-built gfx906 bnb. So a pin suppresses only the torch# reroute (_gfx906_override below), NOT the gfx906 detection for the bnb skip.- _runtime_is_gfx906 = _gfx906_arch_override or _runtime_target_is_gfx906()+ # _runtime_target_is_gfx906 reads UNSLOTH_ROCM_GFX_ARCH itself with the same+ # normalization, so asking it alone loses nothing, and ORing the override back in would+ # walk the no-GPU mask guard it applies above that read.+ _runtime_is_gfx906 = _runtime_target_is_gfx906()# Reroute torch to the last gfx906-capable wheel family (rocm6.3) only when the# host ROCm version would otherwise pick a newer, kernel-less index -- and never# over an explicit pin or an active Strix reroute (the pin/Strix path installs@@ -3691,7 +4548,7 @@ def _ensure_rocm_torch() -> None:_runtime_is_gfx906and _gfx906_needs_legacy_index(ver)and _explicit_rocm_torch_index_url() is None- and _strix_override_url is None+ and _arch_index_url is None)if _gfx906_override:_safe_print(@@ -3704,17 +4561,18 @@ def _ensure_rocm_torch() -> None:f" requires a source build of bitsandbytes for gfx906 (see docs.unsloth.ai/amd).\n")- # The Strix override must fire even when has_hip_torch is True: an existing- # torch.version.hip == "7.1" is exactly the broken combo it repairs.- if _strix_override_url is not None and _strix_override_pkgs is not None:- index_url = _strix_override_url- _torch_pkg, _vision_pkg, _audio_pkg = _strix_override_pkgs+ # Either reroute must fire even when has_hip_torch is True: an existing+ # torch.version.hip == "7.1" is exactly the broken combo they repair. The+ # missing-kernel route declines above when torch already runs on its leaf.+ if _arch_index_url is not None and _arch_index_pkgs is not None:+ index_url = _arch_index_url+ _torch_pkg, _vision_pkg, _audio_pkg = _arch_index_pkgs_safe_print(- f" Strix arch-specific override -- installing torch from "+ f" AMD per-gfx index override -- installing torch from "f"{_strip_index_url_credentials(index_url)}")pip_install(- "ROCm torch (Strix arch-specific)",+ f"ROCm torch (AMD per-gfx index, {_torch_index_leaf(index_url)})","--force-reinstall","--no-cache-dir",_torch_pkg,diff --git a/tests/studio/install/test_amd_fastpath_probe.py b/tests/studio/install/test_amd_fastpath_probe.pyindex 8c1504fcf1f..bc20ff95fc0 100644--- a/tests/studio/install/test_amd_fastpath_probe.py+++ b/tests/studio/install/test_amd_fastpath_probe.py@@ -46,6 +46,8 @@ def _host(linux = True,no_torch = False,env = None,+ probe_source = "kfd",+ installed_family = None,):"""A ROCm host with a CPU wheel by default; each argument moves one thing."""for name in _ROUTING_ENV:@@ -58,7 +60,20 @@ def _host(monkeypatch.setattr(stack.platform, "machine", lambda: machine)monkeypatch.setattr(stack, "_has_usable_nvidia_gpu", lambda: nvidia)monkeypatch.setattr(stack, "_has_rocm_gpu", lambda: rocm_gpu and not nvidia)- monkeypatch.setattr(stack, "_detect_amd_gfx_codes", lambda dedup = True: list(gfx))++ def _detect(dedup = True, **_kw):+ # The real probe records which tool answered; callers read it to decide whether the+ # list is ROCr-filtered and in the masks' order. Leaving the global at whatever ran+ # last makes that depend on test order, and on a real AMD box on the machine.+ stack._LAST_AMD_GFX_PROBE = probe_source if gfx else None+ return list(dict.fromkeys(gfx)) if dedup else list(gfx)++ monkeypatch.setattr(stack, "_detect_amd_gfx_codes", _detect)+ monkeypatch.setattr(stack, "_kfd_gfx_targets", lambda: [], raising = False)+ # No AMD per-arch wheel is installed unless a case says so: on the gfx1151 runner these+ # two read a real one out of the venv and decide gates no case here described.+ monkeypatch.setattr(stack, "_installed_rocm_wheel_family", lambda: installed_family)+ monkeypatch.setattr(stack, "_torch_requires_rocm_sdk", lambda: installed_family is not None)monkeypatch.setattr(stack, "_detect_rocm_version", lambda: rocm_ver)monkeypatch.setattr(stack, "_infer_linux_amd_gfx_arch", lambda: inferred)version, hip = torch@@ -119,7 +134,32 @@ def test_a_real_device_selection_is_not_a_hidden_host(monkeypatch):],)def test_a_rocm_wheel_keeps_the_fast_path(monkeypatch, torch):- _host(monkeypatch, torch = torch)+ # gfx1100 rather than the default gfx1151: the question here is whether a ROCm wheel is+ # left alone, and only an arch every one of these wheels actually carries asks it. Strix+ # is not that arch on the older tags, and the case below is where it is answered.+ _host(monkeypatch, torch = torch, gfx = ("gfx1100",))+ assert _needs_pass() is False++[email protected]("gfx", ["gfx1150", "gfx1151"])+def test_a_strix_host_on_a_wheel_without_its_kernels_forces_the_pass(monkeypatch, gfx):+ """rocm6.4 does not carry gfx1150/gfx1151 (AMD dates support to 7.1), and+ _ensure_rocm_torch already reroutes such a host on a fresh install. Keeping the fast path+ is the preflight declining a repair the repair itself performs."""+ _host(monkeypatch, torch = ("2.9.0+rocm6.4", "6.4"), gfx = (gfx,))+ assert _needs_pass() is True+ # A generic tag that does carry them is still not the build Strix wants: the reroute+ # prefers AMD's 7.13 fixes over every generic index below the floor, so the pass is due+ # until torch IS that build.+ _host(monkeypatch, torch = ("2.11.0+rocm7.2", "7.2"), gfx = (gfx,), rocm_ver = (7, 2))+ assert _needs_pass() is True+ _host(+ monkeypatch,+ torch = ("2.11.0+rocm7.13.0", "7.13"),+ gfx = (gfx,),+ rocm_ver = (7, 2),+ installed_family = gfx,+ )assert _needs_pass() is False@@ -140,9 +180,36 @@ def test_an_unreadable_torch_keeps_the_fast_path(monkeypatch, kwargs):assert _needs_pass() is False-def test_a_mixed_arch_host_keeps_the_fast_path(monkeypatch):- _host(monkeypatch, torch = ("2.9.0+cpu", ""), gfx = ("gfx1151", "gfx1100"))+def test_a_mixed_arch_host_keeps_the_fast_path_only_while_it_is_ambiguous(monkeypatch):+ """Being mixed is not being unreadable. Unpinned, probe and mask order can disagree with+ nothing to resolve it, so the fast path stands. Pinned, _runtime_gfx_target composes both+ layers and names a card whose generic wheel can still lack kernels for it."""+ # Ambiguous: amd-smi enumerates in discovery order and a mask indexes HIP order.+ _host(+ monkeypatch,+ torch = ("2.9.0+cpu", ""),+ gfx = ("gfx1151", "gfx1103"),+ probe_source = "amd-smi",+ env = {"HIP_VISIBLE_DEVICES": "1"},+ )assert _needs_pass() is False+ # Ambiguous: a UUID names a device but no position in a list of arches.+ _host(+ monkeypatch,+ torch = ("2.9.0+cpu", ""),+ gfx = ("gfx1151", "gfx1103"),+ env = {"ROCR_VISIBLE_DEVICES": "GPU-8d1f2e3a4b5c6d7e"},+ )+ assert _needs_pass() is False+ # Not ambiguous: KFD node order IS the order the mask indexes, so this names gfx1103,+ # whose generic wheel carries no kernels for it.+ _host(+ monkeypatch,+ torch = ("2.9.0+cpu", ""),+ gfx = ("gfx1100", "gfx1103"),+ env = {"HIP_VISIBLE_DEVICES": "1"},+ )+ assert _needs_pass() is Truedef test_two_cards_of_one_arch_are_not_ambiguous(monkeypatch):@@ -187,7 +254,7 @@ def test_a_set_hip_mask_shadows_the_cuda_alias(monkeypatch, cuda):"""CUDA_VISIBLE_DEVICES is HIP's alias, not a layer under it (_pick_visible_index).Hiding NVIDIA with CUDA_VISIBLE_DEVICES=-1 while pinning HIP is a real mixed-host- pattern; the HIP mask wins, so the GPU is visible and the wheel is repairable.+ pattern: the HIP mask wins, so the GPU is visible and the wheel repairable."""_host(monkeypatch,@@ -308,8 +375,8 @@ def _decision(result):"""The CLI's own account of which input produced its exit code.Exit 1 alone is five states (no-torch venv, resolved backend, non-ROCm pin, absent or- masked AMD host, unreadable torch), so the code cannot say which one it saw. Asserting- the line back against the code keeps the diagnostic from drifting off the decision.+ masked AMD host, unreadable torch), so the code cannot say which it saw. Asserting the+ line back against the code keeps the diagnostic from drifting."""stdout = result.stdout.decode(errors = "replace")marked = [@@ -459,10 +526,18 @@ def _repair_installs(monkeypatch):dict(rocm_ver = (6, 4), inferred = None, gfx = ("gfx1030",)),True,),- # The repair prints "skipping torch reinstall" and returns for all three.+ # The default host here is Strix, whose per-arch index needs no host ROCm version, so+ # an unreadable one is the shape that route exists for rather than a reason to stop.(- "a visible GPU whose ROCm version cannot be read",+ "a visible Strix GPU whose ROCm version cannot be read",dict(rocm_ver = None, inferred = None),+ True,+ ),+ # A non-Strix arch the generic wheel does carry: the repair prints "skipping torch+ # reinstall" and returns, so the preflight must keep the fast path.+ (+ "a visible GPU whose ROCm version cannot be read",+ dict(rocm_ver = None, inferred = None, gfx = ("gfx1100",)),False,),(@@ -489,3 +564,217 @@ def test_the_preflight_and_the_repair_agree(monkeypatch, label, host, expected):assert installs, f"{label}: preflight forced a pass the repair declined"else:assert not installs, f"{label}: the repair acts but the preflight kept the fast path"+++# Right wheel family, wrong architecture+++def _rocm_torch(+ monkeypatch,+ *,+ family,+ owns_sdk = None,+ **kw,+):+ """A host whose torch IS a ROCm build.++ ``family`` is the per-arch family it reads back as; None means unknowable.+ ``owns_sdk`` is whether torch requires AMD's rocm[libraries], separating a generic wheel+ (False, no family to read) from a per-arch install whose family will not read back.+ """+ _host(monkeypatch, torch = ("2.11.0+rocm7.13.0", "7.13"), **kw)+ _owns = family is not None if owns_sdk is None else owns_sdk+ monkeypatch.setattr(stack, "_torch_requires_rocm_sdk", lambda: _owns)+ monkeypatch.setattr(stack, "_installed_rocm_wheel_family", lambda: family)+++def test_a_generic_wheel_without_kernels_for_this_gpu_forces_the_pass(monkeypatch):+ """The reported host on an update. Torch is a ROCm build, which used to end the probe+ for all of them, so the repair was reachable on a fresh install and never on update."""+ _rocm_torch(monkeypatch, family = None, gfx = ("gfx1103",))+ assert _needs_pass() is True+++def test_a_per_arch_wheel_built_for_another_gpu_forces_the_pass(monkeypatch):+ """A per-arch install outlives the card it was made for: the gfx110X-all wheels carry+ no gfx1200 kernels, and no update would ever notice."""+ _rocm_torch(monkeypatch, family = "gfx110x-all", gfx = ("gfx1200",))+ assert _needs_pass() is True+++def test_that_repair_is_reachable_with_no_readable_rocm_version(monkeypatch):+ """Both per-arch repairs are version-independent, and a bundled-runtime host has no+ system ROCm to read a version from -- the very host they exist for."""+ _rocm_torch(monkeypatch, family = "gfx110x-all", gfx = ("gfx1200",), rocm_ver = None)+ assert _needs_pass() is True+++ "family, gfx",+ [+ ("gfx1152", ("gfx1152",)), # already on its own leaf+ ("gfx110x-all", ("gfx1103",)), # already on the leaf this GPU needs+ (None, ("gfx1100",)), # generic wheels do carry kernels for it+ ],+)+def test_a_healthy_rocm_install_still_keeps_the_fast_path(monkeypatch, family, gfx):+ """The cost of a wrong True is only a dependency pass, but an update that runs one every+ time is the reason this probe exists."""+ _rocm_torch(monkeypatch, family = family, gfx = gfx)+ assert _needs_pass() is False+++def test_an_unknowable_family_keeps_the_fast_path(monkeypatch):+ """_installed_rocm_wheel_family answers None for two runtimes with no `rocm` to+ arbitrate. _ensure_rocm_torch cannot skip on a family it never read, so forcing the pass+ would reinstall the multi-GB stack on every single update rather than once."""+ _rocm_torch(monkeypatch, family = None, owns_sdk = True, gfx = ("gfx1152",))+ assert _needs_pass() is False+++def test_a_matching_family_below_its_torch_floor_forces_the_pass(monkeypatch):+ """The family is the right SHAPE, not a working build: below 2.11 these leaves carry the+ _grouped_mm bug, and _already_on_leaf keeps a matching family only above that floor.+ Keeping the fast path here leaves the broken build in place on every update."""+ _rocm_torch(monkeypatch, family = "gfx1152", gfx = ("gfx1152",))+ monkeypatch.setattr(+ stack, "_probe_torch_runtime", lambda: (True, True, "2.10.0+rocm7.13.0", "7.13", "")+ )+ assert _needs_pass() is True+++def test_a_leaf_with_no_torch_floor_keeps_the_fast_path_below_211(monkeypatch):+ """Only the leaves in _ROCM_GFX_TORCH211_LEAVES have that bug; the rest ship <2.11 builds+ and are correct as they are, so the floor must not be applied to them."""+ _rocm_torch(monkeypatch, family = "gfx110x-all", gfx = ("gfx1103",))+ monkeypatch.setattr(+ stack, "_probe_torch_runtime", lambda: (True, True, "2.10.0+rocm7.13.0", "7.13", "")+ )+ assert _needs_pass() is False+++def test_a_named_arch_resolves_a_host_no_ordinal_can(monkeypatch):+ """The decline message offers UNSLOTH_ROCM_GFX_ARCH as the way through, so it has to be+ one: the user naming the arch outright is the reading no ordinal or UUID can contradict.+ Without it the same host stays ambiguous and keeps the fast path."""+ _host(+ monkeypatch,+ torch = ("2.9.0+cpu", ""),+ gfx = ("gfx1151", "gfx1103"),+ probe_source = "amd-smi",+ env = {"HIP_VISIBLE_DEVICES": "1", "UNSLOTH_ROCM_GFX_ARCH": "gfx1103"},+ )+ assert _needs_pass() is True+++def test_a_rocm_pin_is_not_asked_a_hardware_question(monkeypatch):+ """A pin commits to an index regardless of the visible GPU, which is why every hardware+ gate above it is skipped. Asked under a pin, the family question answers for whatever card+ the probing machine has -- how the end-to-end CLI case began failing on an AMD box."""+ # The pin names the family torch already carries, so nothing is due for it either.+ _rocm_torch(+ monkeypatch,+ family = "gfx110x-all",+ gfx = ("gfx1151",),+ env = {"UNSLOTH_TORCH_INDEX_URL": "https://download.pytorch.org/whl/rocm7.13"},+ )+ assert _needs_pass() is False+ # A pin that no longer matches the installed wheel is the pin's own question, not a+ # hardware one, and _ensure_rocm_torch reinstalls for it.+ _rocm_torch(+ monkeypatch,+ family = "gfx110x-all",+ gfx = ("gfx1151",),+ env = {"UNSLOTH_TORCH_INDEX_URL": "https://download.pytorch.org/whl/rocm6.4"},+ )+ assert _needs_pass() is True+ # The same stale family without a pin is exactly what the repair is for.+ _rocm_torch(monkeypatch, family = "gfx110x-all", gfx = ("gfx1151",))+ assert _needs_pass() is True+++def test_a_stale_family_no_index_can_repair_keeps_the_fast_path(monkeypatch):+ """The preflight must not promise a repair the repair declines. gfx1010 has no AMD leaf+ and no generic kernels, so _ensure_rocm_torch refuses on the same routability question,+ and answering True here buys a dependency pass per update and never a working torch."""+ _rocm_torch(monkeypatch, family = "gfx110x-all", gfx = ("gfx1010",))+ assert _needs_pass() is False+ # An empty leaf is not the test: the datacentre parts have none and the generic index+ # serves them, so their stale family is still worth the pass.+ for _gfx in ("gfx942", "gfx950"):+ _rocm_torch(monkeypatch, family = "gfx110x-all", gfx = (_gfx,))+ assert _needs_pass() is True, _gfx+++def test_a_mixed_host_gfx906_keeps_the_fast_path(monkeypatch):+ """gfx906 answers the abstract routability question yes, but its one usable route is the+ rocm6.3 tag, which opens only when it is the sole detected arch. _ensure_rocm_torch+ declines the demotion there, so asking the abstract question buys a pass and no repair."""+ _rocm_torch(+ monkeypatch,+ family = "gfx110x-all",+ gfx = ("gfx1100", "gfx906"),+ env = {"HIP_VISIBLE_DEVICES": "1"},+ )+ assert _needs_pass() is False+ # Alone, gfx906 does have a route, and the same stale family is worth the pass.+ _rocm_torch(monkeypatch, family = "gfx110x-all", gfx = ("gfx906",))+ assert _needs_pass() is True+++def test_a_confirmed_spoof_forces_the_pass_even_on_a_matching_family(monkeypatch):+ """_clear_confirmed_hsa_spoof runs only inside _ensure_rocm_torch, so a fast path taken+ on the wheel question alone leaves HSA_OVERRIDE_GFX_VERSION set: ROCr keeps presenting an+ ISA the installed wheels have no code for (#7331), however well the family matches."""+ _rocm_torch(+ monkeypatch,+ family = "gfx1152",+ gfx = (),+ rocm_ver = None,+ env = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ )+ monkeypatch.setattr(stack, "_kfd_gfx_targets", lambda: ["gfx1152"], raising = False)+ assert _needs_pass() is True+++def test_a_sole_gfx906_above_its_legacy_tag_forces_the_pass(monkeypatch):+ """The gfx906 reroute is a compatibility reroute, not a missing-kernel one, so the wheel+ question never saw it and the rocm6.3 downgrade was unreachable from `studio update`."""+ _rocm_torch(monkeypatch, family = None, gfx = ("gfx906",), rocm_ver = (6, 4))+ assert _needs_pass() is True+ # Already on the legacy tag: nothing left to do.+ _host(monkeypatch, torch = ("2.9.0+rocm6.3", "6.3"), gfx = ("gfx906",), rocm_ver = (6, 4))+ assert _needs_pass() is False+++def test_a_repin_to_another_per_arch_leaf_forces_the_pass(monkeypatch):+ """Both leaves are torch 2.11 with a three-part +rocm7.13.0 tag, so the pin arm's version+ comparison sees no change and would keep the fast path over an edited pin -- the update+ that was supposed to move the card onto its own wheels."""+ _rocm_torch(+ monkeypatch,+ family = "gfx110x-all",+ env = {"UNSLOTH_TORCH_INDEX_URL": "https://repo.amd.com/rocm/whl/gfx120X-all/"},+ )+ assert _needs_pass() is True+++def test_a_pin_naming_the_installed_leaf_keeps_the_fast_path(monkeypatch):+ """The same comparison the other way: nothing to apply, so nothing to pass for."""+ _rocm_torch(+ monkeypatch,+ family = "gfx120x-all",+ env = {"UNSLOTH_TORCH_INDEX_URL": "https://repo.amd.com/rocm/whl/gfx120X-all/"},+ )+ assert _needs_pass() is False+++def test_a_pin_at_a_non_floor_leaf_already_satisfied_keeps_the_fast_path(monkeypatch):+ """The pin arm now answers the preflight, so a heuristic that calls a valid environment+ stale costs a dependency pass on every update as well as the reinstall behind it."""+ _rocm_torch(+ monkeypatch,+ family = "gfx110x-all",+ env = {"UNSLOTH_TORCH_INDEX_URL": "https://repo.amd.com/rocm/whl/gfx110X-all/"},+ )+ assert _needs_pass() is Falsediff --git a/tests/studio/install/test_installed_family_hermeticity.py b/tests/studio/install/test_installed_family_hermeticity.pynew file mode 100644index 00000000000..250cc4a26c4--- /dev/null+++ b/tests/studio/install/test_installed_family_hermeticity.py@@ -0,0 +1,223 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A test that reaches the reinstall skip without pinning the installed-wheel pair reads+the machine running pytest, so it passes on a bare laptop and fails on any host that+already has AMD per-arch torch. Three cases in TestEnsureRocmTorch did.++_installed_rocm_wheel_family and _torch_requires_rocm_sdk go to importlib.metadata for the+RUNNING interpreter, which is the venv being repaired at install time and the test runner+here. This file fakes the metadata layer, never the functions, so their parsing still runs.+"""++from __future__ import annotations++import importlib.util+import io+import os+import sys+from contextlib import contextmanager+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+++PACKAGE_ROOT = Path(__file__).resolve().parents[3]++_STACK_PATH = PACKAGE_ROOT / "studio" / "install_python_stack.py"+_STACK_SPEC = importlib.util.spec_from_file_location(+ "studio_install_python_stack_hermeticity", _STACK_PATH+)+assert _STACK_SPEC is not None and _STACK_SPEC.loader is not None+stack_mod = importlib.util.module_from_spec(_STACK_SPEC)+sys.modules[_STACK_SPEC.name] = stack_mod+_STACK_SPEC.loader.exec_module(stack_mod)++_MARK = stack_mod._TORCH_PROBE_MARKER++# `rocm` Requires-Dist, torch Requires-Dist, distributions on disk. Two are pip behaviours,+# not hypotheticals: installing a generic wheel over a per-arch one drops rocm[libraries]+# from torch but leaves `rocm` naming the old family, and a family switch upgrades `rocm`+# in place without uninstalling the superseded runtime.+AMBIENT_STATES: "dict[str, tuple]" = {+ "bare": (None, ["filelock"], []),+ "perarch-gfx1151": (+ ["rocm-sdk-libraries-gfx1151==7.13.0; extra == 'libraries'"],+ ["rocm[libraries]==7.13.0"],+ ["rocm", "rocm-sdk-libraries-gfx1151"],+ ),+ "perarch-gfx110X-all": (+ ["rocm-sdk-libraries-gfx110X-all==7.13.0; extra == 'libraries'"],+ ["rocm[libraries]==7.13.0"],+ ["rocm", "rocm-sdk-libraries-gfx110X-all"],+ ),+ "perarch-gfx120X-all": (+ ["rocm-sdk-libraries-gfx120X-all==7.13.0; extra == 'libraries'"],+ ["rocm[libraries]==7.13.0"],+ ["rocm", "rocm-sdk-libraries-gfx120X-all"],+ ),+ "generic-with-orphan-rocm": (+ ["rocm-sdk-libraries-gfx110X-all==7.13.0; extra == 'libraries'"],+ ["filelock"],+ ["rocm", "rocm-sdk-libraries-gfx110X-all"],+ ),+ "two-families-after-switch": (+ None,+ ["filelock"],+ ["rocm-sdk-libraries-gfx110X-all", "rocm-sdk-libraries-gfx1151"],+ ),+}+++class _Dist:+ """The one attribute _installed_rocm_wheel_family reads off a distribution."""++ def __init__(self, name: str):+ self.metadata = {"Name": name}+++@contextmanager+def ambient(state: str):+ """Make importlib.metadata describe ``state`` instead of this interpreter."""+ from importlib import metadata++ rocm_reqs, torch_reqs, dists = AMBIENT_STATES[state]+ real_requires = metadata.requires++ def _requires(name):+ if name == "rocm":+ if rocm_reqs is None:+ raise metadata.PackageNotFoundError("rocm")+ return list(rocm_reqs)+ if name == "torch":+ return list(torch_reqs)+ return real_requires(name)++ with (+ patch.object(metadata, "requires", _requires),+ patch.object(metadata, "distributions", lambda *a, **kw: [_Dist(n) for n in dists]),+ ):+ yield+++def _route(+ gfx: str,+ torch_line: str,+ env: "dict | None" = None,+ family: "str | None" = None,+ torch_owns_rocm: bool = False,+) -> str:+ """Every pip argument _ensure_rocm_torch() produced, as one string. ``family`` /+ ``torch_owns_rocm`` pin the installed-wheel pair; the defaults are "no ROCm installed"."""+ pip, pip_try = MagicMock(), MagicMock(return_value = True)+ probe = MagicMock(returncode = 0, stdout = _MARK + torch_line + "\n")+ buf = io.StringIO()++ stack_mod._invalidate_torch_runtime_probe()+ with (+ patch.dict(os.environ, env or {}, clear = False),+ patch.object(stack_mod, "IS_WINDOWS", False),+ patch.object(stack_mod, "IS_MACOS", False),+ patch.object(stack_mod, "_TORCH_BACKEND", ""),+ patch.object(stack_mod.platform, "machine", return_value = "x86_64"),+ patch.object(stack_mod, "pip_install", pip),+ patch.object(stack_mod, "pip_install_try", pip_try),+ patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = False),+ patch.object(stack_mod, "_has_rocm_gpu", return_value = True),+ patch.object(stack_mod, "_infer_linux_amd_gfx_arch", return_value = None),+ patch.object(stack_mod, "_detect_amd_gfx_codes", return_value = [gfx]),+ patch.object(stack_mod, "_detect_rocm_version", return_value = (7, 1)),+ patch.object(stack_mod, "_kfd_gfx_targets", return_value = []),+ patch.object(stack_mod, "_installed_rocm_wheel_family", return_value = family),+ patch.object(stack_mod, "_torch_requires_rocm_sdk", return_value = torch_owns_rocm),+ patch.object(stack_mod.os.path, "isdir", return_value = True),+ patch.object(stack_mod.subprocess, "run", return_value = probe),+ ):+ for _stale in (+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ "UNSLOTH_ROCM_GFX_ARCH",+ "UNSLOTH_TORCH_INDEX_URL",+ "UNSLOTH_AMD_ROCM_MIRROR",+ "UNSLOTH_ROCM_TORCH_INSTALLED",+ ):+ if _stale not in (env or {}):+ os.environ.pop(_stale, None)+ stack_mod._invalidate_torch_runtime_probe()+ import contextlib++ with contextlib.redirect_stdout(buf):+ stack_mod._ensure_rocm_torch()+ stack_mod._invalidate_torch_runtime_probe()+ return str(pip.call_args_list) + str(pip_try.call_args_list)+++# The generic-ROCm hosts are the interesting ones: that is where the skip arms live.+HOSTS = {+ "gfx1103-cpu-torch": ("gfx1103", "2.10.0+cpu||"),+ "gfx1103-generic-rocm": ("gfx1103", "2.10.0+rocm7.1|7.1|"),+ "gfx1100-generic-rocm": ("gfx1100", "2.10.0+rocm7.1|7.1|"),+}++[email protected]("host", sorted(HOSTS))+def test_pinning_the_pair_makes_this_machine_irrelevant(host):+ """Pinning the pair is SUFFICIENT isolation. Not "routing ignores what is installed" --+ at install time it must not; the claim is that these two functions are the only door."""+ gfx, torch_line = HOSTS[host]+ with ambient("bare"):+ expected = _route(gfx, torch_line)+ for state in AMBIENT_STATES:+ with ambient(state):+ got = _route(gfx, torch_line)+ assert got == expected, (+ f"{host} routes differently when the interpreter running the tests is in the "+ f"{state!r} state, even though the installed-wheel pair is pinned. Something in "+ f"_ensure_rocm_torch now reads this venv by a path those two functions do not "+ f"cover, so the suite's verdict depends on who runs it.\n"+ f" bare: {expected}\n {state}: {got}"+ )+++ "family, torch_owns_rocm, expect_reinstall",+ [+ (None, False, True),+ ("gfx110x-all", True, False),+ # Family matches but torch does not own it: the orphan, so the running torch is the+ # generic build with no gfx1103 kernels and the skip must not fire.+ ("gfx110x-all", False, True),+ ("gfx120x-all", True, True),+ ],+ ids = ["no-family", "correct-family", "orphan-metapackage", "wrong-family"],+)+def test_the_installed_family_decides_the_skip(family, torch_owns_rocm, expect_reinstall):+ """The other half: without this, pinning both to None would satisfy the test above while+ the feature they gate quietly stopped working."""+ with ambient("bare"):+ calls = _route(+ "gfx1103", "2.10.0+rocm7.13.0|7.13|", family = family, torch_owns_rocm = torch_owns_rocm+ )+ rerouted = "repo.amd.com/rocm/whl/gfx110X-all/" in calls+ assert rerouted is expect_reinstall, (+ f"family={family!r} torch_owns_rocm={torch_owns_rocm} should "+ f"{'reinstall' if expect_reinstall else 'keep the installed wheels'}; got {calls}"+ )+++def test_the_states_are_distinguishable():+ """Non-vacuity: if the fake metadata said nothing, the test above would pass emptily."""+ with ambient("perarch-gfx1151"):+ assert stack_mod._installed_rocm_wheel_family() == "gfx1151"+ assert stack_mod._torch_requires_rocm_sdk() is True+ with ambient("bare"):+ assert stack_mod._installed_rocm_wheel_family() is None+ assert stack_mod._torch_requires_rocm_sdk() is False+ with ambient("generic-with-orphan-rocm"):+ assert stack_mod._installed_rocm_wheel_family() == "gfx110x-all"+ assert stack_mod._torch_requires_rocm_sdk() is False+ with ambient("two-families-after-switch"):+ # Two runtimes, no `rocm` to arbitrate: unknowable, not a guess.+ assert stack_mod._installed_rocm_wheel_family() is Nonediff --git a/tests/studio/install/test_missing_kernel_arch_routing_9396.py b/tests/studio/install/test_missing_kernel_arch_routing_9396.pynew file mode 100644index 00000000000..0572c6cbffc--- /dev/null+++ b/tests/studio/install/test_missing_kernel_arch_routing_9396.py@@ -0,0 +1,1735 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Routing tests for ROCm targets absent from PyTorch's generic wheels.++Torch, hardware probes, and pip are mocked; the generic wheel architecture list was measured.+"""++from __future__ import annotations++import contextlib+import importlib.util+import io+import os+import sys+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+++PACKAGE_ROOT = Path(__file__).resolve().parents[3]++_STACK_PATH = PACKAGE_ROOT / "studio" / "install_python_stack.py"+_STACK_SPEC = importlib.util.spec_from_file_location(+ "studio_install_python_stack_9396", _STACK_PATH+)+assert _STACK_SPEC is not None and _STACK_SPEC.loader is not None+stack_mod = importlib.util.module_from_spec(_STACK_SPEC)+sys.modules[_STACK_SPEC.name] = stack_mod+_STACK_SPEC.loader.exec_module(stack_mod)++_CPU_TORCH = stack_mod._TORCH_PROBE_MARKER + "2.10.0+cpu||\n"+# Generic pytorch.org ROCm torch: links HIP, so has_hip_torch is True and every+# "already installed" gate sees a ROCm build -- the state the repair must still fix.+_ROCM_GENERIC_TORCH = stack_mod._TORCH_PROBE_MARKER + "2.10.0+rocm7.1|7.1|\n"+# AMD per-arch torch, as repo.amd.com serves it.+_ROCM_ARCH_TORCH = stack_mod._TORCH_PROBE_MARKER + "2.11.0+rocm7.13.0|7.13|\n"+# Generic wheels whose own rocm tag disagrees with the host: pinned once, or outlived by an+# /opt/rocm upgrade.+_ROCM_GENERIC_TORCH_63 = stack_mod._TORCH_PROBE_MARKER + "2.9.1+rocm6.3|6.3|\n"+_ROCM_GENERIC_TORCH_72 = stack_mod._TORCH_PROBE_MARKER + "2.11.0+rocm7.2|7.2|\n"++_GENERIC = "download.pytorch.org/whl/rocm"+_AMD = "repo.amd.com/rocm/whl"++[email protected](autouse = True)+def _reset_torch_runtime_probe():+ stack_mod._invalidate_torch_runtime_probe()+ yield+ stack_mod._invalidate_torch_runtime_probe()+++def _run_install(+ *,+ gfx_devices = ("gfx1103",),+ inferred = None,+ rocm_version = (7, 1),+ env = None,+ kfd = (),+ torch_probe = None,+ installed_family = None,+ rocm_gpu_visible = True,+ torch_owns_rocm = True,+ probe_source = "kfd",+ unmasked_gfx_devices = None,+):+ """Drive _ensure_rocm_torch() over a host with ``gfx_devices`` and return the pip calls."""+ # The torch probe is cached per process and the autouse fixture clears it once per TEST,+ # so a case driving two hosts in a row would judge the second by the first's torch.+ stack_mod._invalidate_torch_runtime_probe()+ probe = MagicMock()+ probe.returncode = 0+ probe.stdout = torch_probe or _CPU_TORCH++ probes = []++ def _fake_detect(+ dedup = True,+ ignore_hsa_override = False,+ ignore_visible_masks = False,+ ):+ probes.append(dedup)+ # rocminfo runs on the ROCr stack, so its answer is already mask-filtered; only a+ # re-probe that strips the masks sees the whole machine. A caller that sets+ # unmasked_gfx_devices is modelling exactly that gap.+ codes = list(+ unmasked_gfx_devices+ if (ignore_visible_masks and unmasked_gfx_devices is not None)+ else gfx_devices+ )+ # Callers read the recorded probe to decide whether the list is ROCr-filtered and in+ # HIP order. This one hands back device order, which is KFD sysfs; leaving the global+ # as the previous test left it makes those decisions test-order dependent.+ stack_mod._LAST_AMD_GFX_PROBE = probe_source if codes else None+ return list(dict.fromkeys(codes)) if dedup else codes++ _env = dict(env or {})+ if _env.get("UNSLOTH_ROCM_GFX_ARCH"):+ inferred = _env["UNSLOTH_ROCM_GFX_ARCH"]++ with (+ patch.object(stack_mod, "IS_WINDOWS", False),+ patch.object(stack_mod, "pip_install_try", return_value = True) as pip_try,+ patch.object(stack_mod, "pip_install") as pip,+ patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = False),+ patch.object(stack_mod, "_has_rocm_gpu", return_value = rocm_gpu_visible),+ patch.object(stack_mod, "_infer_linux_amd_gfx_arch", return_value = inferred),+ patch.object(stack_mod, "_detect_amd_gfx_codes", side_effect = _fake_detect),+ patch.object(stack_mod, "_detect_rocm_version", return_value = rocm_version),+ patch.object(stack_mod, "_kfd_gfx_targets", return_value = list(kfd), create = True),+ patch.object(stack_mod, "_installed_rocm_wheel_family", return_value = installed_family),+ patch.object(stack_mod, "_torch_requires_rocm_sdk", return_value = torch_owns_rocm),+ patch.dict(os.environ, _env, clear = False),+ ):+ for _stale in (+ "UNSLOTH_ROCM_GFX_ARCH",+ "UNSLOTH_AMD_ROCM_MIRROR",+ "UNSLOTH_TORCH_INDEX_URL",+ "UNSLOTH_TORCH_INDEX_FAMILY",+ "HSA_OVERRIDE_GFX_VERSION",+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ ):+ if _stale not in _env:+ os.environ.pop(_stale, None)+ _out = io.StringIO()+ with patch("os.path.isdir", return_value = True):+ with patch("subprocess.run", return_value = probe):+ with contextlib.redirect_stdout(_out):+ stack_mod._ensure_rocm_torch()+ _run_install.hsa_override_after = os.environ.get("HSA_OVERRIDE_GFX_VERSION")+ _run_install.probes = probes+ _run_install.printed = _out.getvalue()+ return str(pip.call_args_list) + str(pip_try.call_args_list)+++# ── the reported host, and its two siblings ──────────────────────────────────+++ "gfx, leaf",+ [+ ("gfx1103", "gfx110X-all"), # Radeon 780M / 760M / 740M -- the reported card+ ("gfx1032", "gfx103X-all"), # RX 6650 / 6600+ ("gfx1034", "gfx103X-all"), # RX 6500 / 6400 / 6300+ ],+)+def test_an_arch_with_no_generic_kernels_routes_to_the_amd_index(gfx, leaf):+ calls = _run_install(gfx_devices = (gfx,))+ assert f"{_AMD}/{leaf}/" in calls, calls+ assert _GENERIC not in calls, calls+ # The carrier is shared with the Strix reroute, so the label has to name the leaf+ # actually installed; a 780M laptop reading "Strix" is the installer lying to it.+ assert f"AMD per-gfx index, {leaf.lower()}" in calls, calls+++def test_no_nameable_arch_is_left_without_kernels():+ """Every named arch has either generic kernels or an AMD per-arch route."""+ nameable = {arch for _pat, arch in stack_mod._WIN_GPU_NAME_ARCH_TABLE}+ stranded = {+ arch+ for arch in nameable+ if arch not in stack_mod._GENERIC_ROCM_WHEEL_GFX+ and not stack_mod._generic_rocm_wheel_lacks_kernels(arch)+ }+ assert stranded == set(), stranded+++def test_the_rule_covers_the_rdna2_arches_the_name_table_never_spells():+ """Cover RDNA 2 arches reported by rocminfo but absent from the name table."""+ for arch in ("gfx1031", "gfx1033", "gfx1035", "gfx1036"):+ assert stack_mod._generic_rocm_wheel_lacks_kernels(arch), arch+ assert stack_mod._GFX_TO_AMD_INDEX_ARCH[arch] == "gfx103X-all"+++def test_the_leaf_comes_from_the_map_windows_already_routes_by():+ """One arch/leaf pairing for both platforms; a second table here could drift from it."""+ assert stack_mod._GFX_TO_AMD_INDEX_ARCH["gfx1103"] == "gfx110X-all"+ assert stack_mod._GFX_TO_AMD_INDEX_ARCH["gfx1032"] == "gfx103X-all"++[email protected]("arch", ["gfx1030", "gfx1100", "gfx1151", "gfx942", "gfx1201"])+def test_an_arch_the_generic_wheel_carries_is_never_rerouted(arch):+ assert not stack_mod._generic_rocm_wheel_lacks_kernels(arch)+++def test_an_arch_with_no_amd_leaf_keeps_todays_behaviour():+ """Nothing better to route to, so the rule declines rather than inventing a leaf."""+ assert not stack_mod._generic_rocm_wheel_lacks_kernels("gfx803")+ assert not stack_mod._generic_rocm_wheel_lacks_kernels("gfx1010")+ assert not stack_mod._generic_rocm_wheel_lacks_kernels(None)+++def test_the_reroute_is_not_gated_on_the_rocm_version_floor():+ """Missing generic kernels require rerouting regardless of the ROCm version."""+ calls = _run_install(gfx_devices = ("gfx1103",), rocm_version = (7, 13))+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_the_companion_pins_are_bounded_but_not_floored_at_211():+ """Bound companion versions without excluding older per-arch mirror builds."""+ calls = _run_install(gfx_devices = ("gfx1103",))+ for spec in stack_mod._ROCM_ARCH_INDEX_TORCH_PKG_SPEC:+ assert spec in calls, (spec, calls)+ assert "torch>=2.11.0" not in calls, calls+ # Every companion is bounded above, so none can drift to a different torch major.+ assert all("<" in spec for spec in stack_mod._ROCM_ARCH_INDEX_TORCH_PKG_SPEC)+++def test_the_hardware_is_probed_once_for_both_reroutes():+ """The Strix and missing-kernel reroutes share one per-device hardware probe."""+ _run_install(gfx_devices = ("gfx1103",))+ per_device = [dedup for dedup in _run_install.probes if dedup is False]+ assert len(per_device) == 1, _run_install.probes+++def test_the_shared_probe_still_reaches_strix_above_the_rocm_floor():+ """The shared probe still reaches missing-kernel routing above the Strix floor."""+ calls = _run_install(gfx_devices = ("gfx1103",), rocm_version = (7, 13))+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_the_mirror_override_is_honoured():+ calls = _run_install(+ gfx_devices = ("gfx1103",), env = {"UNSLOTH_AMD_ROCM_MIRROR": "https://mirror.test/whl"}+ )+ assert "https://mirror.test/whl/gfx110X-all/" in calls, calls+++# ── the neighbours this must not disturb ─────────────────────────────────────++[email protected]("gfx", ["gfx1100", "gfx1102", "gfx1030", "gfx1201"])+def test_a_supported_arch_keeps_the_generic_index(gfx):+ calls = _run_install(gfx_devices = (gfx,))+ assert _GENERIC in calls, calls+ assert _AMD not in calls, calls+++def test_strix_still_takes_its_own_reroute():+ """#7331's path runs through the extracted detection helper now; it must be unchanged."""+ calls = _run_install(gfx_devices = ("gfx1151",), inferred = "gfx1151")+ assert f"{_AMD}/gfx1151/" in calls, calls+ assert "torch>=2.11.0,<2.12.0" in calls, calls+++def test_an_explicit_index_pin_wins():+ calls = _run_install(+ gfx_devices = ("gfx1103",),+ env = {"UNSLOTH_TORCH_INDEX_URL": "https://download.pytorch.org/whl/rocm6.4"},+ )+ assert _AMD not in calls, calls+++def test_the_gfx906_arch_override_wins():+ """A pinned MI50 runtime target must not be rerouted by a gfx1103 sitting in the same box."""+ calls = _run_install(gfx_devices = ("gfx1103", "gfx906"), env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx906"})+ assert _AMD not in calls, calls+++def test_a_mixed_host_whose_runtime_target_is_supported_keeps_the_generic_index():+ """gfx1103 present, but the visible-device mask selects the dGPU: rerouting would pull the+ wrong wheel for the card that will actually run."""+ calls = _run_install(gfx_devices = ("gfx1100", "gfx1103"), env = {"HIP_VISIBLE_DEVICES": "0"})+ assert _GENERIC in calls, calls+ assert _AMD not in calls, calls+++# ── the probe the routing decision indexes into ──────────────────────────────++# Measured on an AMD DevLab strix-halo host (amd-smi 26.2.2): `list` carries no gfx+# token at all, only `static --asic` does, and both head every device with a+# line-leading "GPU: N" while naming no agent.+_AMD_SMI_LIST = "GPU: 0\n BDF: 0000:03:00.0\n KFD_ID: 40251\n NODE_ID: 1\n"+++def _amd_smi_asic(arches):+ return "".join(+ f"GPU: {i}\n"+ f" ASIC:\n"+ f" MARKET_NAME: AMD Radeon Graphics\n"+ f" DEVICE_ID: 0x1586\n"+ f" TARGET_GRAPHICS_VERSION: {arch}\n"+ for i, arch in enumerate(arches)+ )+++def _amd_smi_only_host(arches):+ """Patches making the real probes see an amd-smi-only host with ``arches``."""++ def _which(name):+ return None if name == "rocminfo" else f"/usr/bin/{name}"++ def _run(cmd, **kwargs):+ out = MagicMock()+ out.returncode = 0+ out.stdout = (+ _AMD_SMI_LIST if list(cmd[:2]) == ["amd-smi", "list"] else _amd_smi_asic(arches)+ )+ return out++ return (+ patch("shutil.which", side_effect = _which),+ patch.object(stack_mod, "_amd_smi_allowed", return_value = True),+ patch("subprocess.run", side_effect = _run),+ )+++def _detect_over_amd_smi(arches, dedup = False):+ _which_p, _allowed_p, _run_p = _amd_smi_only_host(arches)+ with _which_p, _allowed_p, _run_p:+ return stack_mod._detect_amd_gfx_codes(dedup = dedup)+++def test_amd_smi_keeps_one_entry_per_device():+ """dedup=False indexes DEVICES, and amd-smi names no agent: without its GPU: N+ header the output is flat, so two cards of one arch collapse into one entry and+ every device ordinal past them addresses the wrong card."""+ assert _detect_over_amd_smi(("gfx1200", "gfx1200", "gfx1032")) == [+ "gfx1200",+ "gfx1200",+ "gfx1032",+ ]+++def test_amd_smi_still_reports_arches_when_asked_to_dedup():+ assert _detect_over_amd_smi(("gfx1200", "gfx1200", "gfx1032"), dedup = True) == [+ "gfx1200",+ "gfx1032",+ ]+++def test_a_repeated_arch_on_an_amd_smi_host_does_not_shift_the_mask():+ """HIP_VISIBLE_DEVICES=1 over gfx1200, gfx1200, gfx1032 selects a gfx1200. Reading a+ collapsed list would call it gfx1032 and install gfx103X-all wheels, stranding the+ card that will actually run -- on a host the generic index already served."""+ probe = MagicMock()+ probe.returncode = 0+ probe.stdout = _CPU_TORCH+ _which_p, _allowed_p, _run_p = _amd_smi_only_host(("gfx1200", "gfx1200", "gfx1032"))++ def _run(cmd, **kwargs):+ if str(cmd[0]) == sys.executable:+ return probe+ out = MagicMock()+ out.returncode = 0+ out.stdout = (+ _AMD_SMI_LIST+ if list(cmd[:2]) == ["amd-smi", "list"]+ else _amd_smi_asic(("gfx1200", "gfx1200", "gfx1032"))+ )+ return out++ with (+ patch.object(stack_mod, "IS_WINDOWS", False),+ patch.object(stack_mod, "pip_install_try", return_value = True) as pip_try,+ patch.object(stack_mod, "pip_install") as pip,+ patch.object(stack_mod, "_has_usable_nvidia_gpu", return_value = False),+ patch.object(stack_mod, "_has_rocm_gpu", return_value = True),+ patch.object(stack_mod, "_infer_linux_amd_gfx_arch", return_value = None),+ patch.object(stack_mod, "_detect_rocm_version", return_value = (7, 1)),+ patch.object(stack_mod, "_kfd_gfx_targets", return_value = []),+ patch.object(stack_mod, "_installed_rocm_wheel_family", return_value = None),+ patch.dict(os.environ, {"HIP_VISIBLE_DEVICES": "1"}, clear = False),+ _which_p,+ _allowed_p,+ ):+ with patch("os.path.isdir", return_value = True):+ with patch("subprocess.run", side_effect = _run):+ stack_mod._ensure_rocm_torch()+ calls = str(pip.call_args_list) + str(pip_try.call_args_list)+ assert _GENERIC in calls, calls+ assert _AMD not in calls, calls+++# ── the sources the runtime target falls back to ─────────────────────────────+++def test_kfd_topology_answers_when_neither_userland_probe_is_installed():+ """A runtime-only ROCm install ships no rocminfo and no amd-smi; the kernel's own+ topology still names the GPU, and _has_rocm_gpu() already reads that same sysfs."""+ calls = _run_install(gfx_devices = (), kfd = ("gfx1103",))+ assert f"{_AMD}/gfx110X-all/" in calls, calls+ assert _GENERIC not in calls, calls+++ "mask", ["HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"]+)[email protected]("value", ["", "-1"])[email protected]("probe", [(), ("gfx1103",)])+def test_a_mask_that_selects_no_gpu_takes_no_reroute(mask, value, probe):+ """An empty (or -1) visible-device mask selects NO GPU, whichever source answers.++ "" and "-1" are a deliberate choice of no device, and NO source here is filtered the+ way honouring that needs: only ROCR reaches rocminfo, amd-smi reads the driver, KFD+ sysfs. So a probe answering is no evidence the GPU is visible -- hence both the empty and+ populated probe, since CI exports an empty mask over a populated /sys/class/kfd. Generic+ torch still installs."""+ calls = _run_install(gfx_devices = probe, kfd = ("gfx1103",), env = {mask: value})+ assert f"{_AMD}/gfx110X-all/" not in calls, calls+ assert _GENERIC in calls, calls+++def test_a_mask_naming_a_device_still_reroutes():+ """The guard is only for a mask that selects nothing: one that names an ordinal leaves+ both the runtime-only and the probed host exactly as they were."""+ calls = _run_install(gfx_devices = (), kfd = ("gfx1103",), env = {"HIP_VISIBLE_DEVICES": "0"})+ assert f"{_AMD}/gfx110X-all/" in calls, calls+ calls = _run_install(gfx_devices = ("gfx1103",), env = {"HIP_VISIBLE_DEVICES": "0"})+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_a_live_probe_outranks_kfd_topology():+ """Only the userland probe is renumbered by a visible-device mask, so it leads."""+ calls = _run_install(gfx_devices = ("gfx1100",), kfd = ("gfx1103",))+ assert _GENERIC in calls, calls+ assert _AMD not in calls, calls+++def test_the_named_arch_repairs_a_host_no_probe_can_see():+ """UNSLOTH_ROCM_GFX_ARCH over a generic ROCm torch: the inferred-arch install is+ gated on there being no HIP torch, so without this fallback the named GPU keeps a+ wheel that has no kernels for it."""+ calls = _run_install(+ gfx_devices = (),+ kfd = (),+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1103"},+ torch_probe = _ROCM_GENERIC_TORCH,+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_a_probed_arch_still_wins_over_the_inferred_one():+ """The product-name fallback is last: a runtime that enumerates a GPU decides (#7305).+ That precedence is about the CPU-model guess, which is the half _infer_linux_amd_gfx_arch+ reaches only after the explicit variable, and the case below is the other half."""+ calls = _run_install(+ gfx_devices = ("gfx1100",),+ inferred = "gfx1103",+ torch_probe = _ROCM_GENERIC_TORCH,+ )+ assert _AMD not in calls, calls+++def test_an_explicit_arch_outranks_the_probe():+ """UNSLOTH_ROCM_GFX_ARCH is the documented escape hatch, and install.sh,+ _infer_linux_amd_gfx_arch, _runtime_target_is_gfx906 and _detect_windows_gfx_arch all read+ it before probing. Resolving it after the probes made this the one place the hardware+ could overrule the override."""+ calls = _run_install(+ gfx_devices = ("gfx1200",),+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1103"},+ torch_probe = _ROCM_GENERIC_TORCH,+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls+ # Hiding every GPU is a statement about this run, and still outranks the arch.+ assert _AMD not in _run_install(+ gfx_devices = ("gfx1200",),+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1103", "HIP_VISIBLE_DEVICES": ""},+ torch_probe = _ROCM_GENERIC_TORCH,+ )+++def test_the_inferred_arch_install_is_not_repeated_by_the_reroute():+ """#7305's inferred install resolves its index from the same arch the reroutes+ would, so running both force-reinstalls the multi-GB stack twice in one call."""+ calls = _run_install(+ gfx_devices = (),+ inferred = "gfx1151",+ rocm_gpu_visible = False,+ )+ assert calls.count("--index-url") == 1, calls+ assert f"{_AMD}/gfx1151/" in calls, calls+++# ── not re-downloading what is already installed ─────────────────────────────+++def test_torch_already_on_the_right_per_arch_wheels_is_not_reinstalled():+ """_ensure_rocm_torch runs twice per install and again on every update, and the+ reroute is a --force-reinstall --no-cache-dir of a multi-GB stack."""+ calls = _run_install(+ gfx_devices = ("gfx1103",),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert _AMD not in calls, calls+ assert _GENERIC not in calls, calls+ # Skipping the torch install must still leave rocm_torch_ready set, or the AMD+ # bitsandbytes repair every `studio update` exists for stops running too.+ assert "bitsandbytes" in calls, calls++[email protected]("family", [None, "gfx103x-all"])+def test_an_unknown_or_foreign_family_still_reinstalls(family):+ """Act only on a family read back positively, never on a guess."""+ calls = _run_install(+ gfx_devices = ("gfx1103",),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = family,+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_a_stale_runtime_beside_a_non_rocm_torch_does_not_veto_the_repair():+ """A rocm-sdk-libraries left behind by an earlier install names a family while the+ torch on disk is CPU-only; the repair must still run."""+ calls = _run_install(gfx_devices = ("gfx1103",), installed_family = "gfx110x-all")+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_a_leaf_that_needs_torch_211_keeps_its_floor():+ """An unreadable ROCm version reads as 0.0, which is below the Strix floor, so a+ gfx1152 host lands on this branch instead. Its leaf is one of the four whose <2.11+ builds carry the _grouped_mm bug, and the generic branch already floors those."""+ calls = _run_install(gfx_devices = ("gfx1152",), inferred = "gfx1152", rocm_version = None)+ assert f"{_AMD}/gfx1152/" in calls, calls+ assert "torch>=2.11.0,<2.12.0" in calls, calls+ assert "torch>=2.4,<2.12.0" not in calls, calls+++# ── the spoofed runtime the per-arch wheels cannot survive ───────────────────+++def test_a_kfd_only_spoofed_host_clears_the_override_before_installing():+ """With no rocminfo and no amd-smi the spoof check has nothing to distrust and declines,+ but amdkfd writes gfx_target_version itself, so a single-arch kernel reading the override+ contradicts IS the corroborated spoof. Left set, the gfx1151-only wheels get a device the+ runtime still calls gfx1100 (#7331)."""+ calls = _run_install(+ gfx_devices = (),+ kfd = ("gfx1151",),+ inferred = "gfx1151",+ env = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ )+ assert f"{_AMD}/gfx1151/" in calls, calls+ assert _run_install.hsa_override_after is None, _run_install.hsa_override_after+++def test_an_override_naming_the_real_arch_is_left_alone_on_the_kfd_path():+ """11.5.1 names gfx1151, which is what the kernel reports: nothing is being masked."""+ _run_install(+ gfx_devices = (),+ kfd = ("gfx1151",),+ inferred = "gfx1151",+ env = {"HSA_OVERRIDE_GFX_VERSION": "11.5.1"},+ )+ assert _run_install.hsa_override_after == "11.5.1"+++def test_a_mixed_kernel_reading_never_clears_the_override():+ """Two arches means the single-GPU premise the correction rests on does not hold."""+ _run_install(+ gfx_devices = (),+ kfd = ("gfx1151", "gfx1100"),+ inferred = "gfx1151",+ env = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ )+ assert _run_install.hsa_override_after == "11.0.0"+++# ── what the banners are allowed to print ────────────────────────────────────+++_SECRET_MIRROR = "https://user:[email protected]/whl"+++def test_the_missing_kernel_banner_redacts_mirror_credentials():+ """UNSLOTH_AMD_ROCM_MIRROR can carry userinfo, and installer output reaches CI logs."""+ calls = _run_install(gfx_devices = ("gfx1103",), env = {"UNSLOTH_AMD_ROCM_MIRROR": _SECRET_MIRROR})+ assert "mirror.example/whl/gfx110X-all/" in calls, calls+ assert "s3cr3t-token" not in _run_install.printed, _run_install.printed+++def test_the_strix_banner_redacts_mirror_credentials():+ """Same carrier, same banner rule: the reroute this one shares its variables with."""+ _run_install(+ gfx_devices = ("gfx1151",),+ inferred = "gfx1151",+ env = {"UNSLOTH_AMD_ROCM_MIRROR": _SECRET_MIRROR},+ )+ assert "s3cr3t-token" not in _run_install.printed, _run_install.printed+++# ── which card decides the family on a mixed host ────────────────────────────++[email protected]("apu", ["gfx1103", "gfx1036", "gfx1035", "gfx1033"])+def test_a_leading_integrated_gpu_does_not_pick_the_family(apu):+ """Enumeration order alone puts the APU first on a Ryzen box with a Radeon card. The+ family is chosen for ONE arch, so letting the APU decide strands the discrete card the+ generic index was serving. _SHADOWING_INTEGRATED_GFX is the existing policy (#7776)."""+ calls = _run_install(gfx_devices = (apu, "gfx1200"))+ assert _GENERIC in calls, calls+ assert _AMD not in calls, calls+++def test_the_discrete_card_still_decides_when_it_needs_the_amd_index():+ """Deposing the APU is about which card decides, not about avoiding the reroute."""+ calls = _run_install(gfx_devices = ("gfx1103", "gfx1032"))+ assert f"{_AMD}/gfx103X-all/" in calls, calls+++def test_a_visible_device_mask_still_wins_over_the_preference():+ """A pin is the user naming a device and is honoured verbatim, exactly as+ _visible_devices_pinned documents and _detect_windows_gfx_arch already behaves."""+ calls = _run_install(gfx_devices = ("gfx1103", "gfx1200"), env = {"HIP_VISIBLE_DEVICES": "0"})+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_a_lone_integrated_gpu_is_never_deposed():+ """Nothing else to run on, so the APU is the runtime target."""+ calls = _run_install(gfx_devices = ("gfx1103",))+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_an_all_integrated_host_is_never_deposed():+ """Every candidate is a shadowing APU, so there is no discrete card to prefer."""+ calls = _run_install(gfx_devices = ("gfx1103", "gfx1036"))+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++# ── building the index URL ───────────────────────────────────────────────────+++def test_the_leaf_lands_on_the_path_not_inside_a_mirror_token():+ """A mirror can carry its token in the query. rstrip + concat buried the arch inside+ it and left the request pointing at the bare mirror path."""+ assert (+ stack_mod._index_url_join("https://m.example/whl?token=x", "gfx110X-all")+ == "https://m.example/whl/gfx110X-all/?token=x"+ )+ assert (+ stack_mod._index_url_join("https://m.example/whl#frag", "gfx110X-all")+ == "https://m.example/whl/gfx110X-all/#frag"+ )+ assert (+ stack_mod._index_url_join("https://m.example/whl?a=1#f", "gfx1152")+ == "https://m.example/whl/gfx1152/?a=1#f"+ )+++def test_the_split_lands_on_whichever_delimiter_comes_first():+ """A fragment may itself contain "?". Reaching for "?" first then cuts inside the+ fragment, so the leaf is appended to a fragment and the request still asks for the bare+ path -- the same failure the query case above exists to prevent."""+ assert (+ stack_mod._index_url_join("https://m.example/whl#sha256=abc?download=1", "gfx110X-all")+ == "https://m.example/whl/gfx110X-all/#sha256=abc?download=1"+ )+++def test_a_plain_mirror_is_joined_exactly_as_before():+ for base in ("https://repo.amd.com/rocm/whl", "https://repo.amd.com/rocm/whl/"):+ assert (+ stack_mod._index_url_join(base, "gfx103X-all")+ == "https://repo.amd.com/rocm/whl/gfx103X-all/"+ )+++def test_a_query_mirror_reaches_the_arch_index_end_to_end():+ calls = _run_install(+ gfx_devices = ("gfx1103",),+ env = {"UNSLOTH_AMD_ROCM_MIRROR": "https://m.example/whl?token=x"},+ )+ assert "https://m.example/whl/gfx110X-all/?token=x" in calls, calls+++def test_every_strix_arch_has_a_leaf_in_the_shared_map():+ """Both reroutes now build their URL through _amd_arch_index_url, which returns None+ for an arch the map does not name; the Strix set must stay inside it."""+ for arch in ("gfx1150", "gfx1151", "gfx1152"):+ assert stack_mod._GFX_TO_AMD_INDEX_ARCH.get(arch) == arch, arch+++def test_a_generic_torch_beside_a_stale_rocm_meta_package_is_still_repaired():+ """Measured 2026-08-27: forcing generic rocm7.1 torch over a per-arch install leaves+ `rocm` and rocm-sdk-libraries-gfx110X-all behind, so the family still reads gfx110x-all+ while torch is 2.10.0+rocm7.1 with no gfx1103 kernels. torch.version.hip is set on both,+ so only torch's own requires separates them."""+ calls = _run_install(+ gfx_devices = ("gfx1103",),+ torch_probe = _ROCM_GENERIC_TORCH,+ installed_family = "gfx110x-all",+ torch_owns_rocm = False,+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++# Verbatim `metadata.requires("torch")` for both builds, read on an AMD DevLab host+# after installing generic rocm7.1 torch over an AMD gfx110X-all one.+_AMD_TORCH_REQUIRES = [+ "filelock",+ "typing-extensions>=4.10.0",+ "setuptools<82",+ "sympy>=1.13.3",+ "networkx>=2.5.1",+ "jinja2",+ "fsspec>=0.8.5",+ "rocm[libraries]==7.13.0",+ "triton==3.6.0+rocm7.13.0",+]+_GENERIC_TORCH_REQUIRES = [+ "filelock",+ "typing-extensions>=4.10.0",+ 'setuptools; python_version >= "3.12"',+ "sympy>=1.13.3",+ "networkx>=2.5.1",+ "jinja2",+ "fsspec>=0.8.5",+ 'triton-rocm==3.6.0; platform_system == "Linux"',+]+++ "requires, owns",+ [(_AMD_TORCH_REQUIRES, True), (_GENERIC_TORCH_REQUIRES, False), ([], False)],+)+def test_the_ownership_check_reads_torchs_own_requires(requires, owns):+ """Only AMD's torch declares `rocm[libraries]`. triton-rocm rides along on the generic+ ROCm build and rocm-sdk-core is a sibling distribution, so neither may match."""+ with patch("importlib.metadata.requires", return_value = requires):+ assert stack_mod._torch_requires_rocm_sdk() is owns+++def test_an_unroutable_discrete_card_does_not_depose_a_routable_apu():+ """gfx1010 (RDNA 1) is in neither the generic wheel nor the per-arch map, so no index+ can make it work. Handing it the decision trades a repairable 780M for nothing."""+ calls = _run_install(gfx_devices = ("gfx1103", "gfx1010"))+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_an_all_unroutable_host_keeps_enumeration_order():+ """Neither card has a route, so there is nothing to prefer and nothing to lose."""+ calls = _run_install(gfx_devices = ("gfx1013", "gfx1010"))+ assert _GENERIC in calls, calls+ assert _AMD not in calls, calls+++# ── a per-arch install outliving the GPU it was made for ─────────────────────+++def test_a_stale_per_arch_family_is_replaced_when_the_target_goes_generic():+ """An earlier gfx1103-only run installs gfx110X-all. Add a dGPU, or point+ HIP_VISIBLE_DEVICES at one, and those wheels carry no kernels for the new target,+ while torch.version.hip keeps rocm_torch_ready true and the fallback from running."""+ calls = _run_install(+ gfx_devices = ("gfx1200",),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert _GENERIC in calls, calls+++def test_a_target_inside_the_installed_family_is_left_alone():+ """gfx1101 is served by the same gfx110X-all build; nothing to repick."""+ calls = _run_install(+ gfx_devices = ("gfx1101",),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert _GENERIC not in calls, calls+ assert _AMD not in calls, calls+++def test_a_stale_family_is_replaced_by_the_right_per_arch_index_too():+ calls = _run_install(+ gfx_devices = ("gfx1032",),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert f"{_AMD}/gfx103X-all/" in calls, calls++[email protected]("family, owns", [(None, True), ("gfx110x-all", False)])+def test_an_unreadable_family_never_forces_a_reinstall(family, owns):+ """None is "unknowable" and a torch that does not own `rocm` is not a per-arch install;+ neither may churn a working venv."""+ calls = _run_install(+ gfx_devices = ("gfx1200",),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = family,+ torch_owns_rocm = owns,+ )+ assert _GENERIC not in calls, calls+ assert _AMD not in calls, calls+++# ── the three host shapes the reroutes reach only once a second signal is missing ──++_ROCM_ARCH_TORCH_210 = stack_mod._TORCH_PROBE_MARKER + "2.10.0+rocm7.13.0|7.13|\n"+++def test_a_gfx906_dgpu_never_deposes_a_routable_apu():+ """gfx906's only route fires solely when it is the ONE detected arch, so naming it the+ target on a mixed host installs a rocm7.x wheel whose BLAS has no gfx906 kernels and+ strands both cards. The APU keeps the selection; gfx906 keeps its env opt-in."""+ calls = _run_install(gfx_devices = ("gfx1103", "gfx906"))+ assert f"{_AMD}/gfx110X-all/" in calls, calls+ assert "rocm6.3" not in calls and _GENERIC not in calls, calls+ # Alone it still takes the legacy route, so the exclusion is scoped to the mixed host.+ assert "rocm6.3" in _run_install(gfx_devices = ("gfx906",), rocm_version = (7, 1))+++def test_a_sub_211_build_of_the_right_family_is_still_repaired():+ """A matching family is the right SHAPE, not a working build: on the 2.11-floor leaves a+ sub-2.11 wheel carries the _grouped_mm bug. An unreadable ROCm version routes gfx1152+ through the missing-kernel branch, so this is the only floor such a host meets."""+ calls = _run_install(+ gfx_devices = ("gfx1152",),+ inferred = "gfx1152",+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH_210,+ installed_family = "gfx1152",+ )+ assert f"{_AMD}/gfx1152/" in calls and "torch>=2.11.0,<2.12.0" in calls, calls+++def test_at_the_floor_the_matching_family_is_still_skipped():+ """The other half of the same gate: at or above 2.11 the family match still wins, so an+ up-to-date host does not re-download the multi-GB stack on every update."""+ calls = _run_install(+ gfx_devices = ("gfx1152",),+ inferred = "gfx1152",+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx1152",+ )+ assert f"{_AMD}/gfx1152/" not in calls, calls+ assert "torch already runs on the gfx1152 wheels" in _run_install.printed+++def test_a_stale_family_is_repaired_when_no_generic_tag_resolves():+ """Demoting hands the job to the generic fallback, which resolves no tag at all when the+ ROCm version is unreadable -- the shape of a bundled-runtime host. The branch announced a+ reinstall, installed nothing, and kept the family it just called incompatible."""+ calls = _run_install(+ gfx_devices = ("gfx1200",),+ inferred = "gfx1200",+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert f"{_AMD}/gfx120X-all/" in calls, calls+++# ── the routes a second, independent reading has to survive ───────────────────++[email protected]("probe", [(), ("gfx1103",)])+def test_an_unreadable_rocm_version_still_routes_a_missing_kernel_arch(probe):+ """A bundled-runtime host has no /opt/rocm version to read, and the missing-kernel+ reroute has no version floor anyway: whichever index a version would pick ships no kernels+ for these arches. Returning early leaves the GPU on a wheel that faults."""+ calls = _run_install(+ gfx_devices = probe,+ kfd = ("gfx1103",),+ rocm_version = None,+ inferred = None,+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls++[email protected]("mask", ["", "-1"])+def test_an_empty_rocr_mask_under_a_named_hip_mask_still_selects_no_gpu(mask):+ """ROCr filters BENEATH HIP, so the masks intersect: HIP naming device 0 over a ROCr mask+ exposing nothing leaves nothing to target. Checking only the first mask that is set+ reinstalls a multi-GB stack for a GPU the user hid."""+ calls = _run_install(+ gfx_devices = ("gfx1103",),+ env = {"HIP_VISIBLE_DEVICES": "0", "ROCR_VISIBLE_DEVICES": mask},+ )+ assert _AMD not in calls, calls+ # A mask that does name a device is untouched, so the guard is scoped to a hidden GPU.+ assert f"{_AMD}/gfx110X-all/" in _run_install(+ gfx_devices = ("gfx1103",),+ env = {"HIP_VISIBLE_DEVICES": "0"},+ )+++def test_keeping_the_matching_wheels_also_clears_a_confirmed_spoof():+ """Keeping the wheels is not keeping the status quo. They carry the PHYSICAL arch alone,+ so a confirmed spoof left set has ROCr keep naming the one arch they have no code for+ (#7331). The reinstall arm clears it for that reason; the skip arm needs it as much."""+ calls = _run_install(+ gfx_devices = ("gfx1100",),+ inferred = "gfx1152",+ kfd = ("gfx1152",),+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx1152",+ env = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ )+ assert f"{_AMD}/gfx1152/" not in calls, calls+ assert "torch already runs on the gfx1152 wheels" in _run_install.printed+ assert _run_install.hsa_override_after is None, _run_install.hsa_override_after+++# ── the two mask layers, and the install they outlive ────────────────────────+++def test_the_rocr_layer_is_applied_before_the_hip_index_on_an_unfiltered_list():+ """ROCr is processed first and HIP indexes the SURVIVORS, so HIP's index is relative to+ what ROCr left. Neither amd-smi (driver) nor KFD sysfs (kernel) is ROCr-filtered:+ resolving HIP against those lists names a GPU the runtime does not expose, and installs+ per-arch wheels that fault on first use."""+ calls = _run_install(+ gfx_devices = ("gfx1200", "gfx1103"),+ env = {"ROCR_VISIBLE_DEVICES": "1", "HIP_VISIBLE_DEVICES": "0"},+ )+ # ROCr leaves [gfx1103]; HIP index 0 is therefore the gfx1103, not the gfx1200.+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_a_rocr_filtered_probe_is_not_filtered_a_second_time():+ """rocminfo is the one probe ROCr renumbers, and it is renumbered whenever the mask is+ set -- not only when it happens to be the first mask set. Applying the mask again to a+ list it already shaped would index the survivors by a position in the original."""+ with (+ patch.object(stack_mod, "_detect_amd_gfx_codes", return_value = ["gfx1103"]),+ patch.object(stack_mod, "_kfd_gfx_targets", return_value = [], create = True),+ patch.object(stack_mod, "_LAST_AMD_GFX_PROBE", "rocminfo"),+ patch.dict(+ os.environ,+ {"ROCR_VISIBLE_DEVICES": "1", "HIP_VISIBLE_DEVICES": "0"},+ clear = False,+ ),+ ):+ assert stack_mod._runtime_gfx_target(None)[0] == "gfx1103"+++def test_a_uuid_rocr_mask_on_one_architecture_still_routes():+ """ROCR_VISIBLE_DEVICES also takes GPU UUIDs, and may mix them with indices. A UUID+ names no position in a probe reporting arches, but on a host of one architecture it+ cannot change which arch is selected, so the reroute proceeds."""+ calls = _run_install(+ gfx_devices = ("gfx1103", "gfx1103"),+ env = {"ROCR_VISIBLE_DEVICES": "GPU-8d1f2e3a4b5c6d7e"},+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_an_unmappable_uuid_declines_the_reroute_on_a_mixed_host():+ """On a mixed host the UUID decides everything and nothing here can read it. The reroute+ installs wheels for ONE arch, so picking the first entry may serve the GPU the mask hid+ and leave the selected card with no kernels at all."""+ calls = _run_install(+ gfx_devices = ("gfx1103", "gfx1200"),+ env = {"ROCR_VISIBLE_DEVICES": "GPU-8d1f2e3a4b5c6d7e"},+ )+ assert _AMD not in calls, calls+ assert "names a GPU by UUID" in _run_install.printed, _run_install.printed+ # UNSLOTH_ROCM_GFX_ARCH is the documented way through, and the message says so.+ assert f"{_AMD}/gfx110X-all/" in _run_install(+ gfx_devices = ("gfx1103", "gfx1200"),+ env = {"ROCR_VISIBLE_DEVICES": "GPU-8d1f2e3a4b5c6d7e", "UNSLOTH_ROCM_GFX_ARCH": "gfx1103"},+ )+++def test_a_stale_per_arch_family_is_repaired_even_when_the_rocm_version_is_unreadable():+ """A per-arch install outlives the GPU it was made for: swap a gfx1200 card into a box on+ gfx110X-all wheels and the generic index would serve it, so the unreadable-version exit+ stands and the stale-family repair never runs on wheels with no gfx1200 kernels."""+ calls = _run_install(+ gfx_devices = ("gfx1200",),+ inferred = None,+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert f"{_AMD}/gfx120X-all/" in calls, calls+ # A family that already matches still takes the exit, so an up-to-date host is untouched.+ _run_install(+ gfx_devices = ("gfx1200",),+ inferred = None,+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx120x-all",+ )+ assert "skipping torch reinstall" in _run_install.printed, _run_install.printed+++# ── two orders, and the mask that cannot be applied to either ────────────────+++def _target(+ gfx_devices,+ probe_source,+ env,+ kfd = (),+):+ """Resolve the runtime target with ``probe_source`` named as the probe that answered.++ ``kfd`` is the kernel topology, empty by default: an unreadable /sys/class/kfd leaves+ only the probe's own ordering to go on."""+ with (+ patch.object(stack_mod, "_detect_amd_gfx_codes", return_value = list(gfx_devices)),+ patch.object(stack_mod, "_kfd_gfx_targets", return_value = list(kfd), create = True),+ patch.object(stack_mod, "_LAST_AMD_GFX_PROBE", probe_source),+ patch.dict(os.environ, env, clear = False),+ ):+ for _stale in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ if _stale not in env:+ os.environ.pop(_stale, None)+ return stack_mod._runtime_gfx_target(None)[0]+++def test_a_mask_mixing_an_index_and_a_uuid_keeps_the_host_ambiguous():+ """AMD documents "0,GPU-DEADBEEFDEADBEEF" as a valid mask. Judging ambiguity on the list+ left AFTER the resolvable tokens were applied can leave one arch standing and hide the+ very ambiguity the UUID created, so the question has to be asked of the original."""+ assert (+ _target(+ ["gfx1103", "gfx1200"],+ "amd-smi",+ {"ROCR_VISIBLE_DEVICES": "0,GPU-8d1f2e3a4b5c6d7e", "HIP_VISIBLE_DEVICES": "1"},+ )+ is None+ )+ # One arch cannot be made ambiguous by any mask over it.+ assert (+ _target(+ ["gfx1103", "gfx1103"],+ "kfd",+ {"ROCR_VISIBLE_DEVICES": "0,GPU-8d1f2e3a4b5c6d7e"},+ )+ == "gfx1103"+ )+++def test_amd_smi_discovery_order_is_not_indexed_as_hip_order():+ """amd-smi enumerates in discovery order while the masks index HIP order, derived from+ the KFD node id. setup.sh translates through `amd-smi list -e`'s HIP_ID map and refuses a+ mask when it is missing or not 1:1; no map is read here, so on unlike adapters an+ untranslated ordinal names another card's arch. No KFD topology either, so the ordering+ the next test substitutes is unavailable."""+ assert _target(["gfx1103", "gfx1200"], "amd-smi", {"HIP_VISIBLE_DEVICES": "1"}) is None+ # rocminfo and KFD sysfs are already in the order the masks use.+ assert _target(["gfx1103", "gfx1200"], "kfd", {"HIP_VISIBLE_DEVICES": "1"}) == "gfx1200"+ # Nothing to mistranslate: like adapters give the same arch at every ordinal.+ assert _target(["gfx1200", "gfx1200"], "amd-smi", {"HIP_VISIBLE_DEVICES": "1"}) == "gfx1200"+ # An unset mask is not safety: the runtime still opens HIP ordinal 0, and discovery-order+ # 0 can be the other card. setup.sh declines unlike adapters with no HIP map whether or+ # not a mask is set, and this has to read the host the same way.+ assert _target(["gfx1103", "gfx1200"], "amd-smi", {}) is None+++def test_kfd_order_resolves_a_mask_amd_smi_order_cannot():+ """KFD nodes ARE the order the masks index, which is why the fallback above reads them+ when no userland probe answers. Declining an ordering this file already solves leaves a+ Ryzen APU-plus-dGPU box -- the reported shape -- on a wheel it has no kernels for."""+ assert (+ _target(+ ["gfx1200", "gfx1103"],+ "amd-smi",+ {"HIP_VISIBLE_DEVICES": "0"},+ kfd = ["gfx1103", "gfx1200"],+ )+ == "gfx1103"+ )+ # A KFD list of another length is a different view of the machine, not a translation of+ # this one, so the ordinal still has nothing trustworthy to index.+ assert (+ _target(+ ["gfx1200", "gfx1103"],+ "amd-smi",+ {"HIP_VISIBLE_DEVICES": "0"},+ kfd = ["gfx1103", "gfx1200", "gfx1200"],+ )+ is None+ )+ # A UUID names a device no source can place, so KFD does not rescue that one.+ assert (+ _target(+ ["gfx1200", "gfx1103"],+ "amd-smi",+ {"ROCR_VISIBLE_DEVICES": "GPU-8d1f2e3a4b5c6d7e"},+ kfd = ["gfx1103", "gfx1200"],+ )+ is None+ )+++def test_an_explicit_arch_is_authoritative_for_the_repair_gate_too():+ """Stacked masks can leave a device list the override is not in: ROCr keeps the gfx1200,+ the user names the gfx1103. The caller reads that set to decide which arch lacks kernels,+ so a target missing from it is selected and then never repaired."""+ calls = _run_install(+ gfx_devices = ("gfx1200", "gfx1103"),+ probe_source = "amd-smi",+ env = {+ "ROCR_VISIBLE_DEVICES": "0",+ "HIP_VISIBLE_DEVICES": "0",+ "UNSLOTH_ROCM_GFX_ARCH": "gfx1103",+ },+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_a_generic_wheel_is_judged_by_its_own_rocm_tag():+ """Which arches a generic wheel carries belongs to THAT wheel. Pin rocm6.3 once, or+ upgrade /opt/rocm afterwards, and a gfx1200 box runs a 2.9.1+rocm6.3 build with no kernels+ for it while the host reads 7.2 -- judged by the host, it looks healthy forever."""+ calls = _run_install(+ gfx_devices = ("gfx1200",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_GENERIC_TORCH_63,+ torch_owns_rocm = False,+ )+ assert f"{_AMD}/gfx120X-all/" in calls, calls+ # The wheel that does carry it is left alone, whatever the host version reads.+ assert _AMD not in _run_install(+ gfx_devices = ("gfx1200",),+ rocm_version = (6, 3),+ torch_probe = _ROCM_GENERIC_TORCH_72,+ torch_owns_rocm = False,+ )+++def test_a_named_arch_resolves_an_ordering_no_probe_can():+ """UNSLOTH_ROCM_GFX_ARCH is what the decline message tells the user to set, so it has to+ resolve the host it is offered for. Read from the environment, not the product-name+ inference, which is weaker than the probe and must not decide a host it left open."""+ assert (+ _target(+ ["gfx1103", "gfx1200"],+ "amd-smi",+ {"HIP_VISIBLE_DEVICES": "1", "UNSLOTH_ROCM_GFX_ARCH": "gfx1103"},+ )+ == "gfx1103"+ )+ assert _target(["gfx1103", "gfx1200"], "amd-smi", {"HIP_VISIBLE_DEVICES": "1"}) is None+++ "gfx, leaf",+ [+ ("gfx1200", "gfx120X-all"), # RDNA 4, and the generic wheel lists it+ ("gfx1151", "gfx1151"), # Strix Halo, reached here when the version is unreadable+ ],+)+def test_the_torch_floor_applies_to_the_family_not_to_the_missing_kernel_gate(gfx, leaf):+ """Several floor leaves serve GPUs the generic wheel DOES carry kernels for, so gating the+ 2.11 floor on missing kernels never reaches them: the preflight forces the dependency pass+ and this branch then declines it, and the _grouped_mm bug survives every update."""+ calls = _run_install(+ gfx_devices = (gfx,),+ inferred = None,+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH_210,+ installed_family = leaf.lower(),+ )+ assert f"{_AMD}/{leaf}/" in calls, calls+ assert "torch>=2.11.0,<2.12.0" in calls, calls+ # At the floor the same host keeps its wheels, so this is the floor and not a reinstall loop.+ assert f"{_AMD}/{leaf}/" not in _run_install(+ gfx_devices = (gfx,),+ inferred = None,+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = leaf.lower(),+ )++[email protected]("gfx", ["gfx942", "gfx950"])+def test_a_generic_only_replacement_gpu_still_gets_a_wheel(gfx):+ """The datacentre parts live only on the generic index, so a stale per-arch install that+ outlives its GPU has no AMD leaf to be repaired onto. With no readable host version there+ is no tag either, so the branch announced the reinstall and installed nothing."""+ calls = _run_install(+ gfx_devices = (gfx,),+ inferred = None,+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert _GENERIC in calls, calls+ assert "carries no" in _run_install.printed, _run_install.printed+++def test_a_rocr_mask_index_out_of_range_keeps_todays_fallback():+ """_pick_visible_index warns and falls back to GPU 0 for an out-of-range index, matching+ setup.ps1's Resolve-VisibleGpuIndex. A stricter rule here would split the two and withdraw+ the repair from single-GPU hosts: ROCR_VISIBLE_DEVICES=1 on a one-GPU box is a typo."""+ assert _target(["gfx1103"], "kfd", {"ROCR_VISIBLE_DEVICES": "1"}) == "gfx1103"+ assert _target(["gfx1103"], "kfd", {"ROCR_VISIBLE_DEVICES": "0,9"}) == "gfx1103"+ assert _target(["gfx1103", "gfx1200"], "kfd", {"ROCR_VISIBLE_DEVICES": "1"}) == "gfx1200"+++def test_a_target_no_index_can_serve_is_not_worth_a_reinstall():+ """gfx1010 is in neither the generic wheel nor the AMD leaf map, so an empty leaf reads as+ "every family is wrong" and spends a multi-GB reinstall on a wheel that cannot carry+ kernels for it either. Demote only when there is somewhere to go."""+ calls = _run_install(+ gfx_devices = ("gfx1010",),+ inferred = None,+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert _GENERIC not in calls and _AMD not in calls, calls+ # A target the generic wheel does carry is still repaired, so the guard is scoped.+ assert _GENERIC in _run_install(+ gfx_devices = ("gfx942",),+ inferred = None,+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )++[email protected]("gfx", ["gfx1200", "gfx1201"])+ "rocm_version, rerouted",+ [((6, 0), True), ((6, 3), True), ((6, 4), False), ((7, 1), False)],+)+def test_generic_kernel_support_is_keyed_by_the_tag_the_version_selects(+ gfx, rocm_version, rerouted+):+ """Which arches the generic wheel carries belongs to the wheel a version resolves to, not+ the index as a whole. AMD puts production RDNA 4 at ROCm 6.4, so a current amdgpu beside a+ stale /opt/rocm gets a rocm6.3 wheel with no kernels while a gfx120X-all leaf exists."""+ calls = _run_install(gfx_devices = (gfx,), rocm_version = rocm_version)+ if rerouted:+ assert f"{_AMD}/gfx120X-all/" in calls, calls+ else:+ assert _AMD not in calls and _GENERIC in calls, calls++[email protected]("rocm_version", [(6, 0), (7, 1)])+def test_an_arch_with_no_recorded_minimum_is_unaffected_by_the_version(rocm_version):+ """The measurement covers rocm7.x; only arches known to postdate an older tag are keyed by+ it, so everything else keeps the union reading and the generic index it always had."""+ calls = _run_install(gfx_devices = ("gfx1100",), rocm_version = rocm_version)+ assert _AMD not in calls and _GENERIC in calls, calls++[email protected]("gfx", ["gfx1150", "gfx1151"])+def test_strix_on_an_old_generic_wheel_is_rerouted_without_a_host_version(gfx):+ """The Strix arm is gated on a ROCm VERSION, and an unreadable one reads as 0.0, so it+ never runs on a bundled-runtime host. The rocm6.3 wheel carries no gfx1150/gfx1151 (AMD+ dates support to 7.1), so omitting them from the version map keeps a build that faults."""+ calls = _run_install(+ gfx_devices = (gfx,),+ rocm_version = None,+ torch_probe = _ROCM_GENERIC_TORCH_63,+ torch_owns_rocm = False,+ )+ assert f"{_AMD}/{gfx}/" in calls, calls+ # Only the build the reroute would fetch is left alone: a generic rocm7.2 wheel does+ # carry these arches, but Strix wants AMD's 7.13 fixes over any index below the floor.+ assert _AMD not in _run_install(+ gfx_devices = (gfx,),+ rocm_version = None,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = gfx,+ )+++def test_a_masked_gfx906_on_a_mixed_host_is_not_demoted_to_another_dead_wheel():+ """gfx906's only route is the rocm6.3 tag, unlocked only when it is the ONE detected+ arch. A mask can still select the MI50 on a mixed host, and every tag above rocm6.3+ dropped its BLAS kernels, so demoting there buys a second unusable torch."""+ calls = _run_install(+ gfx_devices = ("gfx1100", "gfx906"),+ env = {"HIP_VISIBLE_DEVICES": "1"},+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert "reinstalling for this GPU" not in _run_install.printed, _run_install.printed+ assert _GENERIC not in calls, calls+ # The same stale family with a routable target is still demoted.+ _run_install(+ gfx_devices = ("gfx1100", "gfx1200"),+ env = {"HIP_VISIBLE_DEVICES": "1"},+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert "reinstalling for this GPU" in _run_install.printed, _run_install.printed+++ "env",+ [+ {"HIP_VISIBLE_DEVICES": "1"},+ {"CUDA_VISIBLE_DEVICES": "2"},+ ],+)+def test_an_ordinal_past_an_inferred_arch_resolves_nothing(env):+ """One guess about the machine is not a device list, so an ordinal past its only entry+ indexes nothing: the mask names a GPU the guess cannot account for, and the out-of-range+ rule would answer with the guess anyway, then reinstall per-arch wheels for it."""+ calls = _run_install(+ gfx_devices = (),+ kfd = (),+ inferred = "gfx1103",+ rocm_gpu_visible = False,+ env = env,+ )+ assert _AMD not in calls, calls+ assert "past the only architecture" in _run_install.printed, _run_install.printed+++ "env",+ [+ {},+ {"HIP_VISIBLE_DEVICES": "0"},+ {"ROCR_VISIBLE_DEVICES": "1"},+ ],+)+def test_an_inferred_arch_still_installs_where_no_ordinal_contradicts_it(env):+ """Only the contradiction declines. No mask and index 0 agree with the guess, and an+ out-of-range ROCr index keeps the fallback the ROCr layer already documents."""+ calls = _run_install(+ gfx_devices = (),+ kfd = (),+ inferred = "gfx1103",+ rocm_gpu_visible = False,+ env = env,+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++def test_a_named_arch_outranks_an_ordinal_the_inference_cannot_place():+ """UNSLOTH_ROCM_GFX_ARCH is the user answering the question the ordinal left open, and+ the decline message says to set it, so it has to be honoured here too."""+ calls = _run_install(+ gfx_devices = (),+ kfd = (),+ inferred = "gfx1103",+ rocm_gpu_visible = False,+ env = {"HIP_VISIBLE_DEVICES": "1", "UNSLOTH_ROCM_GFX_ARCH": "gfx1103"},+ )+ assert f"{_AMD}/gfx110X-all/" in calls, calls+++ "env",+ [+ {"ROCR_VISIBLE_DEVICES": "1"},+ {"HIP_VISIBLE_DEVICES": "1"},+ ],+)+def test_a_masked_gfx906_is_judged_by_the_host_the_legacy_route_probes(env):+ """ROCr filters the list this function sees, so a physically mixed host arrives as a lone+ gfx906 while _runtime_target_is_gfx906 re-probes the machine and declines the rocm6.3 tag.+ Deriving "is it alone" twice lets the two disagree, and the demotion then installs a newer+ wheel whose BLAS has no gfx906 kernels."""+ calls = _run_install(+ gfx_devices = ("gfx1100", "gfx906"),+ env = env,+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert "reinstalling for this GPU" not in _run_install.printed, _run_install.printed+ assert _GENERIC not in calls, calls++[email protected]("gfx", ["gfx1150", "gfx1151"])+def test_a_strix_host_with_no_readable_version_still_gets_rocm_torch(gfx):+ """An unreadable version reads as 0.0, so the Strix arm sat out and the missing-kernel+ fallback declined too (these arches are in the generic list). The generic branch had no+ tag either, so a visible Strix host was left on CPU torch permanently."""+ calls = _run_install(+ gfx_devices = (gfx,),+ rocm_version = None,+ torch_owns_rocm = False,+ )+ assert f"{_AMD}/{gfx}/" in calls, calls+++def test_the_strix_reroute_keeps_the_wheels_it_would_have_fetched():+ """The branch force-reinstalls a multi-GB stack and _ensure_rocm_torch runs twice per+ install, so acting on the arch alone re-downloads it every time."""+ calls = _run_install(+ gfx_devices = ("gfx1151",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx1151",+ )+ assert _AMD not in calls, calls+ assert "keeping it" in _run_install.printed, _run_install.printed+++def test_an_explicit_arch_keeps_its_feature_suffix_out_of_the_target():+ """rocminfo and HSA spell a target with its feature flags (gfx1151:sramecc-:xnack-), so a+ user copying one into UNSLOTH_ROCM_GFX_ARCH offers a string every lookup misses: the Strix+ set, the AMD leaf map and the generic list are keyed on the bare arch, so the one thing+ the decline message tells the user to set would resolve nothing."""+ assert _target([], "rocminfo", {"UNSLOTH_ROCM_GFX_ARCH": "gfx1151:sramecc-:xnack-"}) == (+ "gfx1151"+ )+ calls = _run_install(+ gfx_devices = (),+ rocm_version = (7, 2),+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1151:xnack-"},+ torch_probe = _ROCM_GENERIC_TORCH,+ torch_owns_rocm = False,+ )+ assert f"{_AMD}/gfx1151/" in calls, calls+++def test_a_version_below_every_index_is_not_read_as_support():+ """A ROCm older than the oldest tag this installer maps resolves no tag at all, and a+ wheel older than every tag predates the arches those tags were measured to add. Reading+ "no tag" as "carries it" preserves exactly the build that cannot run."""+ assert stack_mod._generic_rocm_wheel_lacks_kernels("gfx1200", (5, 7))+ assert stack_mod._generic_rocm_wheel_lacks_kernels("gfx1200", (6, 3))+ assert not stack_mod._generic_rocm_wheel_lacks_kernels("gfx1200", (6, 4))+++def test_a_stale_host_version_does_not_pick_a_generic_tag_without_the_target():+ """gfx950 (MI350X) lives only on the generic index, so the repair picks a TAG rather than+ an index -- and a stale /opt/rocm beside a current kernel offers rocm6.3, which predates+ the part. The reinstall would download multiple GB and land on a wheel with no kernels."""+ calls = _run_install(+ gfx_devices = ("gfx950",),+ rocm_version = (6, 3),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+ assert f"{_GENERIC}7.2" in calls, calls+ # A version whose tag does carry the target still takes that tag, not the newest one.+ assert f"{_GENERIC}7.0" in _run_install(+ gfx_devices = ("gfx950",),+ rocm_version = (7, 0),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ )+++ "mask", ["HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"]+)[email protected]("value", ["", "-1"])+def test_a_mask_that_selects_no_gpu_takes_no_gfx906_reroute_either(mask, value):+ """The legacy route is a harsher version of what the guard above declines: a+ force-reinstall onto an OLDER tag, plus the loss of bitsandbytes. Its detection asks+ whether gfx906 is the sole arch, which no mask filters, so a CI job hiding every GPU over+ a populated host was downgraded while the same job on any other arch was not."""+ calls = _run_install(gfx_devices = ("gfx906",), rocm_version = (7, 2), env = {mask: value})+ assert "rocm6.3" not in calls, calls+ assert f"{_GENERIC}7.2" in calls, calls+ assert "bitsandbytes" in calls, calls+ # A mask naming a device is untouched: the legacy route and the bnb skip both still fire.+ _named = _run_install(gfx_devices = ("gfx906",), rocm_version = (7, 2), env = {mask: "0"})+ assert f"{_GENERIC}6.3" in _named, _named+ # The mask sits above UNSLOTH_ROCM_GFX_ARCH here too, as it does in _runtime_gfx_target:+ # hiding every GPU is a statement about this run, and the arch is read below it.+ _pinned = _run_install(+ gfx_devices = (),+ rocm_version = (7, 2),+ env = {mask: value, "UNSLOTH_ROCM_GFX_ARCH": "gfx906"},+ )+ assert "rocm6.3" not in _pinned, _pinned+++def test_an_explicit_arch_still_reconciles_a_contradicting_spoof():+ """UNSLOTH_ROCM_GFX_ARCH returns before the spoof detection runs, and+ HSA_OVERRIDE_GFX_VERSION=11.0.0 is the workaround half these hosts carry from before+ per-arch wheels existed. Naming the physical arch bought the right wheels and left ROCr+ handing torch a gfx1100 agent none of them match: #7331 with the fix downloaded."""+ calls = _run_install(+ gfx_devices = (),+ kfd = ("gfx1151",),+ inferred = "gfx1151",+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1151", "HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ )+ assert f"{_AMD}/gfx1151/" in calls, calls+ assert _run_install.hsa_override_after is None, _run_install.hsa_override_after+++def test_an_explicit_arch_reconciles_the_spoof_on_the_reroute_path_too():+ """The same host with ROCm torch installed takes the Strix reroute instead, reaching the+ clear through _runtime_gfx_target's third return value. Both paths install gfx1151-only+ wheels, so both have to answer the override."""+ calls = _run_install(+ gfx_devices = (),+ kfd = ("gfx1151",),+ inferred = "gfx1151",+ rocm_version = (7, 2),+ torch_probe = _ROCM_GENERIC_TORCH,+ torch_owns_rocm = False,+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1151", "HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ )+ assert f"{_AMD}/gfx1151/" in calls, calls+ assert _run_install.hsa_override_after is None, _run_install.hsa_override_after+++def test_an_arch_naming_what_the_override_spoofs_to_keeps_the_spoof():+ """Setting both to gfx1100 is a deliberate pairing -- run this card as an RDNA 3 dGPU --+ not a leftover. Clearing it would strand the wheels the user just asked for."""+ _run_install(+ gfx_devices = (),+ kfd = ("gfx1103",),+ inferred = "gfx1103",+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1100", "HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ )+ assert _run_install.hsa_override_after == "11.0.0"+++def test_a_repin_between_per_arch_leaves_is_applied():+ """Swap the card, edit UNSLOTH_TORCH_INDEX_URL to the new leaf, and every shape the+ version string carries stays put: gfx1151 and gfx120X-all are both torch 2.11 with a+ three-part +rocm7.13.0 tag. Judged on that alone the edited pin reads as satisfied, so the+ old wheels survive the update in silence."""+ calls = _run_install(+ gfx_devices = ("gfx1200",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ env = {"UNSLOTH_TORCH_INDEX_URL": f"https://{_AMD}/gfx120X-all/"},+ )+ assert f"{_AMD}/gfx120X-all" in calls, calls+ # A pin naming the family already installed is still not a reinstall: this runs on every+ # update and the stack is multi-GB.+ assert _AMD not in _run_install(+ gfx_devices = ("gfx1200",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx120x-all",+ env = {"UNSLOTH_TORCH_INDEX_URL": f"https://{_AMD}/gfx120X-all/"},+ )+++def test_a_pin_at_a_non_floor_leaf_keeps_the_build_from_that_leaf():+ """The version heuristic reads any 2.11 build as a mismatch, because that is what a build+ from some OTHER index looks like. The leaf serves 2.11 too, so a correctly pinned host+ force-reinstalled under the legacy torch<2.11 cap on every update. A readable family says+ which index the build came from, and is decisive both ways."""+ assert _AMD not in _run_install(+ gfx_devices = ("gfx1100",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ env = {"UNSLOTH_TORCH_INDEX_URL": f"https://{_AMD}/gfx110X-all/"},+ )+ # The other family under the same pin is still repinned.+ assert f"{_AMD}/gfx110X-all" in _run_install(+ gfx_devices = ("gfx1100",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx120x-all",+ env = {"UNSLOTH_TORCH_INDEX_URL": f"https://{_AMD}/gfx110X-all/"},+ )+++def test_a_floor_leaf_still_repairs_a_sub_211_build_of_its_own_family():+ """gfx1151 and the other floor leaves carry the _grouped_mm bug below torch 2.11, which is+ the one thing their pin has to keep repairing, so a matching family must NOT satisfy it."""+ assert f"{_AMD}/gfx1151" in _run_install(+ gfx_devices = ("gfx1151",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_ARCH_TORCH_210,+ installed_family = "gfx1151",+ env = {"UNSLOTH_TORCH_INDEX_URL": f"https://{_AMD}/gfx1151/"},+ )+++def test_a_generic_only_target_gets_its_tag_floor_on_a_fresh_install_too():+ """gfx950 has no AMD per-arch leaf, so the only way to give it kernels is a generic tag+ that carries it (rocm7.0+). That floor was applied solely to a host already on ROCm wheels+ that had to be demoted, so a fresh install or a CPU/CUDA torch walked past it and a stale+ /opt/rocm put the card on rocm6.3. Which tag carries an arch is a fact about the arch."""+ for _probe in (_CPU_TORCH, None):+ calls = _run_install(+ gfx_devices = ("gfx950",),+ rocm_version = (6, 3),+ torch_probe = _probe,+ torch_owns_rocm = False,+ )+ assert f"{_GENERIC}7.2" in calls, calls+ # A host version whose tag does carry the target keeps that tag, not the newest one.+ assert f"{_GENERIC}7.0" in _run_install(+ gfx_devices = ("gfx950",),+ rocm_version = (7, 0),+ torch_probe = _CPU_TORCH,+ torch_owns_rocm = False,+ )+ # An arch the generic wheel serves at every tag is untouched: no floor to apply.+ assert f"{_GENERIC}6.3" in _run_install(+ gfx_devices = ("gfx1100",),+ rocm_version = (6, 3),+ torch_probe = _CPU_TORCH,+ torch_owns_rocm = False,+ )+++def test_matching_per_arch_wheels_clear_a_confirmed_spoof_with_nothing_to_reroute():+ """The spoof clear lived inside the missing-kernel / below-floor branch, so a host whose+ per-arch wheels ALREADY match reached no arm at all -- exactly when the wheels are right+ and the spoof is the only thing wrong. They carry the physical arch alone, so the runtime+ keeps asking them for code they do not have (#7331)."""+ calls = _run_install(+ gfx_devices = ("gfx1100",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_ARCH_TORCH,+ installed_family = "gfx110x-all",+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1100", "HSA_OVERRIDE_GFX_VERSION": "10.3.0"},+ )+ assert _run_install.hsa_override_after is None, _run_install.hsa_override_after+ # Clearing it is not a licence to reinstall: the wheels were already the right ones.+ assert "torch" not in calls, calls+++def test_a_spoof_survives_wheels_that_are_not_the_targets_family():+ """The clear above is owned by a family read back positively from a torch that owns it.+ Generic wheels, or another family's, are the paths where the override may be the only+ source of usable kernels, so it must stay set there."""+ _run_install(+ gfx_devices = ("gfx1100",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_GENERIC_TORCH,+ installed_family = None,+ torch_owns_rocm = False,+ env = {"UNSLOTH_ROCM_GFX_ARCH": "gfx1100", "HSA_OVERRIDE_GFX_VERSION": "10.3.0"},+ )+ assert _run_install.hsa_override_after == "10.3.0", _run_install.hsa_override_after+++def test_a_rocr_masked_mi50_beside_a_dgpu_keeps_the_generic_wheels():+ """The mixed-host rule withholds the rocm6.3 tag from a gfx906 sharing a machine: the+ downgrade is persistent and every tag above rocm6.3 dropped the dGPU's kernels, while the+ mask lasts one session. rocminfo runs on the ROCr stack, so with ROCR naming the MI50 it+ reports that card alone and the machine read as single-architecture."""+ calls = _run_install(+ gfx_devices = ("gfx906",),+ unmasked_gfx_devices = ("gfx1100", "gfx906"),+ rocm_version = (7, 2),+ probe_source = "rocminfo",+ env = {"ROCR_VISIBLE_DEVICES": "1"},+ )+ assert "rocm6.3" not in calls, calls+ assert f"{_GENERIC}7.2" in calls, calls+ # The dGPU's bitsandbytes is part of what the downgrade cost.+ assert "bitsandbytes" in calls, calls+ # A machine that really is gfx906 alone still takes the legacy tag under the same mask,+ # including a mask whose ordinal names no device: the sole-arch question is about the+ # machine, and the answer decides which wheels carry kernels for the card that is there.+ for _ordinal in ("0", "1"):+ _sole = _run_install(+ gfx_devices = ("gfx906",),+ unmasked_gfx_devices = ("gfx906",),+ rocm_version = (7, 2),+ probe_source = "rocminfo",+ env = {"ROCR_VISIBLE_DEVICES": _ordinal},+ )+ assert f"{_GENERIC}6.3" in _sole, (_ordinal, _sole)+++def test_a_generic_only_target_on_a_stale_tag_is_repaired_on_update_too():+ """gfx950 has no per-arch leaf, so _generic_rocm_wheel_lacks_kernels answers False for it+ by design and the preflight read a rocm6.3 build as healthy. The install path applies a+ floor those wheels fail, so the card was repaired once and never from `studio update`."""+ for _tag, _hip, _repair in (+ ("2.9.1+rocm6.3", "6.3.0", True),+ ("2.11.0+rocm7.2", "7.2.0", False),+ ):+ with (+ patch.object(+ stack_mod, "_probe_torch_runtime", return_value = (True, True, _tag, _hip, "")+ ),+ patch.object(stack_mod, "_torch_requires_rocm_sdk", return_value = False),+ patch.object(stack_mod, "_installed_rocm_wheel_family", return_value = None),+ ):+ assert (+ stack_mod._rocm_torch_family_needs_repair("gfx950", (7, 2), ["gfx950"]) is _repair+ ), _tag+ # An arch with a leaf is still judged by the reroute question, not by this one.+ with (+ patch.object(+ stack_mod,+ "_probe_torch_runtime",+ return_value = (True, True, "2.11.0+rocm7.2", "7.2.0", ""),+ ),+ patch.object(stack_mod, "_torch_requires_rocm_sdk", return_value = False),+ patch.object(stack_mod, "_installed_rocm_wheel_family", return_value = None),+ ):+ assert stack_mod._rocm_torch_family_needs_repair("gfx1103", (7, 2), ["gfx1103"]) is True+++def test_a_generic_only_target_installs_when_the_rocm_version_is_unreadable():+ """The unreadable-version exit asks the reroute question, which gfx950 answers False to+ for want of a leaf, so a runtime-only host was left on CPU torch on every retry. An+ unreadable version is the absence of a reading, not evidence the tag clears the floor."""+ assert f"{_GENERIC}7.2" in _run_install(+ gfx_devices = ("gfx950",),+ rocm_version = None,+ torch_probe = _CPU_TORCH,+ torch_owns_rocm = False,+ )+ # An arch the generic wheel serves at every tag still exits there.+ _served = _run_install(+ gfx_devices = ("gfx1100",),+ rocm_version = None,+ torch_probe = _CPU_TORCH,+ torch_owns_rocm = False,+ )+ assert "torch" not in _served, _served+++def test_a_generic_only_target_pinned_to_a_stale_tag_is_reinstalled():+ """Forcing the pass is half a repair: a generic build names no family, so the family arm+ declines, there is no per-arch index to move to, and torch.version.hip keeps the fallback+ from running. A gfx950 pinned to rocm6.3 survived every update, and the preflight asked+ for a pass the install refused."""+ for _ver in ((7, 2), None):+ assert f"{_GENERIC}7.2" in _run_install(+ gfx_devices = ("gfx950",),+ rocm_version = _ver,+ torch_probe = _ROCM_GENERIC_TORCH_63,+ torch_owns_rocm = False,+ ), _ver+ # A generic build whose tag DOES carry the target is left alone, at either version.+ for _ver in ((7, 2), None):+ _kept = _run_install(+ gfx_devices = ("gfx950",),+ rocm_version = _ver,+ torch_probe = _ROCM_GENERIC_TORCH,+ torch_owns_rocm = False,+ )+ assert "torch" not in _kept, (_ver, _kept)+ # So is an arch the generic wheel serves at every tag.+ _served = _run_install(+ gfx_devices = ("gfx1100",),+ rocm_version = (7, 2),+ torch_probe = _ROCM_GENERIC_TORCH_63,+ torch_owns_rocm = False,+ )+ assert "torch" not in _served, _serveddiff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.pyindex db067b5604e..12c76f8276b 100644--- a/tests/studio/install/test_rocm_support.py+++ b/tests/studio/install/test_rocm_support.py@@ -601,9 +601,38 @@ class TestDetectRocmVersion:# TEST: install_python_stack.py -- _ensure_rocm_torch+def _named_arch_only():+ """_infer_linux_amd_gfx_arch with the product-name half removed.++ The function answers UNSLOTH_ROCM_GFX_ARCH first and infers from the board only after,+ and a real AMD host decides that second half. Cases naming an arch still get it; the+ rest get None instead of whatever board the runner happens to have."""+ return (os.environ.get("UNSLOTH_ROCM_GFX_ARCH") or "").strip().lower() or None++class TestEnsureRocmTorch:"""Verify ROCm torch reinstall logic."""+ @pytest.fixture(autouse = True)+ def _isolate_host(self, monkeypatch):+ """Describe the host by mocks alone: hide KFD topology and any ambient GPU mask.++ Both are read by _runtime_gfx_target and neither is covered by the per-case mocks.+ KFD sysfs is filtered by nothing, so on a real AMD machine it supplies a GPU no case+ asked for; an inherited empty HIP/ROCR/CUDA mask means "no GPU" and suppresses the+ very reroute a case asserts. A masked CI job hits both at once. The product-name+ inference is the third: on a Strix box /proc/cpuinfo names gfx1151 and the Strix+ route then answers before the tag these cases assert, which is what the gfx1151+ runner sees. Cases that mean to exercise any of the three set it themselves and win,+ since that happens inside this fixture."""+ for _mask in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(_mask, raising = False)+ with (+ patch.object(stack_mod, "_kfd_gfx_targets", return_value = []),+ patch.object(stack_mod, "_infer_linux_amd_gfx_arch", _named_arch_only),+ ):+ yield+# _infer_linux_amd_gfx_arch mocked to None: on a real Strix host the live# /proc/cpuinfo would otherwise take the inferred-install path and break# these "must not install" hosts (environment leak, not the code under test).@@ -934,8 +963,18 @@ class TestEnsureRocmTorch:@patch.object(stack_mod, "_has_rocm_gpu", return_value = True)@patch.object(stack_mod, "_infer_linux_amd_gfx_arch", return_value = None)@patch.object(stack_mod, "_detect_rocm_version", return_value = None)+ @patch.object(stack_mod, "_installed_rocm_wheel_family", return_value = None)+ @patch.object(stack_mod, "_torch_requires_rocm_sdk", return_value = False)def test_version_unreadable_prints_warning(- self, mock_ver, mock_infer, mock_gpu, mock_nvidia, mock_pip, capsys+ self,+ _mock_owns_sdk,+ _mock_family,+ mock_ver,+ mock_infer,+ mock_gpu,+ mock_nvidia,+ mock_pip,+ capsys,):"""ROCm detected but version unreadable should print warning and skip."""with patch("os.path.isdir", return_value = True):@@ -1013,6 +1052,12 @@ class TestEnsureRocmTorch:assert "gfx1151" not in callsassert "non-Strix runtime target (gfx1100)" in buf.getvalue()+ # The venv is described by mocks like the hardware: the Strix skip arm asks+ # _already_on_amd_arch_leaf, which reads this interpreter's own metadata, so on a host+ # that already runs AMD gfx1151 torch it keeps the wheels and the reroute never fires.+ # Passed as `new` rather than return_value so no mock argument joins the signature.+ @patch.object(stack_mod, "_installed_rocm_wheel_family", lambda: None)+ @patch.object(stack_mod, "_torch_requires_rocm_sdk", lambda: False)@patch.object(stack_mod, "IS_MACOS", False)@patch("platform.machine", return_value = "x86_64")@patch.object(stack_mod, "IS_WINDOWS", False)@@ -1137,6 +1182,11 @@ Agent 4assert "gfx1151" in torch_callassert "torch>=2.11.0,<2.12.0" in torch_call+ # A gfx pin is compared against the installed `rocm` meta-package before the version+ # heuristics run, and that read goes to THIS interpreter's metadata. Unpinned, the+ # gfx120X-all and gfx1150 cases below flip on any host that already has AMD per-arch+ # torch, because the family it reads back is that host's, not the pin's.+ @patch.object(stack_mod, "_installed_rocm_wheel_family", lambda: None)def test_rocm_pin_family_mismatch_helper(self):"""_rocm_pin_family_mismatch: exact rocm compare, else the 2.11 line."""f = stack_mod._rocm_pin_family_mismatch@@ -1271,6 +1321,11 @@ Agent 4any(str(a).startswith("torch") for a in _c.args) for _c in mock_pip.call_args_list)+ # Same reason as test_rocm_pin_family_mismatch_helper: the pin's staleness is judged+ # against the installed family first, so an unpinned read makes this assert something+ # about the machine running the suite.+ @patch.object(stack_mod, "_installed_rocm_wheel_family", lambda: None)+ @patch.object(stack_mod, "_torch_requires_rocm_sdk", lambda: False)@patch.object(stack_mod, "IS_WINDOWS", False)@patch.object(stack_mod, "pip_install_try", return_value = True)@patch.object(stack_mod, "pip_install")@@ -1456,6 +1511,24 @@ class TestGfx906LegacyReroute:"""gfx906 hosts on ROCm >= 6.4 must be rerouted to the rocm6.3 torch index;hosts already on gfx906-capable wheels are left alone."""+ @pytest.fixture(autouse = True)+ def _isolate_host(self, monkeypatch):+ """Hide KFD topology and any ambient GPU mask, for the reason given on+ TestEnsureRocmTorch: a real AMD test machine's sysfs would otherwise supply a GPU+ these gfx906 cases did not ask for, its product name would infer an arch none of them+ named, and an inherited empty mask would suppress the reroute they assert."""+ for _mask in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(_mask, raising = False)+ with (+ patch.object(stack_mod, "_kfd_gfx_targets", return_value = []),+ patch.object(stack_mod, "_infer_linux_amd_gfx_arch", _named_arch_only),+ # No per-arch wheel is installed in any of these cases; on the gfx1151 runner+ # both read a real one out of the venv and answer for a host none described.+ patch.object(stack_mod, "_installed_rocm_wheel_family", return_value = None),+ patch.object(stack_mod, "_torch_requires_rocm_sdk", return_value = False),+ ):+ yield+@staticmethoddef _gfx906_reroute_block(source: str) -> str:"""The MI50/gfx906 reroute block, bounded on the ';;' that closes its@@ -5636,6 +5709,61 @@ class TestStrixRocm71Override:with patch.object(m, "IS_WINDOWS", True):assert m._amd_arch_index_url("gfx1151") == m._windows_rocm_index_url("gfx1151")+ def test_a_windows_mirror_token_ending_in_a_slash_survives_the_join(self):+ """_index_url_join trims the path head and leaves the query alone, which is the whole+ point of it: "/" is in the base64 alphabet, so a token may legitimately end with one.+ The Windows base trimmed the raw env value first, which ate that character before the+ join could protect it, so the two platforms built different URLs from one mirror."""+ _mirror = "https://mirror.example/whl?token=YWJj/"+ # The Windows base is read once at import, so the env has to be set before the load.+ with patch.dict(os.environ, {"UNSLOTH_ROCM_WINDOWS_MIRROR": _mirror}):+ _spec = importlib.util.spec_from_file_location("stack_mirror_query", _STACK_PATH)+ m = importlib.util.module_from_spec(_spec)+ _spec.loader.exec_module(m)+ with patch.object(m, "IS_WINDOWS", True):+ assert m._windows_rocm_index_url("gfx1151") == (+ "https://mirror.example/whl/gfx1151/?token=YWJj/"+ )+ # Linux reads its own var at call time and always agreed; the two must now match.+ with (+ patch.object(m, "IS_WINDOWS", False),+ patch.dict(os.environ, {"UNSLOTH_AMD_ROCM_MIRROR": _mirror}),+ ):+ assert m._amd_arch_index_url("gfx1151") == (+ "https://mirror.example/whl/gfx1151/?token=YWJj/"+ )+ # A trailing slash on a plain path is still not doubled.+ with patch.object(stack_mod, "_ROCM_WINDOWS_INDEX_BASE", "https://mirror.example/whl/"):+ assert stack_mod._windows_rocm_index_url("gfx1151") == (+ "https://mirror.example/whl/gfx1151/"+ )++ def test_a_query_authenticated_mirror_says_pip_cannot_use_it(self):+ """Keeping the token whole is the lesser of two corruptions, not a working index: pip+ joins the package name onto the index URL as text (posixpath.join in+ SearchScope.get_index_urls_locations), so ".../gfx1151/?token=x" asks the index ROOT+ for a page whose name is inside the token, and a fragment never reaches the server at+ all. A mirror that can resolve nothing has to say why rather than 404 per package."""+ m = stack_mod+ for _base in ("https://mirror.example/whl?token=x", "https://mirror.example/whl#tok"):+ m._WARNED_QUERY_INDEX_BASES.discard(_base)+ _said = []+ with patch.object(m, "_safe_print", side_effect = _said.append):+ m._index_url_join(_base, "gfx110X-all")+ # Once per mirror, however many repairs consult it.+ m._index_url_join(_base, "gfx110X-all")+ assert len(_said) == 1, _said+ assert "netrc" in _said[0] and "credential" in _said[0], _said+ # A mirror pip CAN authenticate says nothing: userinfo lives in the netloc, which+ # the join never touches and pip carries onto every project URL.+ _plain = "https://user:[email protected]/whl"+ _quiet = []+ with patch.object(m, "_safe_print", side_effect = _quiet.append):+ assert m._index_url_join(_plain, "gfx110X-all") == (+ "https://user:[email protected]/whl/gfx110X-all/"+ )+ assert _quiet == [], _quiet+def test_strix_gfx_detection_in_install_sh(self):"""install.sh must detect gfx1151 and gfx1150 for the override."""source = _INSTALL_SH_PATH.read_text(encoding = "utf-8")@@ -5791,7 +5919,9 @@ class TestStrixRocm71Override:assert stack_mod._strix_needs_amd_arch_index((7, 14)) is Trueassert stack_mod._strix_needs_amd_arch_index((7, 0)) is Trueassert stack_mod._strix_needs_amd_arch_index((6, 0)) is True- assert stack_mod._strix_needs_amd_arch_index((5, 0)) is False+ # No generic tag resolves below 6.0, so there is no wheel to prefer and the per-arch+ # index, needing no host ROCm, is the only route. Same answer as an unreadable version.+ assert stack_mod._strix_needs_amd_arch_index((5, 0)) is Truedef test_torch_constraint_updated_for_strix_amd_index(self):"""install.sh must set TORCH_CONSTRAINT>=2.11 when routing Strix to AMD index."""