Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion .claude/skills/validate-kernel-pr/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ The supplied worktree must be clean. The report records the base commit, patch S
caller-supplied head OID. A direct head checkout without a patch can run diagnostics, but cannot
prove mergeability or base attribution and therefore cannot produce `PASS`.

The patch is reverted when the process exits, including on interrupt and on every degraded path,
so the worktree is handed back in the state it was supplied. Consecutive runs in the same worktree
are therefore supported; a run that left the patch applied would make the next one report
`not isolated-clean` and blame the caller.

### 2 — `gpu_claim`

Claim a GPU over a **sampling window**, not one instantaneous reading, and acquire a non-blocking
Expand All @@ -111,9 +116,18 @@ The report records host, HIP index, matching AMD SMI index, BDF, market name, ar
GFX activity before the run. `pick-idle-gpu.py` emits the **translated HIP index**; the validator
maps it back through AMD SMI enumeration instead of incorrectly using it as an AMD SMI index.

`amdsmi_get_gpu_activity` is not available everywhere — some driver and amd-smi combinations fail
it outright or report `N/A` while enumeration, BDF, ASIC and VRAM queries all work. Activity is
therefore treated as optional, and `gpu_claim.idleness_basis` names the evidence the claim rests
on: `activity+vram` when busy percentages were measured, `vram-only` when only resident VRAM
separated the devices. In the `vram-only` case `gfx_activity_before_pct` is `null`, which means
unknown, not zero — an unavailable metric is never reported as an observed idle GPU.

If no GPU stays idle, `gpu_claim` is `skip`, `degraded_mode` is `NO_GPU`, both correctness stages
are `skip`, and the verdict is `INCONCLUSIVE`. The script performs no architecture-specific
compile in this branch, so it does not call the result `compile-only`.
compile in this branch, so it does not call the result `compile-only`. That skip distinguishes two
different facts: GPUs present but none idle is an environment fact, whereas AMD SMI being
unqueryable is a portability gap in the validator and says nothing about the GPUs.

### 3 — `runtime_compat`

Expand Down
114 changes: 86 additions & 28 deletions .claude/skills/validate-kernel-pr/pick-idle-gpu.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
#!/usr/bin/env python3
"""Select an AMD GPU that stays idle across a sampling window."""

from __future__ import annotations

import argparse
import os
import sys
import time
from pathlib import Path

ACTIVITY_BASIS = "activity+vram"
VRAM_ONLY_BASIS = "vram-only"


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
Expand All @@ -24,26 +29,60 @@ def parse_args() -> argparse.Namespace:
return args


def amdsmi_search_paths() -> list[Path]:
"""Directories that have shipped the amdsmi bindings across ROCm releases."""
roots = [Path(os.environ["ROCM_PATH"])] if os.environ.get("ROCM_PATH") else []
roots.append(Path("/opt/rocm"))
roots.extend(sorted(Path("/opt").glob("rocm-*"), reverse=True))

candidates = [
Path("/usr/lib/python3/dist-packages"),
Path(
f"/usr/lib/python{sys.version_info.major}.{sys.version_info.minor}/dist-packages"
),
]
for root in roots:
# ROCm >= 7.1 ships the bindings under share/amd_smi; older builds put
# them next to the CLI. Probe both, newest ROCm first.
candidates.append(root / "share" / "amd_smi")
candidates.append(root / "libexec" / "amdsmi_cli")
return candidates


def import_amdsmi():
try:
import amdsmi

return amdsmi
except ImportError:
for candidate in (
Path("/usr/lib/python3/dist-packages"),
Path(
f"/usr/lib/python{sys.version_info.major}.{sys.version_info.minor}/dist-packages"
),
Path("/opt/rocm/libexec/amdsmi_cli"),
):
for candidate in amdsmi_search_paths():
if candidate.is_dir() and str(candidate) not in sys.path:
sys.path.append(str(candidate))
import amdsmi

return amdsmi


