Skip to content

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

Linux: fix ROCm detection on split Debian stacks (#8886)

Natani L. Mayday3703a6678508
diff --git a/install.sh b/install.sh
index 5c07e2e6cc7..f6e0e4b336a 100755
--- a/install.sh
+++ b/install.sh
@@ -3651,17 +3651,17 @@ _cap_cuda_family_for_pre_turing() {
}
# ── ROCm version sources ──
-# One helper per source, each printing at most one "rocmX.Y" line, and each
-# returning 0 unconditionally: install.sh runs under set -e, so a real AMD GPU
-# with no ROCm userspace at all has to reach the actionable warning at the end of
-# the ROCm branch rather than have a failing source kill the installer.
+# One helper per source, each returning 0 unconditionally: under set -e a failing source
+# would kill the installer before the actionable warning at the end of the ROCm branch.
+# Every source that execs runs through _run_bounded: highest-wins consults all five, so a
+# single wedged probe would hang the installer. A timed-out probe just declined to answer.
_rocm_tag_from_amd_smi() {
command -v amd-smi >/dev/null 2>&1 || return 0
# Cut at the field separator and require digits: the line is pipe-delimited
# ("... | ROCm version: N/A | amdgpu version: 6.10.10 | ..."), so stripping every
# non-digit fabricated rocm6.10 out of the amdgpu driver version. Position used to
# hide that; under highest-wins a fabricated reading outvotes a real 6.1.
- amd-smi version 2>/dev/null | awk -F'ROCm version: ' \
+ _run_bounded amd-smi version 2>/dev/null | awk -F'ROCm version: ' \
'NF>1{v=$2; sub(/[ \t|].*$/, "", v); if (v ~ /^[0-9]+\.[0-9]+/) {split(v,a,"."); print "rocm"a[1]"."a[2]} exit}' || return 0
}
@@ -3672,39 +3672,43 @@ _rocm_tag_from_version_file() {
_rocm_tag_from_hipconfig() {
command -v hipconfig >/dev/null 2>&1 || return 0
- hipconfig --version 2>/dev/null \
+ _run_bounded hipconfig --version 2>/dev/null \
| awk 'NR==1 && /^[0-9]/{split($1,a,"."); if(a[1]+0>0){print "rocm"a[1]"."a[2]}}' || return 0
}
_rocm_tag_from_dpkg() {
command -v dpkg-query >/dev/null 2>&1 || return 0
- # Require the status word "installed". dpkg-query -W lists every package in the
- # status database except purged ones, so a rocm-core taken out with `apt remove`
- # stays queryable in state "deinstall ok config-files" still reporting the version
- # it had, and under highest-wins that dead entry outranks every live source (ran
- # 7.0, downgraded to 6.1, never purged -> rocm7.0 off a tree that is gone).
- # ${Status} over ${db:Status-Status}: documented showformat field with no dpkg
- # version floor, and dpkg renders an unrecognised field as empty rather than
- # failing, so a dpkg lacking it goes silent instead of over-reporting.
- _rt_ver=$(dpkg-query -W -f='${Status} ${Version}\n' rocm-core 2>/dev/null \
- | awk '$3 == "installed" && $4 != "" { print $4; exit }') || return 0
- [ -n "$_rt_ver" ] || return 0
- printf '%s\n' "$_rt_ver" | sed 's/^[0-9]*://' \
- | awk -F'[.-]' '{print "rocm"$1"."$2; exit}' || return 0
+ # Require the status word "installed" ($4 of the three-word ${Status}): dpkg-query -W lists
+ # every package except purged ones, so a removed-but-not-purged entry still reports its old
+ # version and could outrank the live runtime under highest-wins. ${Status} over
+ # ${db:Status-Status}: documented showformat field with no dpkg version floor, and an
+ # unrecognised field renders empty rather than failing, so a dpkg lacking it goes silent.
+ # `|| true` is load-bearing: dpkg-query exits nonzero when either package is absent while
+ # still printing the other's line. rocm-core wins outright; libhsa-runtime64-1 is read only
+ # in its absence (Debian ships no rocm-core), comes from the distro archive, and can be older.
+ { _run_bounded dpkg-query -W -f='${Package} ${Status} ${Version}\n' rocm-core libhsa-runtime64-1 2>/dev/null || true; } \
+ | awk '
+ $4 == "installed" && $5 != "" {
+ v = $5
+ sub(/^[0-9]+:/, "", v)
+ split(v, a, /[.-]/)
+ if (a[1] !~ /^[0-9]+$/ || a[2] !~ /^[0-9]+$/) next
+ if ($1 == "rocm-core") _core[_nc++] = "rocm" a[1] "." a[2]
+ else _hsa[_nh++] = "rocm" a[1] "." a[2]
+ }
+ END {
+ if (_nc) { for (_i = 0; _i < _nc; _i++) print _core[_i] }
+ else { for (_i = 0; _i < _nh; _i++) print _hsa[_i] }
+ }
+ ' || return 0
}
_rocm_tag_from_rpm() {
command -v rpm >/dev/null 2>&1 || return 0
- # Bounded, alone among the five, because this is the one source highest-wins
- # newly made unconditional that can block forever: it used to be LAST in a
- # first-answer-wins `||` chain, so /opt/rocm/.info/version answered at position
- # two and rpm was never invoked on a normal RHEL/SLES install. `rpm -q` is not a
- # lock-free read -- a leftover /var/lib/rpm/__db.00* from a killed rpm/yum wedges
- # plain queries in futex on the BerkeleyDB backend (rpm < 4.16, i.e. RHEL 8 /
- # SLES 15; rhbz#485780, rhbz#73097), and rpm 6.0.x deadlocks `rpm --query`
- # against a running dnf (rhbz#2463435). A version probe must not hang the
- # installer, and a timed-out probe is just a source that declined to answer.
- # _run_bounded no-ops where `timeout` is absent, so this adds no dependency.
+ # `rpm -q` is not a lock-free read: a leftover /var/lib/rpm/__db.00* from a killed
+ # rpm/yum wedges plain queries in futex on the BerkeleyDB backend (rpm < 4.16, i.e.
+ # RHEL 8 / SLES 15; rhbz#485780, rhbz#73097), and rpm 6.0.x deadlocks `rpm --query`
+ # against a running dnf (rhbz#2463435). _run_bounded no-ops where `timeout` is absent.
_rt_ver=$(_run_bounded rpm -q --qf '%{VERSION}\n' rocm-core 2>/dev/null) || return 0
[ -n "$_rt_ver" ] || return 0
printf '%s\n' "$_rt_ver" | awk -F'[.-]' '{print "rocm"$1"."$2; exit}' || return 0
@@ -3725,17 +3729,16 @@ _highest_rocm_tag() {
'
}
-# Consult EVERY source and take the highest, not the first that answers. Distros
-# with split ROCm packaging ship one component well behind the runtime the GPU
-# actually uses: Debian 13 (and Linux Mint on top of it) packages hipconfig at
-# 5.7.x next to a 6.1.x rocminfo/HSA, so first-answer resolution reported rocm5.7
-# on a working gfx1100 and the 6.0+ gate below sent it to CPU-only wheels (issue
-# #8402). A source reading lower than another on the same host is stale packaging,
-# not a downgrade. The symmetric risk, overshoot, is bounded: PyTorch's ROCm wheels
-# vendor their own userspace and need only an amdgpu/KFD driver AMD documents as
-# compatible +/- 2 releases, the normalisation below can only emit a leaf PyTorch
-# publishes, the one source that can report a tree that is not installed is
-# filtered above, and any disagreement is named on stderr for the install log.
+# Consult EVERY source and take the highest, not the first that answers. Distros with split
+# ROCm packaging ship one component well behind the runtime the GPU actually uses: Debian 13
+# (and Linux Mint on top of it) packages hipconfig at 5.7.x next to a 6.1.x rocminfo/HSA, so
+# first-answer resolution reported rocm5.7 on a working gfx1100 and the 6.0+ gate below sent
+# it to CPU-only wheels (issue #8402). A source reading lower than another on the same host
+# is stale packaging, not a downgrade. Overshoot is bounded: PyTorch's ROCm wheels vendor
+# their own userspace and need only an amdgpu/KFD driver AMD documents as compatible +/- 2
+# releases, the normalisation below can only emit a leaf PyTorch publishes, package-manager
+# sources that can report an uninstalled tree are filtered above, and any disagreement is
+# named on stderr for the install log.
_detect_rocm_version_tag() {
_rt_readings=$({
_rocm_tag_from_amd_smi
@@ -3865,7 +3868,7 @@ get_torch_index_url() {
case "$_rocm_tag" in
rocm[1-5].*)
echo "[WARN] ROCm $_rocm_tag detected but PyTorch ROCm wheels require ROCm 6.0+ -- falling back to CPU-only PyTorch" >&2
- echo "[WARN] $_rocm_tag is the HIGHEST version any of amd-smi, /opt/rocm/.info/version, hipconfig or rocm-core reported." >&2
+ echo "[WARN] $_rocm_tag is the HIGHEST version detected from usable ROCm sources; where dpkg has no rocm-core (Debian) the installed libhsa-runtime64-1 is read instead." >&2
echo "[WARN] Upgrade ROCm: https://rocm.docs.amd.com/en/latest/deploy/linux/index.html" >&2
echo "[WARN] If this host really runs ROCm 6.0+ and only its packaging says otherwise, pin the wheels and re-run:" >&2
echo "[WARN] UNSLOTH_TORCH_INDEX_FAMILY=rocm6.4 (a PyTorch wheel leaf: rocm6.0-6.4, rocm7.0-7.2)" >&2
@@ -3914,7 +3917,7 @@ get_torch_index_url() {
echo "[WARN] Install the ROCm/HIP SDK, then re-run this installer:" >&2
echo "[WARN] Arch / CachyOS : sudo pacman -S rocm-hip-sdk" >&2
echo "[WARN] other distros : https://rocm.docs.amd.com/en/latest/deploy/linux/index.html" >&2
- echo "[WARN] Minimum required for version detection: amd-smi, hipconfig, /opt/rocm/.info/version, or the rocm-core package." >&2
+ echo "[WARN] Minimum required for version detection: amd-smi, hipconfig, a ROCm version file, or an installed runtime package (Debian: libhsa-runtime64-1)." >&2
echo "$_base/cpu"; return
fi
# Parse CUDA version from nvidia-smi output (POSIX-safe, no grep -P).
@@ -4174,24 +4177,44 @@ _strip_index_url_credentials() {
fi
}
+# 0 when host version $1 (x.y or x.y.z) is no older than leaf version $2 (x.y), or $2 is empty
+_radeon_host_ver_not_older() {
+ [ -n "$1" ] || return 1
+ [ -n "$2" ] || return 0
+ _rh_maj=${1%%.*}; _rh_rest=${1#*.}; _rh_min=${_rh_rest%%.*}
+ _rl_maj=${2%%.*}; _rl_rest=${2#*.}; _rl_min=${_rl_rest%%.*}
+ case "$_rh_maj$_rh_min$_rl_maj$_rl_min" in *[!0-9]*) return 1 ;; esac
+ if [ "$_rh_maj" -gt "$_rl_maj" ]; then return 0; fi
+ if [ "$_rh_maj" -lt "$_rl_maj" ]; then return 1; fi
+ [ "$_rh_min" -ge "$_rl_min" ]
+}
+
get_radeon_wheel_url() {
- # Only meaningful on Linux. Picks a repo.radeon.com base URL whose listing
- # contains torch wheels. Tries paths like rocm-rel-7.2.1/, rocm-rel-7.2/,
- # rocm-rel-7.1.1/, rocm-rel-7.1/ (AMD publishes both M.m and M.m.p dirs).
- # Accepts both X.Y and X.Y.Z host versions since /opt/rocm/.info/version
- # and hipconfig --version can return either shape.
+ # Only meaningful on Linux. AMD publishes both M.m and M.m.p rocm-rel directories, so
+ # both X.Y and X.Y.Z are valid leaf names here.
case "$(uname -s)" in Linux) ;; *) echo ""; return ;; esac
- # Detect ROCm version (X.Y or X.Y.Z) -- try amd-smi, then
- # /opt/rocm/.info/version, then hipconfig.
_full_ver=""
- _full_ver=$({ command -v amd-smi >/dev/null 2>&1 && \
- amd-smi version 2>/dev/null | awk -F'ROCm version: ' \
+ _resolved_tag="${1:-}"
+ _resolved_ver=""
+ case "$_resolved_tag" in
+ rocm[1-9]*.[0-9]*)
+ _resolved_ver=$(printf '%s\n' "$_resolved_tag" \
+ | awk '/^rocm[1-9][0-9]*\.[0-9][0-9]*$/ {sub(/^rocm/, ""); print; exit}')
+ ;;
+ esac
+ _host_ver=$({ command -v amd-smi >/dev/null 2>&1 && \
+ _run_bounded amd-smi version 2>/dev/null | awk -F'ROCm version: ' \
'NF>1{if(match($2,/[0-9]+\.[0-9]+(\.[0-9]+)?/)){print substr($2,RSTART,RLENGTH); ok=1; exit}} END{exit !ok}'; } || \
{ [ -r /opt/rocm/.info/version ] && \
awk 'match($0,/[0-9]+\.[0-9]+(\.[0-9]+)?/){print substr($0,RSTART,RLENGTH); found=1; exit} END{exit !found}' /opt/rocm/.info/version; } || \
{ command -v hipconfig >/dev/null 2>&1 && \
- hipconfig --version 2>/dev/null | awk 'NR==1 && match($0,/[0-9]+\.[0-9]+(\.[0-9]+)?/){print substr($0,RSTART,RLENGTH); found=1} END{exit !found}'; }) 2>/dev/null
+ _run_bounded hipconfig --version 2>/dev/null | awk 'NR==1 && match($0,/[0-9]+\.[0-9]+(\.[0-9]+)?/){print substr($0,RSTART,RLENGTH); found=1} END{exit !found}'; }) 2>/dev/null || _host_ver=""
+ if _radeon_host_ver_not_older "$_host_ver" "$_resolved_ver"; then
+ _full_ver="$_host_ver"
+ else
+ _full_ver="$_resolved_ver"
+ fi
# Validate: must be X.Y or X.Y.Z with X >= 1
case "$_full_ver" in
@@ -5322,7 +5345,7 @@ elif [ -n "$TORCH_INDEX_URL" ]; then
if [ "$SKIP_TORCH" = true ]; then
substep "skipping PyTorch (--no-torch or Intel Mac x86_64)." "$C_WARN"
elif [ "$_amd_gpu_radeon" = true ]; then
- _radeon_url=$(get_radeon_wheel_url)
+ _radeon_url=$(get_radeon_wheel_url "$_torch_index_leaf")
if [ -n "$_radeon_url" ]; then
_radeon_listing_ok=false
if _radeon_fetch_listing "$_radeon_url" 2>/dev/null; then
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.py
index 1b05ebfc37a..2618f63870c 100644
--- a/studio/install_llama_prebuilt.py
+++ b/studio/install_llama_prebuilt.py
@@ -3371,11 +3371,8 @@ def _detect_host_rocm_version() -> tuple[int, int] | None:
except Exception:
pass
- # Distro package-manager fallbacks. Mirrors install.sh::get_torch_index_url
- # and _detect_rocm_version() in install_python_stack.py so package-managed
- # ROCm hosts without /opt/rocm/.info/version still report a usable version
- # and the <= host version filter in resolve_upstream_asset_choice picks
- # the correct upstream prebuilt instead of the newest-regardless fallback.
+ # Distro package-manager fallbacks. Deliberately diverges from install.sh and
+ # _detect_rocm_version(): stops at the first answer, no "installed" status word gate.
for _cmd in (
["dpkg-query", "-W", "-f=${Version}\n", "rocm-core"],
["rpm", "-q", "--qf", "%{VERSION}\n", "rocm-core"],
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index cf5368851eb..0654c9c02ed 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -688,8 +688,34 @@ def _amd_smi_allowed() -> bool:
return False
+# Memoized: _ensure_rocm_torch() runs twice on Linux; the disagreement warning prints once.
+_ROCM_VERSION_PROBE: "tuple[int, int] | None" = None
+_ROCM_VERSION_PROBED: bool = False
+
+
+def _invalidate_rocm_version_probe() -> None:
+ """Forget the memoized host ROCm version."""
+ global _ROCM_VERSION_PROBE, _ROCM_VERSION_PROBED
+ _ROCM_VERSION_PROBE = None
+ _ROCM_VERSION_PROBED = False
+
+
def _detect_rocm_version() -> tuple[int, int] | None:
- """Return (major, minor) of the installed ROCm stack, or None."""
+ """Return (major, minor) of the installed ROCm stack, or None. Memoized per run."""
+ global _ROCM_VERSION_PROBE, _ROCM_VERSION_PROBED
+ if not _ROCM_VERSION_PROBED:
+ _ROCM_VERSION_PROBE = _detect_rocm_version_uncached()
+ _ROCM_VERSION_PROBED = True
+ return _ROCM_VERSION_PROBE
+
+
+def _detect_rocm_version_uncached() -> tuple[int, int] | None:
+ """Probe every ROCm version source and return the highest reading, or None."""
+ readings: list[tuple[str, tuple[int, int]]] = []
+
+ def _record(source: str, major: int, minor: int) -> None:
+ readings.append((source, (major, minor)))
+
rocm_root = os.environ.get("ROCM_PATH") or "/opt/rocm"
for path in (
os.path.join(rocm_root, ".info", "version"),
@@ -701,7 +727,8 @@ def _detect_rocm_version() -> tuple[int, int] | None:
# Explicit length guard: don't rely on the broad except below to
# swallow IndexError on a single-component version (e.g. "6\n").
if len(parts) >= 2:
- return int(parts[0]), int(parts[1])
+ _record("ROCm version file", int(parts[0]), int(parts[1]))
+ break
except Exception:
pass
@@ -722,7 +749,11 @@ def _detect_rocm_version() -> tuple[int, int] | None:
if result.returncode == 0:
m = re.search(r"ROCm version:\s*(\d+)\.(\d+)", result.stdout)
if m:
- return int(m.group(1)), int(m.group(2))
+ _record(
+ "amd-smi",
+ int(m.group(1)),
+ int(m.group(2)),
+ )
except Exception:
pass
@@ -740,41 +771,103 @@ def _detect_rocm_version() -> tuple[int, int] | None:
raw = result.stdout.decode().strip().split("\n")[0]
parts = raw.split(".")
if len(parts) >= 2 and parts[0].isdigit() and parts[1].split("-")[0].isdigit():
- return int(parts[0]), int(parts[1].split("-")[0])
+ _record(
+ "hipconfig",
+ int(parts[0]),
+ int(parts[1].split("-")[0]),
+ )
except Exception:
pass
- # Distro package-manager fallbacks: package-managed ROCm can expose GPUs via
- # rocminfo/amd-smi but lack /opt/rocm/.info/version and hipconfig, so probe
- # dpkg (Debian/Ubuntu) and rpm (RHEL/Fedora/SUSE) for the rocm-core version.
- # Matches install.sh::get_torch_index_url so `studio update` == fresh install.
- for cmd in (
- ["dpkg-query", "-W", "-f=${Version}\n", "rocm-core"],
- ["rpm", "-q", "--qf", "%{VERSION}\n", "rocm-core"],
- ):
- exe = shutil.which(cmd[0])
- if not exe:
- continue
+ # Only "installed" counts: dpkg-query still reports removed-but-not-purged packages.
+ # rocm-core wins outright over libhsa-runtime64-1, which comes from the distro archive
+ # and can be older (Ubuntu 5.7.1 beside AMD's rocm-core 7.2.1), so they are not peers.
+ dpkg = shutil.which("dpkg-query")
+ if dpkg:
try:
result = subprocess.run(
- [exe, *cmd[1:]],
+ [
+ dpkg,
+ "-W",
+ "-f=${Package} ${Status} ${Version}\n",
+ "rocm-core",
+ "libhsa-runtime64-1",
+ ],
stdout = subprocess.PIPE,
stderr = subprocess.DEVNULL,
text = True,
timeout = 5,
)
+ # dpkg-query exits nonzero when either package is absent but still prints
+ # the other's line, so parse stdout regardless of the return code.
+ _dpkg_readings: "dict[str, list[tuple[int, int]]]" = {"rocm-core": [], "hsa": []}
+ for line in result.stdout.splitlines():
+ fields = line.split()
+ if len(fields) < 5 or fields[3] != "installed":
+ continue
+ package, raw = fields[0], fields[4]
+ if package not in ("rocm-core", "libhsa-runtime64-1"):
+ continue
+ # dpkg can prepend an epoch ("1:6.3.0-1"); strip it before parsing.
+ raw = re.sub(r"^\d+:", "", raw)
+ m = re.match(r"(\d+)[.-](\d+)", raw)
+ if m:
+ _key = "rocm-core" if package == "rocm-core" else "hsa"
+ _dpkg_readings[_key].append((int(m.group(1)), int(m.group(2))))
+ if _dpkg_readings["rocm-core"]:
+ for _major, _minor in _dpkg_readings["rocm-core"]:
+ _record("dpkg rocm-core", _major, _minor)
+ else:
+ for _major, _minor in _dpkg_readings["hsa"]:
+ _record("dpkg HSA runtime", _major, _minor)
except Exception:
- continue
- if result.returncode != 0 or not result.stdout.strip():
- continue
- raw = result.stdout.strip()
- # dpkg can prepend an epoch ("1:6.3.0-1"); strip it before parsing.
- raw = re.sub(r"^\d+:", "", raw)
- m = re.match(r"(\d+)[.-](\d+)", raw)
- if m:
- return int(m.group(1)), int(m.group(2))
+ pass
- return None
+ rpm = shutil.which("rpm")
+ if rpm:
+ try:
+ result = subprocess.run(
+ [
+ rpm,
+ "-q",
+ "--qf",
+ "%{VERSION}\n",
+ "rocm-core",
+ ],
+ stdout = subprocess.PIPE,
+ stderr = subprocess.DEVNULL,
+ text = True,
+ timeout = 5,
+ )
+ if result.returncode == 0 and result.stdout.strip():
+ raw = result.stdout.strip()
+ m = re.match(r"(\d+)[.-](\d+)", raw)
+ if m:
+ _record(
+ "rpm rocm-core",
+ int(m.group(1)),
+ int(m.group(2)),
+ )
+ except Exception:
+ pass
+
+ if not readings:
+ return None
+
+ best = max(version for _, version in readings)
+ distinct = {version for _, version in readings}
+
+ if len(distinct) > 1:
+ details = ", ".join(
+ f"{source}=rocm{version[0]}.{version[1]}" for source, version in readings
+ )
+ _safe_print(
+ f"WARNING: ROCm version sources disagree ({details}) -- "
+ f"using the highest, rocm{best[0]}.{best[1]}.",
+ file = sys.stderr,
+ )
+
+ return best
# APU gfx arches whose board commonly also carries a discrete Radeon. HIP often
diff --git a/tests/sh/test_get_torch_index_url.sh b/tests/sh/test_get_torch_index_url.sh
index 88615153e1f..0076bc6e5cf 100755
--- a/tests/sh/test_get_torch_index_url.sh
+++ b/tests/sh/test_get_torch_index_url.sh
@@ -74,6 +74,15 @@ _FAKE_ROCM_DIR=$(mktemp -d)
-e "s|/opt/rocm|$_FAKE_ROCM_DIR|g" \
> "$_FUNC_FILE"
+for _fn in _rocm_tag_from_amd_smi _rocm_tag_from_version_file _rocm_tag_from_hipconfig \
+ _rocm_tag_from_dpkg _rocm_tag_from_rpm _highest_rocm_tag \
+ _detect_rocm_version_tag get_torch_index_url; do
+ if ! grep -q "^$_fn()" "$_FUNC_FILE"; then
+ echo "FAIL: install.sh no longer defines $_fn() at column 0"
+ exit 1
+ fi
+done
+
# Save system PATH so we always have basic tools (uname, grep, head, etc.)
_SYS_PATH="/usr/local/bin:/usr/bin:/bin"
diff --git a/tests/sh/test_rocm_version_source_disagreement.sh b/tests/sh/test_rocm_version_source_disagreement.sh
index d407e603cb5..f36f79f63e6 100755
--- a/tests/sh/test_rocm_version_source_disagreement.sh
+++ b/tests/sh/test_rocm_version_source_disagreement.sh
@@ -68,6 +68,10 @@ _FAKE_PROC_NV_DIR=$(mktemp -d)
sed -n '/^_detect_rocm_version_tag()/,/^}/p' "$INSTALL_SH"
echo ""
sed -n '/^get_torch_index_url()/,/^}/p' "$INSTALL_SH"
+ echo ""
+ sed -n '/^_radeon_host_ver_not_older()/,/^}/p' "$INSTALL_SH"
+ echo ""
+ sed -n '/^get_radeon_wheel_url()/,/^}/p' "$INSTALL_SH"
} | sed -e "s|/usr/bin/nvidia-smi|$_FAKE_SMI_DIR/nvidia-smi-absent|g" \
-e "s|/proc/driver/nvidia|$_FAKE_PROC_NV_DIR|g" \
-e "s|/opt/rocm|$_FAKE_ROCM_DIR|g" \
@@ -77,7 +81,8 @@ _FAKE_PROC_NV_DIR=$(mktemp -d)
# below fail as a plain "cpu" with no hint why.
for _fn in _rocm_tag_from_amd_smi _rocm_tag_from_version_file _rocm_tag_from_hipconfig \
_rocm_tag_from_dpkg _rocm_tag_from_rpm _highest_rocm_tag \
- _detect_rocm_version_tag get_torch_index_url; do
+ _detect_rocm_version_tag get_torch_index_url get_radeon_wheel_url \
+ _radeon_host_ver_not_older; do
if ! grep -q "^$_fn()" "$_FUNC_FILE"; then
echo " FAIL: install.sh no longer defines $_fn() at column 0"
exit 1
@@ -190,50 +195,83 @@ MOCK
chmod +x "$_MOCK_DIR/amd-smi"
}
-# $1 = rocm-core version as dpkg reports it (epoch prefixes allowed, e.g. 1:6.2.4-1)
-# $2 = dpkg status word, default "installed". "config-files" is where `apt remove`
-# without `apt purge` leaves a package: still in /var/lib/dpkg/status, still
-# carrying its old version, and still reported by `dpkg-query -W`.
-# The mock renders the showformat string it is given rather than a bare version, so
-# these assertions test how install.sh ASKS dpkg, not just how it parses the answer.
-add_dpkg_rocm_core() {
- printf '%s\n' "$1" > "$_MOCK_DIR/.dpkg-version"
- printf '%s\n' "${2:-installed}" > "$_MOCK_DIR/.dpkg-status"
+add_dpkg_packages() {
+ printf '%s\n' "$@" > "$_MOCK_DIR/.dpkg-entries"
cat > "$_MOCK_DIR/dpkg-query" <<'MOCK'
#!/bin/sh
_d=${0%/*}
-_ver=$(cat "$_d/.dpkg-version")
-_status=$(cat "$_d/.dpkg-status")
-# Status is "<want> <error-flag> <status>": removed but not purged reads "deinstall ok config-files".
-case "$_status" in installed) _want=install ;; *) _want=deinstall ;; esac
+_entries=$(cat "$_d/.dpkg-entries")
_fmt=''
-_found=''
+_requested=''
+_has_rocm_core=0
+_has_hsa_runtime=0
while [ $# -gt 0 ]; do
case "$1" in
-f=*) _fmt=${1#-f=} ;;
--showformat=*) _fmt=${1#--showformat=} ;;
-f|--showformat) shift; _fmt=$1 ;;
-*) : ;;
- rocm-core) _found=1 ;;
+ rocm-core)
+ _requested="$_requested $1"
+ _has_rocm_core=1
+ ;;
+ libhsa-runtime64-1)
+ _requested="$_requested $1"
+ _has_hsa_runtime=1
+ ;;
esac
shift
done
-[ -n "$_found" ] || exit 1
+[ "$_has_rocm_core" -eq 1 ] && [ "$_has_hsa_runtime" -eq 1 ] || exit 1
[ -n "$_fmt" ] || _fmt='${Package}\t${Version}\n'
# Unknown fields render empty, which is what real dpkg-query does.
-_out=$(printf '%s' "$_fmt" | sed \
- -e "s|\${Package}|rocm-core|g" \
- -e "s|\${Status}|$_want ok $_status|g" \
- -e "s|\${db:Status-Status}|$_status|g" \
- -e "s|\${db:Status-Want}|$_want|g" \
- -e "s|\${db:Status-Eflag}|ok|g" \
- -e "s|\${Version}|$_ver|g" \
- -e "s|\${[^}]*}||g")
-printf "$_out"
+_emit() {
+ _package=$1
+ _status=$2
+ _ver=$3
+ # Status is "<want> <error-flag> <status>": removed but not purged reads
+ # "deinstall ok config-files".
+ case "$_status" in installed) _want=install ;; *) _want=deinstall ;; esac
+ _out=$(printf '%s' "$_fmt" | sed \
+ -e "s|\${Package}|$_package|g" \
+ -e "s|\${Status}|$_want ok $_status|g" \
+ -e "s|\${db:Status-Status}|$_status|g" \
+ -e "s|\${db:Status-Want}|$_want|g" \
+ -e "s|\${db:Status-Eflag}|ok|g" \
+ -e "s|\${Version}|$_ver|g" \
+ -e "s|\${[^}]*}||g")
+ printf "$_out"
+}
+_missing=0
+for _wanted in $_requested; do
+ _found=0
+ while IFS='|' read -r _package _status _ver; do
+ [ "$_package" = "$_wanted" ] && _found=1
+ done <<EOF
+$_entries
+EOF
+ [ "$_found" -eq 1 ] || _missing=1
+done
+while IFS='|' read -r _package _status _ver; do
+ case " $_requested " in
+ *" $_package "*) _emit "$_package" "$_status" "$_ver" ;;
+ esac
+done <<EOF
+$_entries
+EOF
+exit "$_missing"
MOCK
chmod +x "$_MOCK_DIR/dpkg-query"
}
+add_dpkg_rocm_core() {
+ add_dpkg_packages "rocm-core|${2:-installed}|$1"
+}
+
+add_dpkg_hsa_runtime() {
+ add_dpkg_packages "libhsa-runtime64-1|${2:-installed}|$1"
+}
+
# $1 = rocm-core version as rpm reports it
add_rpm_rocm_core() {
cat > "$_MOCK_DIR/rpm" <<MOCK
@@ -278,6 +316,12 @@ run_warnings() {
_ARCH=x86_64; . '$_FUNC_FILE'; get_torch_index_url" 2>&1 >/dev/null | tr '\n' ' '
}
+run_radeon_url() {
+ PATH="$_MOCK_DIR:$_TOOLS_DIR" bash -c \
+ 'uname() { echo Linux; }; . "$1"; get_radeon_wheel_url "$2"' \
+ _ "$_FUNC_FILE" "$1" 2>/dev/null
+}
+
# Same, under `set -e` like the real installer, reporting only the exit status:
# with every source missing, detection must return empty AND succeed or the
# installer dies before the actionable warning.
@@ -294,12 +338,10 @@ _BASE="https://download.pytorch.org/whl"
echo "=== test_rocm_version_source_disagreement ==="
# ── 1. The reported host ────────────────────────────────────────────────────
-# No /opt/rocm/.info/version, hipconfig from the distro's 5.7 packaging, rocm-core
-# at 6.1 in dpkg. Before the fix hipconfig answered first and this returned cpu.
reset_sources
add_hipconfig "5.7.31921-0"
-add_dpkg_rocm_core "1:6.1.2-1"
-assert_eq "Debian 13 hipconfig 5.7 + rocm-core 6.1 -> rocm6.1" "$_BASE/rocm6.1" "$(run_index)"
+add_dpkg_hsa_runtime "1:6.1.2-1"
+assert_eq "Debian 13 hipconfig 5.7 + HSA runtime 6.1 -> rocm6.1" "$_BASE/rocm6.1" "$(run_index)"
_warn=$(run_warnings)
case "$_warn" in
*"require ROCm 6.0+"*) assert_eq "the same host emits no 6.0+ gate warning" "" "$_warn" ;;
@@ -308,6 +350,30 @@ esac
# The breadcrumb that makes a wrong-HIGH reading diagnosable from an install log.
assert_contains "disagreeing sources are named" "sources disagree (rocm5.7 rocm6.1)" "$_warn"
assert_contains "the winning reading is named" "using the highest, rocm6.1" "$_warn"
+assert_eq "Radeon URL uses resolved Debian rocm6.1, not hipconfig 5.7" \
+ "https://repo.radeon.com/rocm/manylinux/rocm-rel-6.1/" "$(run_radeon_url rocm6.1)"
+
+# rocm-core wins even when HSA reads higher, and HSA is emitted first, so position cannot pass this.
+reset_sources
+add_dpkg_packages \
+ "libhsa-runtime64-1|installed|6.4.3+dfsg-4" \
+ "rocm-core|installed|1:6.1.2-2"
+assert_eq "installed rocm-core outranks a HIGHER distro HSA reading -> rocm6.1" \
+ "$_BASE/rocm6.1" "$(run_index)"
+assert_eq "and the outranked HSA reading is not named as a disagreement" "" "$(run_warnings)"
+
+reset_sources
+add_dpkg_packages \
+ "libhsa-runtime64-1|installed|5.7.1-2build1" \
+ "rocm-core|installed|7.2.1.70201-81~24.04"
+assert_eq "Ubuntu + AMD repo resolves rocm7.2" "$_BASE/rocm7.2" "$(run_index)"
+assert_eq "Ubuntu + AMD repo warns about nothing" "" "$(run_warnings)"
+
+reset_sources
+add_hipconfig "5.7.31921-0"
+add_dpkg_hsa_runtime "1:6.1.2-1"
+assert_eq "no rocm-core, so the installed HSA runtime still votes -> rocm6.1" \
+ "$_BASE/rocm6.1" "$(run_index)"
# 2. Same shape from /opt/rocm/.info/version. This one already worked by position,
# so it is here to pin that the rewrite did not lose it.
@@ -351,6 +417,13 @@ assert_eq "config-files rocm-core 7.0 on a 6.1 host -> rocm6.1, not rocm7.0" \
"$_BASE/rocm6.1" "$(run_index)"
assert_eq "the dead dpkg entry is not even named as a disagreement" "" "$(run_warnings)"
+reset_sources
+add_hipconfig "6.1.40093-0"
+add_dpkg_hsa_runtime "1:7.0.0-1" config-files
+assert_eq "config-files HSA runtime 7.0 on a 6.1 host -> rocm6.1, not rocm7.0" \
+ "$_BASE/rocm6.1" "$(run_index)"
+assert_eq "the dead HSA entry is not named as a disagreement" "" "$(run_warnings)"
+
# 5c. The live entry still has to win, or the fix for the reported bug is gone.
# This is what makes 5b non-vacuous: only the dpkg status word differs.
reset_sources
@@ -521,6 +594,32 @@ else
"under 20s" "$((_t1 - _t0))s (outer bound fired)"
fi
+reset_sources
+add_version_file "6.5.0-1"
+assert_eq "a ROCm 6.5 host clipped to the rocm6.4 leaf still gets rocm-rel-6.5.0" \
+ "https://repo.radeon.com/rocm/manylinux/rocm-rel-6.5.0/" "$(run_radeon_url rocm6.4)"
+
+reset_sources
+add_version_file "7.3.1-1"
+assert_eq "a ROCm 7.3 host capped to the rocm7.2 leaf still gets rocm-rel-7.3.1" \
+ "https://repo.radeon.com/rocm/manylinux/rocm-rel-7.3.1/" "$(run_radeon_url rocm7.2)"
+
+# the caller only falls back x.y.z -> x.y, so a leaf-derived x.y never reaches an x.y.z-only directory
+reset_sources
+add_version_file "7.2.1-98"
+assert_eq "a matching-family host still contributes its patch level" \
+ "https://repo.radeon.com/rocm/manylinux/rocm-rel-7.2.1/" "$(run_radeon_url rocm7.2)"
+
+reset_sources
+add_hipconfig "5.7.31921-0"
+assert_eq "an older host probe never overrides the resolved leaf" \
+ "https://repo.radeon.com/rocm/manylinux/rocm-rel-6.1/" "$(run_radeon_url rocm6.1)"
+
+reset_sources
+assert_eq "with no readable host source the leaf is used verbatim" \
+ "https://repo.radeon.com/rocm/manylinux/rocm-rel-6.4/" "$(run_radeon_url rocm6.4)"
+assert_eq "no host source and no leaf yields no Radeon URL" "" "$(run_radeon_url '')"
+
echo ""
echo "Results: $PASS passed, $FAIL failed"
[ "$FAIL" -eq 0 ]
diff --git a/tests/studio/install/test_probe_timeouts.py b/tests/studio/install/test_probe_timeouts.py
index 0ff93c1b12f..4c6acbe87de 100644
--- a/tests/studio/install/test_probe_timeouts.py
+++ b/tests/studio/install/test_probe_timeouts.py
@@ -6,6 +6,7 @@ shell test confirms the bash helper returns within the timeout when nvidia-smi h
"""
import os
+import re
import shutil
import stat
import subprocess
@@ -185,3 +186,101 @@ def test_has_usable_nvidia_gpu_returns_under_timeout():
assert proc.stdout.strip() in {"NONE", "DETECTED"}
finally:
shutil.rmtree(workdir, ignore_errors = True)
+
+
+# Highest-wins runs every ROCm version source on every AMD host, so a hang in any one of
+# them hangs the installer: rpm was bounded when that landed, dpkg-query, hipconfig and
+# amd-smi were not, and dpkg-query decides on Debian, which ships no rocm-core.
+
+# Matched against the EXECUTION line only, so a helper stays free to resolve the tool some
+# other way (a $ROCM_PATH/bin path, a variable) without the assertion going stale.
+_ROCM_SOURCE_PROBES = [
+ ("_rocm_tag_from_amd_smi", r"amd-smi\s+version\b"),
+ ("_rocm_tag_from_hipconfig", r"--version\b"),
+ ("_rocm_tag_from_dpkg", r"dpkg-query\s+-W\b"),
+ ("_rocm_tag_from_rpm", r"\brpm\s+-q\b"),
+]
+
+
+def _exec_lines(body: str, pattern: str) -> list:
+ """Lines that run the probe: matches `pattern` and is not a comment or a lookup guard."""
+ return [
+ line
+ for line in body.splitlines()
+ if re.search(pattern, line)
+ and not line.lstrip().startswith("#")
+ and "command -v" not in line
+ and not re.search(r"\[\s*-x\s", line)
+ ]
+
+
+class TestRocmVersionSourcesBounded:
+ def _src(self) -> str:
+ return INSTALL_SH.read_text(encoding = "utf-8")
+
+ @pytest.mark.parametrize("fn_name,pattern", _ROCM_SOURCE_PROBES)
+ def test_source_probe_is_bounded(self, fn_name, pattern):
+ body = _extract_sh_function_body(self._src(), fn_name)
+ assert body, f"install.sh must define {fn_name}"
+ lines = _exec_lines(body, pattern)
+ assert lines, f"{fn_name} no longer runs a probe matching {pattern}"
+ for line in lines:
+ assert "_run_bounded" in line, f"{fn_name} runs an unbounded probe: {line.strip()}"
+
+ @pytest.mark.parametrize("pattern", [r"amd-smi\s+version\b", r"--version\b"])
+ def test_radeon_wheel_url_probes_are_bounded(self, pattern):
+ body = _extract_sh_function_body(self._src(), "get_radeon_wheel_url")
+ assert body, "install.sh must define get_radeon_wheel_url"
+ lines = _exec_lines(body, pattern)
+ assert lines, f"get_radeon_wheel_url no longer runs a probe matching {pattern}"
+ for line in lines:
+ assert (
+ "_run_bounded" in line
+ ), f"get_radeon_wheel_url runs an unbounded probe: {line.strip()}"
+
+
[email protected](not _have_timeout(), reason = "`timeout` binary not available")
[email protected]("hanging_tool", ["dpkg-query", "hipconfig", "amd-smi"])
+def test_detect_rocm_version_tag_returns_when_a_source_hangs(hanging_tool):
+ """A wedged version source must make _detect_rocm_version_tag decline, not hang the install."""
+ src = INSTALL_SH.read_text(encoding = "utf-8")
+ parts = [
+ _extract_sh_function_body(src, name)
+ for name in (
+ "_run_bounded",
+ "_rocm_tag_from_amd_smi",
+ "_rocm_tag_from_version_file",
+ "_rocm_tag_from_hipconfig",
+ "_rocm_tag_from_dpkg",
+ "_rocm_tag_from_rpm",
+ "_highest_rocm_tag",
+ "_detect_rocm_version_tag",
+ )
+ ]
+ assert all(parts)
+
+ workdir = tempfile.mkdtemp(prefix = "rocm_probe_timeout_")
+ try:
+ fake_dir = Path(workdir, "bin")
+ fake_dir.mkdir()
+ hanging = fake_dir / hanging_tool
+ hanging.write_text("#!/bin/sh\nsleep 30\n")
+ hanging.chmod(hanging.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
+
+ real_bins = {
+ Path(shutil.which(c)).parent for c in ("timeout", "awk", "grep", "sort", "tr", "sh")
+ }
+ path_env = os.pathsep.join([str(fake_dir)] + [str(p) for p in real_bins])
+
+ script = "\n".join(parts) + '\n_detect_rocm_version_tag\necho "RC=$?"\n'
+ proc = subprocess.run(
+ ["sh", "-c", script],
+ env = {"PATH": path_env},
+ stdout = subprocess.PIPE,
+ stderr = subprocess.DEVNULL,
+ text = True,
+ timeout = 25, # internal bound is 10s per probe, the fake sleeps 30s
+ )
+ assert "RC=0" in proc.stdout
+ finally:
+ shutil.rmtree(workdir, ignore_errors = True)
diff --git a/tests/studio/install/test_rocm_gfx_spoof_7331.py b/tests/studio/install/test_rocm_gfx_spoof_7331.py
index 2b326fc10e4..6de6b759f65 100644
--- a/tests/studio/install/test_rocm_gfx_spoof_7331.py
+++ b/tests/studio/install/test_rocm_gfx_spoof_7331.py
@@ -70,8 +70,10 @@ def _reset_torch_runtime_probe():
"""The torch classification is memoized for the life of an install run, so one
test's mocked probe must not leak into the next."""
stack_mod._invalidate_torch_runtime_probe()
+ stack_mod._invalidate_rocm_version_probe()
yield
stack_mod._invalidate_torch_runtime_probe()
+ stack_mod._invalidate_rocm_version_probe()
def _run_install(
diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.py
index 12c76f8276b..7bd726be985 100644
--- a/tests/studio/install/test_rocm_support.py
+++ b/tests/studio/install/test_rocm_support.py
@@ -64,11 +64,12 @@ _install_bnb_windows_rocm = stack_mod._install_bnb_windows_rocm
@pytest.fixture(autouse = True)
def _reset_torch_runtime_probe():
- """The torch classification is memoized for the life of an install run, so one
- test's mocked probe must not leak into the next."""
+ """Both probes are memoized per install run, so they must not leak between tests."""
stack_mod._invalidate_torch_runtime_probe()
+ stack_mod._invalidate_rocm_version_probe()
yield
stack_mod._invalidate_torch_runtime_probe()
+ stack_mod._invalidate_rocm_version_probe()
def _extract_sh_function_body(source: str, name: str) -> str:
@@ -93,39 +94,76 @@ def _extract_sh_function_body(source: str, name: str) -> str:
# A dpkg-query -W stand-in that renders whichever showformat string it is handed,
-# so this tests how install.sh ASKS for the version, not only how it parses the
-# answer. It answers for a package in ANY state because the real tool does: only
-# purged ones are left out, so a rocm-core removed with `apt remove` and never
-# purged keeps reporting the version it had.
+# so this tests how production ASKS for versions, not only how it parses answers.
_DPKG_QUERY_STUB = r"""#!/bin/sh
-_status='__STATUS__'
-_ver='__VERSION__'
-# dpkg's Status field is "<want> <error-flag> <status>".
-case "$_status" in installed) _want=install ;; *) _want=deinstall ;; esac
+_entries='__ENTRIES__'
_fmt=''
-_found=''
+_requested=''
+_has_rocm_core=0
+_has_hsa_runtime=0
while [ $# -gt 0 ]; do
case "$1" in
-f=*) _fmt=${1#-f=} ;;
--showformat=*) _fmt=${1#--showformat=} ;;
-f|--showformat) shift; _fmt=$1 ;;
-*) : ;;
- rocm-core) _found=1 ;;
+ rocm-core)
+ _requested="$_requested $1"
+ _has_rocm_core=1
+ ;;
+ libhsa-runtime64-1)
+ _requested="$_requested $1"
+ _has_hsa_runtime=1
+ ;;
esac
shift
done
-[ -n "$_found" ] || exit 1
+[ "$_has_rocm_core" -eq 1 ] && [ "$_has_hsa_runtime" -eq 1 ] || exit 1
[ -n "$_fmt" ] || _fmt='${Package}\t${Version}\n'
# Unrecognised fields render empty, like the real dpkg-query.
-_out=$(printf '%s' "$_fmt" | sed \
- -e "s|\${Package}|rocm-core|g" \
- -e "s|\${Status}|$_want ok $_status|g" \
- -e "s|\${db:Status-Status}|$_status|g" \
- -e "s|\${db:Status-Want}|$_want|g" \
- -e "s|\${db:Status-Eflag}|ok|g" \
- -e "s|\${Version}|$_ver|g" \
- -e "s|\${[^}]*}||g")
-printf "$_out"
+_emit() {
+ _package=$1
+ _status=$2
+ _ver=$3
+ # dpkg's Status field is "<want> <error-flag> <status>".
+ case "$_status" in installed) _want=install ;; *) _want=deinstall ;; esac
+ _out=$(printf '%s' "$_fmt" | sed \
+ -e "s|\${Package}|$_package|g" \
+ -e "s|\${Status}|$_want ok $_status|g" \
+ -e "s|\${db:Status-Status}|$_status|g" \
+ -e "s|\${db:Status-Want}|$_want|g" \
+ -e "s|\${db:Status-Eflag}|ok|g" \
+ -e "s|\${Version}|$_ver|g" \
+ -e "s|\${[^}]*}||g")
+ # Terminate the record explicitly. $(...) strips trailing newlines, so a caller
+ # whose showformat ends in a REAL newline (Python's "\n") otherwise gets every
+ # package concatenated onto one line, and a multi-package assertion silently
+ # tests only the first record. install.sh passes a literal backslash-n, which
+ # printf re-expands, so that caller just sees one blank line between records and
+ # both parsers skip those.
+ printf "$_out"
+ printf '\n'
+}
+_missing=0
+for _wanted in $_requested; do
+ _found=0
+ while IFS='|' read -r _package _status _ver; do
+ [ "$_package" = "$_wanted" ] && _found=1
+ done <<EOF
+$_entries
+EOF
+ [ "$_found" -eq 1 ] || _missing=1
+done
+# Entries, not requested-argument order, determine stdout order. This proves the
+# parser collects every valid line rather than assuming a particular package order.
+while IFS='|' read -r _package _status _ver; do
+ case " $_requested " in
+ *" $_package "*) _emit "$_package" "$_status" "$_ver" ;;
+ esac
+done <<EOF
+$_entries
+EOF
+exit "$_missing"
"""
@@ -133,9 +171,16 @@ def _write_dpkg_query_stub(
path: str,
version: str,
status: str = "installed",
+ package: str = "rocm-core",
+ packages: dict[str, tuple[str, str]] | None = None,
) -> None:
+ entries = packages or {package: (status, version)}
+ rendered_entries = "\n".join(
+ f"{name}|{entry_status}|{entry_version}"
+ for name, (entry_status, entry_version) in entries.items()
+ )
with open(path, "w", encoding = "utf-8") as f:
- f.write(_DPKG_QUERY_STUB.replace("__STATUS__", status).replace("__VERSION__", version))
+ f.write(_DPKG_QUERY_STUB.replace("__ENTRIES__", rendered_entries))
os.chmod(path, 0o755)
@@ -500,14 +545,17 @@ class TestDetectRocmVersion:
result = _detect_rocm_version()
assert result is None
+ # which() is patched to None below: the detector no longer stops at the first answer,
+ # so unpatched these read the developer's real ROCm install and CI never sees it fail.
def test_version_from_file(self, tmp_path):
"""Reads version from /opt/rocm/.info/version."""
info_dir = tmp_path / ".info"
info_dir.mkdir()
(info_dir / "version").write_text("7.1.0-12345\n")
with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path)}):
- result = _detect_rocm_version()
- assert result == (7, 1)
+ with patch("shutil.which", return_value = None):
+ result = _detect_rocm_version()
+ assert result == (7, 1)
def test_version_62(self, tmp_path):
"""Reads ROCm 6.2 version."""
@@ -515,8 +563,9 @@ class TestDetectRocmVersion:
info_dir.mkdir()
(info_dir / "version").write_text("6.2.0\n")
with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path)}):
- result = _detect_rocm_version()
- assert result == (6, 2)
+ with patch("shutil.which", return_value = None):
+ result = _detect_rocm_version()
+ assert result == (6, 2)
def test_hipconfig_fallback(self, tmp_path):
"""Falls back to hipconfig --version when file not found."""
@@ -532,17 +581,15 @@ class TestDetectRocmVersion:
def test_dpkg_fallback_without_hipconfig(self, tmp_path):
"""dpkg rocm-core fallback works when amd-smi and hipconfig are absent
(regression: a shadowing local re import raised UnboundLocalError)."""
+ dpkg = tmp_path / "dpkg-query"
+ _write_dpkg_query_stub(str(dpkg), "1:6.3.0-1")
def which(cmd):
- return "/usr/bin/dpkg-query" if cmd == "dpkg-query" else None
+ return str(dpkg) if cmd == "dpkg-query" else None
- mock_result = MagicMock()
- mock_result.returncode = 0
- mock_result.stdout = "1:6.3.0-1\n"
with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path / "nonexistent")}):
with patch("shutil.which", side_effect = which):
- with patch("subprocess.run", return_value = mock_result):
- assert _detect_rocm_version() == (6, 3)
+ assert _detect_rocm_version() == (6, 3)
def test_empty_version_file(self, tmp_path):
"""Empty version file should return None."""
@@ -560,20 +607,200 @@ class TestDetectRocmVersion:
info_dir.mkdir()
(info_dir / "version").write_text("6.2.0\n")
with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path)}):
- result = _detect_rocm_version()
- assert result == (6, 2)
+ with patch("shutil.which", return_value = None):
+ result = _detect_rocm_version()
+ assert result == (6, 2)
- def test_multiple_version_sources_first_wins(self, tmp_path):
- """When both .info/version and lib/rocm_version exist, first found wins."""
+ def test_multiple_version_sources_highest_wins(self, tmp_path):
+ """When ROCm version sources disagree, the highest valid version wins."""
info_dir = tmp_path / ".info"
info_dir.mkdir()
- (info_dir / "version").write_text("7.1.0\n")
- lib_dir = tmp_path / "lib"
- lib_dir.mkdir()
- (lib_dir / "rocm_version").write_text("6.3.0\n")
+ (info_dir / "version").write_text("5.7.0\n")
+
+ def which(cmd):
+ return "/usr/bin/hipconfig" if cmd == "hipconfig" else None
+
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = b"6.4.0\n"
+
with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path)}):
- result = _detect_rocm_version()
- assert result == (7, 1) # .info/version checked first
+ with patch("shutil.which", side_effect = which):
+ with patch("subprocess.run", return_value = mock_result):
+ assert _detect_rocm_version() == (6, 4)
+
+ def test_removed_dpkg_rocm_core_is_ignored(self, tmp_path):
+ """Removed-but-not-purged rocm-core must not report a stale version."""
+ dpkg = tmp_path / "dpkg-query"
+ _write_dpkg_query_stub(
+ str(dpkg),
+ "1:7.0.0-1",
+ "config-files",
+ )
+
+ def which(cmd):
+ return str(dpkg) if cmd == "dpkg-query" else None
+
+ with patch.dict(
+ os.environ,
+ {"ROCM_PATH": str(tmp_path / "nonexistent")},
+ ):
+ with patch("shutil.which", side_effect = which):
+ assert _detect_rocm_version() is None
+
+ def test_debian_split_runtime_uses_installed_hsa_runtime(self, tmp_path):
+ """Debian can ship hipconfig 5.7 beside HSA 6.1 with no rocm-core."""
+ hipconfig = tmp_path / "hipconfig"
+ hipconfig.write_text("#!/bin/sh\necho '5.7.31921-0'\n", encoding = "utf-8")
+ hipconfig.chmod(0o755)
+ dpkg = tmp_path / "dpkg-query"
+ _write_dpkg_query_stub(
+ str(dpkg),
+ "unused",
+ packages = {"libhsa-runtime64-1": ("installed", "1:6.1.2-2")},
+ )
+
+ def which(cmd):
+ if cmd == "hipconfig":
+ return str(hipconfig)
+ if cmd == "dpkg-query":
+ return str(dpkg)
+ return None
+
+ with patch.dict(
+ os.environ,
+ {"ROCM_PATH": str(tmp_path / "nonexistent")},
+ ):
+ with patch("shutil.which", side_effect = which):
+ assert _detect_rocm_version() == (6, 1)
+
+ def test_installed_rocm_core_outranks_the_distro_hsa_package(self, tmp_path):
+ """rocm-core wins over libhsa-runtime64-1 even when the HSA reading is HIGHER.
+ HSA is emitted first, so taking the highest reading or the first line fails this."""
+ dpkg = tmp_path / "dpkg-query"
+ _write_dpkg_query_stub(
+ str(dpkg),
+ "unused",
+ packages = {
+ "libhsa-runtime64-1": ("installed", "6.4.3+dfsg-4"),
+ "rocm-core": ("installed", "1:6.1.2-2"),
+ },
+ )
+
+ def which(cmd):
+ return str(dpkg) if cmd == "dpkg-query" else None
+
+ with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path / "nonexistent")}):
+ with patch("shutil.which", side_effect = which):
+ assert _detect_rocm_version() == (6, 1)
+
+ def test_distro_hsa_package_does_not_manufacture_a_disagreement(self, capsys, tmp_path):
+ """The real Ubuntu shape must resolve quietly, not warn on every install."""
+ dpkg = tmp_path / "dpkg-query"
+ _write_dpkg_query_stub(
+ str(dpkg),
+ "unused",
+ packages = {
+ "libhsa-runtime64-1": ("installed", "5.7.1-2build1"),
+ "rocm-core": ("installed", "7.2.1.70201-81~24.04"),
+ },
+ )
+
+ def which(cmd):
+ return str(dpkg) if cmd == "dpkg-query" else None
+
+ with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path / "nonexistent")}):
+ with patch("shutil.which", side_effect = which):
+ assert _detect_rocm_version() == (7, 2)
+ assert "ROCm version sources disagree" not in capsys.readouterr().err
+
+ def test_removed_dpkg_hsa_runtime_is_ignored(self, tmp_path):
+ """Removed-but-not-purged HSA runtime must not report a stale version."""
+ dpkg = tmp_path / "dpkg-query"
+ _write_dpkg_query_stub(
+ str(dpkg),
+ "unused",
+ packages = {"libhsa-runtime64-1": ("config-files", "1:7.0.0-1")},
+ )
+
+ def which(cmd):
+ return str(dpkg) if cmd == "dpkg-query" else None
+
+ with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path / "nonexistent")}):
+ with patch("shutil.which", side_effect = which):
+ assert _detect_rocm_version() is None
+
+ def test_disagreeing_sources_emit_one_warning(self, tmp_path, capsys):
+ """A real disagreement warns once and names the highest selected version."""
+ info_dir = tmp_path / ".info"
+ info_dir.mkdir()
+ (info_dir / "version").write_text("5.7.0\n", encoding = "utf-8")
+
+ def which(cmd):
+ return "/usr/bin/hipconfig" if cmd == "hipconfig" else None
+
+ hipconfig = MagicMock(returncode = 0, stdout = b"6.1.0\n")
+ with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path)}):
+ with patch("shutil.which", side_effect = which):
+ with patch("subprocess.run", return_value = hipconfig):
+ assert _detect_rocm_version() == (6, 1)
+ stderr = capsys.readouterr().err
+ assert stderr.count("ROCm version sources disagree") == 1
+ assert "using the highest, rocm6.1" in stderr
+
+ def test_agreeing_sources_emit_no_disagreement_warning(self, tmp_path, capsys):
+ """Multiple valid sources that agree stay quiet."""
+ info_dir = tmp_path / ".info"
+ info_dir.mkdir()
+ (info_dir / "version").write_text("6.1.0\n", encoding = "utf-8")
+
+ def which(cmd):
+ return "/usr/bin/hipconfig" if cmd == "hipconfig" else None
+
+ hipconfig = MagicMock(returncode = 0, stdout = b"6.1.0\n")
+ with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path)}):
+ with patch("shutil.which", side_effect = which):
+ with patch("subprocess.run", return_value = hipconfig):
+ assert _detect_rocm_version() == (6, 1)
+ assert "ROCm version sources disagree" not in capsys.readouterr().err
+
+ def test_detection_is_memoized_so_the_warning_prints_once(self, tmp_path, capsys):
+ """_ensure_rocm_torch() runs twice on Linux, so the sources must be probed once."""
+ info_dir = tmp_path / ".info"
+ info_dir.mkdir()
+ (info_dir / "version").write_text("5.7.0\n", encoding = "utf-8")
+ calls = []
+
+ def which(cmd):
+ return "/usr/bin/hipconfig" if cmd == "hipconfig" else None
+
+ def run(cmd, *a, **kw):
+ calls.append(cmd)
+ return MagicMock(returncode = 0, stdout = b"6.1.0\n")
+
+ with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path)}):
+ with patch("shutil.which", side_effect = which):
+ with patch("subprocess.run", side_effect = run):
+ assert _detect_rocm_version() == (6, 1)
+ probes_after_first = len(calls)
+ assert _detect_rocm_version() == (6, 1)
+ assert (
+ len(calls) == probes_after_first
+ ), f"second call re-probed: {calls[probes_after_first:]}"
+ assert capsys.readouterr().err.count("ROCm version sources disagree") == 1
+
+ def test_memo_reset_reprobes(self, tmp_path):
+ """The invalidator must actually clear the memo, or the autouse fixture is a no-op."""
+ info_dir = tmp_path / ".info"
+ info_dir.mkdir()
+ (info_dir / "version").write_text("6.1.0\n", encoding = "utf-8")
+ with patch.dict(os.environ, {"ROCM_PATH": str(tmp_path)}):
+ with patch("shutil.which", return_value = None):
+ assert _detect_rocm_version() == (6, 1)
+ (info_dir / "version").write_text("7.0.0\n", encoding = "utf-8")
+ assert _detect_rocm_version() == (6, 1)
+ stack_mod._invalidate_rocm_version_probe()
+ assert _detect_rocm_version() == (7, 0)
def test_hipconfig_multiline_output(self, tmp_path):
"""hipconfig with multi-line output -- should use first line."""
@@ -2372,6 +2599,49 @@ class TestInstallShStructure:
f"but detection resolved {r.stdout.strip()}"
)
+ def test_debian_split_runtime_uses_installed_hsa_runtime_package(self):
+ """Debian 13 may have hipconfig 5.7, HSA runtime 6.1, and no rocm-core."""
+ shell = shutil.which("bash")
+ if not shell:
+ pytest.skip("bash needed to execute the version chain")
+ source = (PACKAGE_ROOT / "install.sh").read_text(encoding = "utf-8")
+
+ with tempfile.TemporaryDirectory() as d:
+ rocm_prefix = os.path.join(d, "rocm")
+ script_body = self._rocm_version_detection_script(source, rocm_prefix)
+
+ hipconfig = os.path.join(d, "hipconfig")
+ with open(hipconfig, "w", encoding = "utf-8") as f:
+ f.write("#!/bin/sh\necho '5.7.31921-0'\n")
+ os.chmod(hipconfig, 0o755)
+
+ _write_dpkg_query_stub(
+ os.path.join(d, "dpkg-query"),
+ "1:6.1.2-2",
+ "installed",
+ package = "libhsa-runtime64-1",
+ )
+
+ for name in ("amd-smi", "rpm"):
+ p = os.path.join(d, name)
+ with open(p, "w", encoding = "utf-8") as f:
+ f.write("#!/bin/sh\nexit 1\n")
+ os.chmod(p, 0o755)
+
+ script = "set -euo pipefail\n" + script_body + '\nprintf "TAG:%s\\n" "$_rocm_tag"\n'
+ env = dict(
+ os.environ,
+ PATH = d + os.pathsep + os.environ.get("PATH", ""),
+ )
+ r = subprocess.run(
+ [shell, "-c", script],
+ env = env,
+ capture_output = True,
+ text = True,
+ )
+ assert r.returncode == 0, r.stderr
+ assert r.stdout.strip() == "TAG:rocm6.1", r.stdout
+
def test_removed_dpkg_rocm_core_cannot_pick_the_wheels(self):
"""Highest-wins fixed the undershoot in #8402 and opened the symmetric
hole: a source reading HIGHER than the runtime now wins outright.
@@ -2467,7 +2737,7 @@ class TestInstallShStructure:
"""install.sh should strip Debian epoch prefix from dpkg-query output."""
sh_path = PACKAGE_ROOT / "install.sh"
source = sh_path.read_text(encoding = "utf-8")
- assert "sed 's/^[0-9]*://' " in source or "sed 's/^[0-9]*://'" in source
+ assert 'sub(/^[0-9]+:/, "", v)' in source
def test_no_double_bracket_in_rocm_block(self):
"""ROCm block must not use bash-only [[ ]] (POSIX char classes [[:space:]] are fine)."""