unsloth/tests/studio/test_ci_shell_suite_coverage.py
Leo Borcherding 3ea6d14c39
AMD: CI coverage for recent fixes, plus three wrong gfx ids (#7431)
* ROCm/AMD CI coverage: arch-table parity, native-Linux lib prepend, RDNA4 grouped_mm, discovery-based shell suite

Three merged ROCm fixes shipped without tests, and the CI wiring that
would have run them was gated on files the fixes do not touch.

Tests added (113):
  tests/studio/install/test_rocm_arch_table_parity.py (27)
    diffs the four duplicated gfx -> AMD pip-index tables across
    install.sh, install.ps1, studio/setup.ps1 and install_python_stack.py,
    plus the GPU-name -> arch tables and the torch 2.11 pin allowlist.
  tests/studio/install/test_rocm_native_linux_lib_dirs.py (26)
    covers #7233: system-ROCm lib dirs prepended ahead of bundled
    libggml-hip, the /dev/kfd + not-WSL + libhsa gate, the opt-out env
    var, root resolution order, and source parity between the two copies.
  studio/backend/tests/test_grouped_mm_rdna4_fallback.py (46)
    covers #7292: registration on the CUDA dispatch key, grouped and
    ungrouped numerics, bias/dtype promotion, and the Linux HIP<7.13 +
    RDNA4 name gate, executed from the shipped source rather than a copy.
  tests/studio/test_ci_shell_suite_coverage.py (14)
    fails if either shell runner goes back to a hardcoded list or skips
    a file without a recorded reason.

CI wiring:
  studio-backend-ci.yml: add install.sh / install.ps1 to the path filter
    (the suites it runs assert against those two files, so install-only
    changes -- the shape most AMD/ROCm routing fixes take -- skipped it),
    and replace the 13-file hardcoded shell list with directory
    discovery. That list had fallen seven files behind, including
    test_strixhalo_wsl_reroute.sh, the only shell coverage of the ROCm
    WSL reroute, which had never run on a PR.
  tests/run_all.sh: same discovery loop so local and CI agree.

* Test review fixes: assert on outcomes, not on the code under test

Self-review of the previous commit found four tests that passed for the
wrong reason.

1. The arch-table parity test pinned expected gfx ids copied out of the
   shipped tables, which enshrined three upstream inaccuracies as
   correct: RX 9070 (non-XT) is gfx1201 not gfx1200, RX 7800 XT is
   gfx1101 not gfx1100, and PRO V710 is gfx1101 not gfx1102 per AMD's
   ROCm compatibility matrix. The expectation is now the AMD pip index
   leaf -- the thing the tables exist to produce, and what a wrong
   answer costs the user. The three known drifts are listed explicitly
   with a test asserting they stay cosmetic, i.e. that the wrong and
   right ids still map to the same wheel index. That test turns red the
   day one of them starts routing users to the wrong wheel.

2. The RDNA4 device-name test extracted the regex from worker.py and
   then matched with it, so it could not fail. Widening the pattern --
   the dangerous edit, since it forces the slow Python mm fallback onto
   RDNA3 users -- would have been silently accepted. It now reads the
   live pattern and checks it against fixed cases, plus asserts the
   name match stays guarded by `not _lin_arch` and that the name is
   lowercased before matching.

3. The CI-coverage test matched a verbatim line of studio-backend-ci.yml,
   so reindenting the step would fail the build while a real regression
   to a hardcoded list could slip past a reformat. It now parses the
   YAML, finds the step by name, and asserts on the glob plus the
   absence of individual filenames. The path-filter test likewise reads
   the parsed trigger instead of scanning raw text.

4. A set comprehension in the parity helper had a ternary whose branches
   were identical.

Mutation-tested: widening the RDNA4 regex, desyncing one copy of the
name table, dropping install.sh from the path filter, and re-skipping
the ROCm WSL shell suite each fail at least two tests. Verified on
Linux (WSL Ubuntu 24.04) with CI's torch pin: 86 + 48 pass.

* Fix three wrong gfx ids in the GPU-name arch tables

The name -> gfx tables disagreed with AMD's ROCm compatibility matrix on
three entries. Corrected against the "Radeon GPU" list at
rocm.docs.amd.com/en/latest/compatibility/compatibility-matrix.html:

  RX 9070, RX 9070 GRE   gfx1200 -> gfx1201   (Navi 48, same die as the XT)
  RX 7800 XT, RX 7700 XT gfx1100 -> gfx1101   (Navi 32, not Navi 31)
  PRO W7700              gfx1100 -> gfx1101
  PRO V710               gfx1102 -> gfx1101   (Navi 32, not Navi 33)

No wheel changes for anyone: gfx1200/gfx1201 both resolve to gfx120X-all
and gfx1100/gfx1101/gfx1102 all resolve to gfx110X-all, in all four copies
of the index-family map. That collapse is why the errors survived being
copied into six places -- the leaf-level tests could not see them.

It was not purely cosmetic, though. install.sh's second copy feeds
"Tip: set UNSLOTH_ROCM_GFX_ARCH=<arch>", so a 7800 XT user following the
printed advice exported gfx1100 and made a wrong id authoritative for
every later run. It would also have become a real misroute the moment AMD
split a family across index leaves, as they already do for gfx1151/gfx1150.

Fixed in all six places, which is two more than the table's own "kept in
sync with" comments claim exist:

  install.sh   _infer_amd_gfx_arch_from_gpu_name
  install.sh   case "$_gpu_disp_mkt"          (banner + env tip; undocumented)
  studio/setup.sh
  install.ps1
  studio/setup.ps1
  studio/install_python_stack.py

Ordering is preserved: the gfx1102 arm still precedes gfx1101 in the shell
copies so "RX 7700S" cannot fall onto the "RX 7700" glob, and the
PowerShell copies keep the (?!S) lookahead.

Test changes:
  - test_rocm_arch_table_parity.py gains _AMD_DOCUMENTED_ARCH, exact gfx
    ids transcribed from AMD rather than from the tables. Agreement between
    six copies proves nothing when all six were transcribed from the same
    mistake, so the ground truth has to come from outside. Verified it
    catches the bug: against the pre-fix tables it fails 6 tests.
  - The parity check now covers all six copies. It had four; the two
    install.sh copies were being treated as one, and
    _WIN_GPU_NAME_ARCH_TABLE was not checked at all.
  - test_rocm_support.py's TestGfxArchNameFallback pinned two of the wrong
    ids as expected values; updated, and extended with a 9060 XT and a
    7900 XTX case so each RDNA3/4 die is represented.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Guard against unregistered copies of the GPU-name arch table

Counting the copies by hand is what let them drift: the in-code "kept in
sync with" comments claimed four, the arch-id fix found six, and scanning
the tree turns up a seventh.

TestNoUnregisteredArchTable rediscovers the copies from the source tree
instead of trusting a hand-maintained list. A table line is one that names
a card and gives its arch; real tables score 9-17 such lines and the only
other hits in the repo are two single-line prose comments, so the
three-line threshold is not load-bearing. A companion test asserts the
scan still finds the known copies, so the heuristic cannot go blind and
pass by finding nothing.

The seventh copy is tests/_zoo_rocm_spoof.py, the fixture other ROCm tests
build their fake AMD host from. It states the mapping backwards (gfx ->
the name torch should report), which makes it an independent witness: it
had gfx1101 -> RX 7800 XT and gfx1201 -> RX 9070 XT right while all six
installer copies were wrong, and nothing compared the two. Now they are
round-tripped against each other.

RX 6700 XT is pinned as a known divergence rather than normalised. AMD's
compatibility matrix documents no consumer RX 6000 card and no gfx1031 at
all, the installer arm is commented "gfx103X family", and gfx1031 appears
only as an index-family key, never as a value a name table emits. With no
external source to correct against, changing shipped behaviour would be
guesswork. A test fails if the divergence ever disappears, so the
exemption cannot go stale.

Also adds the reverse of the AMD-matrix check: a documented card that
matches no arm anywhere is a silent CPU fallback rather than a wrong id.
This cannot detect hardware nobody transcribed, which would need a live
fetch of AMD's matrix and a non-hermetic suite; the docstring says so
rather than implying coverage that is not there.

Verified on Linux: 478 passed, plus all five new guards mutation-tested
to confirm each fails when its invariant is broken.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Docstring said six copies; the list under it now has seven

* tests: run discovered shell tests with bash, not sh

tests/run_all.sh discovered tests/sh/ instead of listing files, but still
invoked each one with sh. Every file there declares a bash shebang, and on
Debian/Ubuntu /bin/sh is dash: test_apt_distro_prompt.sh,
test_studio_home_node_dir.sh and test_with_llama_cpp_dir_link_behavior.sh
fail on bashisms under dash and pass under bash. The old hand-written list
happened to name only dash-clean files, so switching to discovery is what
surfaced it. Backend CI already used bash, so this was a local-only break.

Guarded by a new test asserting both runners invoke tests/sh/ with bash.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix Krackan Point (Radeon 860M/840M) routed to the gfx1150 wheel index

The GPU-name tables map 860M/840M and the Ryzen AI 7 350 / AI 5 340 CPU
strings to gfx1150, but Krackan Point is gfx1152. AMD's own lemonade table
(src/cpp/server/system_info.cpp) maps both Krackan iGPUs to gfx1152.

Unlike the three ids already fixed here, this one is not wheel-neutral:
repo.amd.com publishes gfx1150 and gfx1152 as separate index leaves with
separately built torch wheels, so these laptops were installing wheels
built for a different LLVM target. gfx1152 was absent from the codebase
entirely, so it needed the index-family maps, the torch 2.11 floor lists
(same _grouped_mm bug as gfx1150/1151), the Strix reroute set and the
Windows arch allowlist as well as the seven name tables.

The parity test added in this PR did not catch it because its AMD-matrix
expectations stopped at 890M/880M. Added the APU rows, so the case that
actually changes a wheel is now covered: reverting the tables fails 9
tests naming 860M, 840M and Krackan.

gfx1153 (Ryzen AI 5 430 era) is left alone; AMD publishes no gfx1153
wheel family, so there is nothing to route it to.

Verified: bash -n on both shell installers, PowerShell AST parse on both
.ps1 files, python ast.parse on all touched modules, install suite 1334
passed with no new failures against main, shell suite 20 files.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add gfx1152 to unified-memory classifiers, make parity allowlist set-based

Krackan Point (gfx1152, Radeon 860M/840M) is the third RDNA 3.5 APU and
shares one GPU/system-RAM pool exactly like Strix Point (gfx1150) and
Strix Halo (gfx1151), but only the installers knew about it. The two
runtime classifiers still had two-element arch sets, so a Krackan laptop
got the 0.90 discrete headroom factor on a shared pool and ran llama.cpp
without GGML_CUDA_ENABLE_UNIFIED_MEMORY.

- worker.py _rocm_classify_unified_memory: add gfx1152 to the arch set,
  and 860m/840m to the device-name fallback. The NVIDIA GeForce 840M
  cannot collide there: the function is only reached under _hw.IS_ROCM.
- llama_cpp.py _amd_apu_wants_unified_memory: add gfx1152 to the arch set.
- Tests for both, including the :sramecc-:xnack- suffix form.

TestGfx211AllowlistParity compared four hardcoded allowlist strings, so
adding gfx1152 to all four installers correctly turned three assertions
red without any installer actually disagreeing with another. Each test
now extracts the set its installer holds and compares it to one EXPECTED
constant. Order and spacing are free, membership is not, and the next
leaf is a one-line edit instead of four.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
2026-07-25 18:58:02 -05:00

197 lines
8.7 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Guards that the installer test suites actually run on a PR.
Two ways coverage went missing without anyone noticing:
1. Backend CI ran a hardcoded list of tests/sh/*.sh files. New tests were added
to the directory and never to the list, so by the time this was written the
list was seven files behind -- including test_strixhalo_wsl_reroute.sh, the
only shell coverage of the ROCm WSL reroute, which had never run on a PR.
tests/run_all.sh, the local entrypoint, had drifted the other way.
2. Backend CI's path filter did not include install.sh / install.ps1, while a
large share of the suites it runs (tests/sh/*, tests/studio/install/*) assert
against exactly those two files. An install-only change -- the shape most
AMD/ROCm routing fixes take, e.g. #7277 / #7293 / #7300 -- skipped the
workflow that tests it.
Both are now discovery-based. These tests fail if either reverts to a list, if a
shell test lands somewhere the discovery cannot see it, or if a skip is added
without a reason next to it.
"""
import re
from pathlib import Path
import pytest
import yaml
REPO_ROOT = Path(__file__).resolve().parents[2]
_WORKFLOWS = REPO_ROOT / ".github" / "workflows"
_BACKEND_CI = _WORKFLOWS / "studio-backend-ci.yml"
_PARITY_CI = _WORKFLOWS / "cross-platform-parity-ci.yml"
_RUN_ALL = REPO_ROOT / "tests" / "run_all.sh"
_SH_DIR = REPO_ROOT / "tests" / "sh"
# Files deliberately not run by the auto-discovered Backend CI step. Each needs
# a reason here AND in the workflow; anything else in tests/sh must run.
_EXPECTED_CI_SKIPS = {
"test_install_host_defaults.sh": "asserts an install.ps1 layout that has drifted",
"test_install_rollback_lifecycle.sh": "runs on both platforms in cross-platform-parity-ci.yml",
}
def _backend_ci() -> dict:
return yaml.safe_load(_BACKEND_CI.read_text(encoding = "utf-8"))
def _shell_step_script() -> str:
"""The `run:` body of the shell-installer step, located by name through the
parsed YAML rather than by slicing the raw file."""
for job in _backend_ci()["jobs"].values():
for step in job.get("steps", []):
if step.get("name") == "Shell installer tests":
return step["run"]
raise AssertionError("Backend CI has no 'Shell installer tests' step")
def _shell_test_files():
files = sorted(p.name for p in _SH_DIR.glob("test_*.sh"))
assert files, "tests/sh has no test_*.sh files -- did the directory move?"
return files
def _skip_list(source: str) -> set[str]:
"""The skip= / SH_SKIP= line from a discovery loop."""
m = re.search(r"^\s*(?:skip|SH_SKIP)=\"([^\"]*)\"", source, re.MULTILINE)
assert m, "no skip list found; the discovery loop must declare one (even if empty)"
return {name for name in m.group(1).split() if name}
class TestBackendCiRunsEveryShellTest:
def test_step_discovers_the_directory_instead_of_listing_files(self):
"""Matched against the parsed step script, and on the glob rather than a
verbatim line, so reformatting the loop does not turn CI red -- only
going back to a hardcoded list does."""
script = _shell_step_script()
assert re.search(r"for\s+\w+\s+in\s+tests/sh/test_\*\.sh", script), (
"Backend CI must glob tests/sh; a hardcoded list is how the ROCm WSL "
f"suite went unrun for months. Step script was:\n{script}"
)
listed = re.findall(r"tests/sh/test_[a-z0-9_]+\.sh", script)
assert not listed, f"Backend CI still names individual shell tests: {sorted(set(listed))}"
def test_step_fails_loudly_if_discovery_finds_nothing(self):
"""A moved directory must break the build, not pass vacuously."""
assert "no shell tests discovered under tests/sh" in _shell_step_script()
def test_every_shell_test_runs_or_is_a_known_skip(self):
skips = _skip_list(_shell_step_script())
unexpected = skips - set(_EXPECTED_CI_SKIPS)
assert not unexpected, (
f"Backend CI skips {sorted(unexpected)} without a reason recorded in "
"_EXPECTED_CI_SKIPS; add one or stop skipping it"
)
# Everything else in the directory is covered by the glob.
for name in _shell_test_files():
assert name not in skips or name in _EXPECTED_CI_SKIPS, name
def test_skip_entries_are_not_stale(self):
"""A skip for a deleted file quietly widens next time a name is reused."""
existing = set(_shell_test_files())
for name in _skip_list(_shell_step_script()):
assert name in existing, f"{name} is skipped but no longer exists in tests/sh"
def test_each_skip_is_documented_in_the_workflow(self):
source = _BACKEND_CI.read_text(encoding = "utf-8")
for name in _EXPECTED_CI_SKIPS:
assert (
source.count(name) >= 2
), f"{name} is skipped in Backend CI without a comment explaining why"
def test_rollback_lifecycle_really_does_run_elsewhere(self):
"""The one skip justified by 'another workflow covers it' must be true."""
assert "tests/sh/test_install_rollback_lifecycle.sh" in _PARITY_CI.read_text(
encoding = "utf-8"
)
def test_rocm_shell_suite_is_in_scope(self):
"""The suite whose absence prompted this file: it must exist and be
picked up (i.e. not skipped)."""
assert "test_strixhalo_wsl_reroute.sh" in _shell_test_files()
assert "test_strixhalo_wsl_reroute.sh" not in _skip_list(_shell_step_script())
class TestRunAllMatchesCi:
"""tests/run_all.sh is what a contributor runs before pushing. If it and CI
disagree, one of them is lying about the state of the tree."""
def test_run_all_discovers_the_directory(self):
source = _RUN_ALL.read_text(encoding = "utf-8")
assert 'for _t in "$TESTS_DIR"/sh/test_*.sh; do' in source
def test_run_all_invokes_the_tests_with_bash(self):
"""Both runners must use the interpreter the tests declare. Every file
under tests/sh/ has a bash shebang, and on Debian/Ubuntu /bin/sh is
dash, under which three of them fail on bashisms. Running them with sh
would fail the suite locally for reasons CI never reproduces."""
source = _RUN_ALL.read_text(encoding = "utf-8")
assert 'bash "$_t"' in source, "tests/run_all.sh must run tests/sh/ with bash"
assert 'sh "$_t"' not in source.replace(
'bash "$_t"', ""
), "tests/run_all.sh still invokes a discovered test with sh"
assert 'bash "$s"' in _shell_step_script(), "Backend CI must run tests/sh/ with bash"
def test_run_all_skips_are_a_subset_of_ci_skips(self):
local = _skip_list(_RUN_ALL.read_text(encoding = "utf-8"))
unexpected = local - set(_EXPECTED_CI_SKIPS)
assert not unexpected, (
f"tests/run_all.sh skips {sorted(unexpected)} that CI still runs: a "
"contributor would see green locally and red on the PR"
)
class TestBackendCiPathFilters:
"""The workflow has to fire on the files its tests assert against."""
def _paths(self) -> set[str]:
"""Read the real trigger through the YAML parser. `on:` is a YAML 1.1
boolean, so pyyaml keys it as True."""
wf = _backend_ci()
triggers = wf.get("on", wf.get(True))
assert triggers, "Backend CI has no trigger block"
paths = triggers["pull_request"]["paths"]
assert paths, "Backend CI pull_request trigger has no paths filter"
return set(paths)
@pytest.mark.parametrize(
"path,why",
[
("install.sh", "tests/sh/* and tests/studio/install/* assert against it"),
("install.ps1", "the Windows/ROCm arch tables and pin allowlist live here"),
("studio/**", "covers studio/setup.sh, studio/setup.ps1, install_python_stack.py"),
("tests/**", "test-only changes must run the tests they touch"),
],
)
def test_trigger_covers(self, path, why):
assert path in self._paths(), f"Backend CI does not run when {path} changes ({why})"
def test_installer_change_would_trigger_the_workflow(self):
"""End to end: the exact filenames the ROCm fixes edit."""
paths = self._paths()
for changed in ("install.sh", "install.ps1"):
assert changed in paths
for changed in ("studio/setup.ps1", "studio/setup.sh", "studio/install_python_stack.py"):
assert any(
changed.startswith(pattern.rstrip("*").rstrip("/"))
for pattern in paths
if pattern.endswith("/**")
), f"nothing in the path filter matches {changed}"
if __name__ == "__main__":
pytest.main([__file__, "-v"])