def read_activity(amdsmi, handle) -> tuple[int | None, int | None]:
"""Return (gfx, umc) busy percentages, or None for whichever is unknown.

Some driver and amd-smi combinations fail this query outright (MI308X on
ROCm 7.0 raises AMDSMI_STATUS_UNEXPECTED_DATA) or report "N/A". Both mean
unknown, which must stay distinct from a measured 0 -- reporting unknown as
idle would claim an idleness that was never observed.
"""
try:
activity = amdsmi.amdsmi_get_gpu_activity(handle)
except (OSError, amdsmi.AmdSmiException):
return None, None
gfx = activity.get("gfx_activity")
umc = activity.get("umc_activity")
return (
gfx if isinstance(gfx, int) else None,
umc if isinstance(umc, int) else None,
)


def sample(amdsmi, count: int, interval: float) -> tuple[list[dict], int]:
gpus = []
for smi_index, handle in enumerate(amdsmi.amdsmi_get_processor_handles()):
Expand All @@ -64,14 +103,12 @@ def sample(amdsmi, count: int, interval: float) -> tuple[list[dict], int]:
time.sleep(interval)
busy = 0
for gpu in gpus:
activity = amdsmi.amdsmi_get_gpu_activity(gpu["handle"])
gfx = activity.get("gfx_activity")
umc = activity.get("umc_activity")
gfx = gfx if isinstance(gfx, int) else 0
umc = umc if isinstance(umc, int) else 0
gpu["gfx"].append(gfx)
gpu["umc"].append(umc)
busy += int(gfx > 5)
gfx, umc = read_activity(amdsmi, gpu["handle"])
if gfx is not None:
gpu["gfx"].append(gfx)
busy += int(gfx > 5)
if umc is not None:
gpu["umc"].append(umc)
peak_concurrent = max(peak_concurrent, busy)
for gpu in gpus:
memory = amdsmi.amdsmi_get_gpu_vram_usage(gpu["handle"])
Expand All @@ -81,9 +118,11 @@ def sample(amdsmi, count: int, interval: float) -> tuple[list[dict], int]:
{
"used_gib": used,
"free_gib": total - used,
"peak_gfx": max(gpu["gfx"]),
"mean_gfx": sum(gpu["gfx"]) / len(gpu["gfx"]),
"peak_umc": max(gpu["umc"]),
"peak_gfx": max(gpu["gfx"]) if gpu["gfx"] else None,
"mean_gfx": (
sum(gpu["gfx"]) / len(gpu["gfx"]) if gpu["gfx"] else None
),
"peak_umc": max(gpu["umc"]) if gpu["umc"] else None,
}
)
del gpu["handle"]
Expand Down Expand Up @@ -111,14 +150,17 @@ def main() -> int:
gpu
for gpu in gpus
if gpu["hip_index"] is not None
and gpu["peak_gfx"] <= args.max_busy
and (gpu["peak_gfx"] is None or gpu["peak_gfx"] <= args.max_busy)
and gpu["used_gib"] <= args.max_used_gib
and gpu["free_gib"] >= args.min_free_gib
]
# Prefer GPUs whose idleness was actually measured over ones where the
# activity query failed and only VRAM could be checked.
eligible.sort(
key=lambda gpu: (
gpu["peak_gfx"],
gpu["mean_gfx"],
gpu["peak_gfx"] is None,
gpu["peak_gfx"] or 0,
gpu["mean_gfx"] or 0.0,
gpu["used_gib"],
-gpu["free_gib"],
)
Expand All @@ -137,19 +179,24 @@ def main() -> int:
for gpu in sorted(gpus, key=lambda item: item["smi_index"]):
if gpu["hip_index"] is None:
verdict = "SKIP no hip_id"
elif gpu["peak_gfx"] > args.max_busy:
elif gpu["peak_gfx"] is not None and gpu["peak_gfx"] > args.max_busy:
verdict = f"BUSY peaked {gpu['peak_gfx']}%"
elif gpu["used_gib"] > args.max_used_gib:
verdict = f"HELD {gpu['used_gib']:.1f} GiB used"
elif gpu["free_gib"] < args.min_free_gib:
verdict = f"FULL {gpu['free_gib']:.1f} GiB free"
elif gpu["peak_gfx"] is None:
verdict = "idle by VRAM only (activity unavailable)"
else:
verdict = "idle"
hip_index = "-" if gpu["hip_index"] is None else gpu["hip_index"]
peak_gfx = "n/a" if gpu["peak_gfx"] is None else str(gpu["peak_gfx"])
mean_gfx = "n/a" if gpu["mean_gfx"] is None else f"{gpu['mean_gfx']:.1f}"
peak_umc = "n/a" if gpu["peak_umc"] is None else str(gpu["peak_umc"])
print(
f"{gpu['smi_index']:>4} {hip_index:>4} {gpu['bdf']:<14} "
f"{gpu['peak_gfx']:>6} {gpu['mean_gfx']:>6.1f} "
f"{gpu['peak_umc']:>5} {gpu['used_gib']:>6.1f} GiB "
f"{peak_gfx:>6} {mean_gfx:>6} "
f"{peak_umc:>5} {gpu['used_gib']:>6.1f} GiB "
f"{gpu['free_gib']:>6.1f} GiB {verdict}",
file=sys.stderr,
)
Expand All @@ -161,12 +208,23 @@ def main() -> int:
)

if not eligible:
print(
"No GPU stayed below the activity and resident-memory thresholds.",
file=sys.stderr,
)
if all(gpu["peak_gfx"] is None for gpu in gpus):
print(
"No GPU stayed below the resident-memory thresholds; GPU activity "
"is unavailable on this host, so only VRAM was considered.",
file=sys.stderr,
)
else:
print(
"No GPU stayed below the activity and resident-memory thresholds.",
file=sys.stderr,
)
return 1
selected = eligible[0]
basis = ACTIVITY_BASIS if selected["peak_gfx"] is not None else VRAM_ONLY_BASIS
# Machine-readable and deliberately outside the --quiet guard: callers record
# this so a report never presents a VRAM-only claim as a measured-idle one.
print(f"idleness-basis: {basis}", file=sys.stderr)
if not args.quiet:
print(
f"Chose HIP index {selected['hip_index']} "
Expand Down
5 changes: 5 additions & 0 deletions .claude/skills/validate-kernel-pr/report_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,11 @@
"model": { "type": "string" },
"arch": { "type": "string" },
"bdf": { "type": "string" },
"idleness_basis": {
"type": "string",
"enum": ["activity+vram", "vram-only", "unknown"],
"description": "Evidence the idleness claim rests on. 'vram-only' means the activity API was unavailable, so a null gfx_activity_before_pct is unknown rather than a measured zero."
},
"gfx_activity_before_pct": { "type": ["integer", "null"] },
"gfx_activity_after_pct": { "type": ["integer", "null"] },
"host": { "type": "string" }
Expand Down
47 changes: 40 additions & 7 deletions .claude/skills/validate-kernel-pr/validate_pr.sh
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,11 @@ for item in data["findings"]:
PY
}

# Two independent facts about the supplied worktree:
# BASE_ACTIVE=1 the patch is currently reversed out, i.e. we are mid-baseline-run
# PATCH_APPLIED=1 this process applied the patch and still owes the caller a revert
BASE_ACTIVE=0
PATCH_APPLIED=0
restore_head() {
if [ "$BASE_ACTIVE" -eq 0 ]; then
return 0
Expand All @@ -286,8 +290,20 @@ restore_head() {
return 1
}
cleanup() {
if [ "$PATCH_APPLIED" -eq 0 ]; then
return
fi
if [ "$BASE_ACTIVE" -eq 1 ]; then
restore_head || echo "failed to restore candidate patch in $REPO_WT" >&2
# The baseline run already reversed the patch out, which is the state the
# caller handed us; re-applying it here is what used to leave residue.
PATCH_APPLIED=0
return
fi
if git -C "$REPO_WT" apply -R --check "$PATCHF" >/dev/null 2>&1 \
&& git -C "$REPO_WT" apply -R "$PATCHF" >/dev/null 2>&1; then
PATCH_APPLIED=0
else
echo "failed to revert the candidate patch in $REPO_WT; it is left applied" >&2
fi
}
trap cleanup EXIT
Expand All @@ -311,7 +327,8 @@ amdsmi.amdsmi_init()
try:
for handle in amdsmi.amdsmi_get_processor_handles():
if amdsmi.amdsmi_get_gpu_enumeration_info(handle).get("hip_id") == requested:
print(amdsmi.amdsmi_get_gpu_activity(handle).get("gfx_activity"))
gfx, _ = picker.read_activity(amdsmi, handle)
print("unavailable" if gfx is None else gfx)
break
else:
raise RuntimeError(f"HIP index {requested} has no amd-smi mapping")
Expand All @@ -321,6 +338,9 @@ PY
)
if [[ "$ACTIVITY_AFTER" =~ ^[0-9]+$ ]]; then
jset_json "stages.gpu_claim.gfx_activity_after_pct" "$ACTIVITY_AFTER"
elif [ "$ACTIVITY_AFTER" = "unavailable" ]; then
jset_string "stages.gpu_claim.post_run_note" \
"post-run GFX activity is not reported by the activity API on this host"
else
jset_string "stages.gpu_claim.post_run_note" \
"post-run GFX activity could not be recorded"
Expand Down Expand Up @@ -371,6 +391,7 @@ if [ -n "$PATCHF" ]; then
fi
if git -C "$REPO_WT" apply --check "$PATCHF" >/dev/null 2>&1 \
&& git -C "$REPO_WT" apply "$PATCHF" >/dev/null 2>&1; then
PATCH_APPLIED=1
stage_note "merge_sim" "pass" "patch applies cleanly to the recorded base"
jset_string "repo.patch_sha256" "$(sha256sum "$PATCHF" | awk '{print $1}')"
if [ -n "$HEAD_SHA" ]; then
Expand Down Expand Up @@ -421,10 +442,16 @@ else
PICK_RC=$?
if [ "$PICK_RC" -ne 0 ] || [[ ! "$PICK" =~ ^[0-9]+$ ]]; then
PICK=""
stage_note "gpu_claim" "skip" \
"no verified-idle GPU was claimable (picker exit $PICK_RC)"
# An environment fact and a validator portability gap are different things
# and must not share one message.
case "$PICK_RC" in
1) CLAIM_NOTE="GPUs are present but none stayed below the idleness thresholds across the sampling window" ;;
2) CLAIM_NOTE="AMD SMI could not be queried on this host, so idleness could not be established; this is a validator portability gap, not a statement about the GPUs" ;;
*) CLAIM_NOTE="no verified-idle GPU was claimable (picker exit $PICK_RC)" ;;
esac
stage_note "gpu_claim" "skip" "$CLAIM_NOTE"
jset_string "degraded_mode" "NO_GPU"
finding "note" "gpu_claim" "no verified-idle GPU was claimable; no runtime correctness claim is made"
finding "note" "gpu_claim" "$CLAIM_NOTE; no runtime correctness claim is made"
else
exec {GPU_LOCK_FD}>"/tmp/gpu-$PICK.lock"
if ! flock -n "$GPU_LOCK_FD"; then
Expand Down Expand Up @@ -459,7 +486,7 @@ try:
raise RuntimeError(f"HIP index {requested} has no amd-smi mapping")
smi_index, handle = match
asic = amdsmi.amdsmi_get_gpu_asic_info(handle)
activity = amdsmi.amdsmi_get_gpu_activity(handle)
gfx_activity, _ = picker.read_activity(amdsmi, handle)
print(
json.dumps(
{
Expand All @@ -469,7 +496,7 @@ try:
"model": asic.get("market_name", "unknown"),
"arch": asic.get("target_graphics_version", "unknown"),
"bdf": amdsmi.amdsmi_get_gpu_device_bdf(handle),
"gfx_activity_before_pct": activity.get("gfx_activity"),
"gfx_activity_before_pct": gfx_activity,
"host": socket.gethostname(),
}
)
Expand All @@ -488,6 +515,12 @@ PY
finding "note" "gpu_claim" "GPU identity could not be verified; no runtime correctness claim is made"
else
jset_json "stages.gpu_claim" "$GPU_INFO"
IDLENESS_BASIS=$(sed -n 's/^idleness-basis: //p' "$WORK/gpu-picker.log" | tail -1)
jset_string "stages.gpu_claim.idleness_basis" "${IDLENESS_BASIS:-unknown}"
if [ "$IDLENESS_BASIS" = "vram-only" ]; then
finding "note" "gpu_claim" \
"GPU activity is unavailable on this host; idleness was established from resident VRAM alone"
fi
fi
fi
fi
Expand Down