CI: add Hip occupancy check and small static analysis report (#32365)

* ci: check for occupancy regressions vs master in HIP quality check

Add scripts/hip/gcn-cdna-occupancy-check.py, which compares per-kernel
occupancy between two GGML_HIP_EXPORT_METRICS build logs and fails when
a kernel drops occupancy. Wire it into the HIP quality check workflow:
the baseline (master) is built with the same target and flags, then
compared against the PR build.

Assisted-by: Hermes Agent

* ci: reuse spill-check build and cache master baseline for occupancy check

The PR-side metrics.log is shared with the VGPR spill check, so the
occupancy comparison adds no extra PR build. The master baseline metrics
log is cached by master-push runs and restored on PRs; it is only
rebuilt as a fallback when the master tip has no cached baseline.

* ci: report occupancy and spill changes as a markdown artifact

Extend gcn-cdna-occupancy-check.py to also compare per-kernel VGPR and
SGPR spills, and add a --report option that writes a markdown report
with all regressions and improvements. The workflow uploads the report
as an artifact on PRs, even when the check fails.

* ci: split metrics check and markdown report into separate scripts

gcn-cdna-metrics-check.py compares per-kernel occupancy and spills and
can dump all deltas as TSV; gcn-cdna-metrics-report.py generates the
markdown report from that dump. The workflow runs both on PRs and
uploads the report as an artifact.

* ci: consolidate HIP kernel metrics checks using Clang YAML remarks

Merge VGPR threshold, occupancy/spill comparison, and Markdown reporting
into one script with unchanged checking rules and output formats. Parse
per-kernel optimization records instead of interleaved text diagnostics.
Add unit tests and update the CI baseline cache to contain YAML records.

* ci: preserve comparison kernel selection and fix Python indentation

Count only kernels with occupancy or spill remarks, as before the YAML
migration. Add a regression test for VGPR-only records and fix flake8.

* ci: fix Python type checking for HIP metrics scripts

Cast metric entries to lists before appending and check the dynamic
module spec and loader are available before executing the tests.
Preserve existing checks and reports.

* ci: add blocking and warning HIP kernel regression rules

Preserve the VGPR limit and its exemptions, block spill increases and
occupancy drops with increasing VGPRs, and warn on occupancy-only drops.
Collect all findings and generate the report before failing CI.

Request device optimization records explicitly and bypass ccache during
metrics builds; print YAML diagnostics to investigate missing kernel
resource remarks in ROCm 7.2.1.

* ci: preserve device-only HIP optimization records

Do not enable host remarks: Clang writes host and device optimization
records to the same output path. Filter the device records to kernel
resource usage and validate the compiler output before expensive builds.
Invalidate old baseline caches and avoid reporting a missing TSV.

* ci: include HIP runtime in metrics probe

Assisted-by: ChatGPT

* ci: build only ggml-hip for kernel metrics and propagate build errors

Assisted-by: ChatGPT

* ci: match HIP baseline to merge commit and publish job summary

Assisted-by: ChatGPT

* ci: trust the HIP CI checkout directory before resolving baseline

Assisted-by: ChatGPT

* ci: cache HIP baseline metrics in HF buckets

Assisted-by: ChatGPT

* ci: publish HIP metrics report to logs and job summary

Assisted-by: ChatGPT

* Ci: hip auto clean every 30 days

Assisted-by: ChatGPT

* Update .github/workflows/hip-quality-check.yml

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>

* ci: fix conflits and rebase

Assisted-by: ChatGPT

---------

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
This commit is contained in:
thelittlefireman 2026-11-26 13:50:32 +01:00 • committed by GitHub
parent 55d482814b
commit fd4b137e38
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 822 additions and 143 deletions

View file

@ -11,7 +11,8 @@ on:
'**/*.cuh',
'ggml/src/ggml-hip/CMakeLists.txt',
'ggml/src/ggml-cuda/vendors/hip.h',
'scripts/hip/gcn-cdna-vgpr-check.py'
'scripts/hip/gcn-cdna-metrics.py',
'scripts/hip/test_gcn_cdna_metrics.py'
]
pull_request:
@ -22,7 +23,8 @@ on:
'**/*.cuh',
'ggml/src/ggml-hip/CMakeLists.txt',
'ggml/src/ggml-cuda/vendors/hip.h',
'scripts/hip/gcn-cdna-vgpr-check.py'
'scripts/hip/gcn-cdna-metrics.py',
'scripts/hip/test_gcn_cdna_metrics.py'
]
cache-mode: none
@ -45,15 +47,32 @@ jobs:
runs-on: ubuntu-22.04
container: rocm/dev-ubuntu-22.04:7.2.1
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
- name: Dependencies
id: depends
run: |
sudo apt-get update
sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip jq
sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip python3-yaml jq
- name: Clone
id: checkout
uses: actions/checkout@v6
with:
fetch-depth: 2
# The first parent of the tested merge commit is the exact baseline.
- name: Get baseline SHA
if: ${{ github.event_name == 'pull_request' }}
id: master_sha
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git rev-parse --verify HEAD^2 > /dev/null
baseline_sha=$(git rev-parse HEAD^1)
pr_sha=$(git rev-parse HEAD)
printf 'sha=%s\npr_sha=%s\n' "$baseline_sha" "$pr_sha" >> "$GITHUB_OUTPUT"
printf 'Baseline commit: %s\nPR merge commit: %s\n' "$baseline_sha" "$pr_sha"
- name: Test HIP kernel metrics scripts
run: python3 -m unittest discover -s scripts/hip -p 'test_gcn_cdna_metrics.py'
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
@ -70,6 +89,21 @@ jobs:
folder: llama.cpp
hf_bucket: ggml-org/cache
# Verify device optimization records before starting the expensive builds.
- name: Validate HIP resource remarks
run: |
mkdir -p hip-metrics-probe
cd hip-metrics-probe
printf '%s\n' '#include <hip/hip_runtime.h>' '__global__ void metrics_probe(float * out) { *out = 1.0f; }' > probe.hip
"$(hipconfig -l)/clang" -x hip --offload-arch=gfx908 -O2 -c probe.hip -o probe.o \
-Rpass-analysis=kernel-resource-usage --save-temps \
-Xarch_device -fsave-optimization-record=yaml \
-Xarch_device -foptimization-record-passes=kernel-resource-usage
for metric in NumVGPR Occupancy VGPRSpill SGPRSpill; do
grep -q "Name: *$metric$" probe.opt.yaml || { echo "Missing $metric in GPU optimization records"; exit 1; }
done
python3 ../scripts/hip/gcn-cdna-metrics.py vgpr probe.opt.yaml
- name: Build with Werror
id: cmake_build
run: |
@ -83,19 +117,178 @@ jobs:
cd build
make -j $(nproc)
- name: Check for major VGPR spills
- name: Build HIP kernel resource metrics
id: vgpr_check
shell: bash
run: |
cmake -B build -S . \
-DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \
-DGPU_TARGETS=gfx908 \
-DGGML_HIP=ON \
-DGGML_HIP_EXPORT_METRICS=On \
-DCMAKE_HIP_FLAGS="" \
-DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \
-DCMAKE_BUILD_TYPE=Release
cd build
make -j $(nproc) 2>&1 | tee metrics.log | grep -v 'Rpass-analysis=kernel-resource-usage\|remark:\|^$'
python3 ../scripts/hip/gcn-cdna-vgpr-check.py metrics.log
set -o pipefail
CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d'
echo "Optimization record files:"
find . -type f -name '*.opt.yaml' | sed -n '1,10p'
echo "GPU kernel remarks in YAML:"
grep -rl --include='*.opt.yaml' 'kernel-resource-usage' . | sed -n '1,10p' || true
echo "First YAML record:"
first_yaml=$(find ggml/src/ggml-hip -type f -name '*.opt.yaml' -print -quit)
if [ -n "$first_yaml" ]; then head -n 35 "$first_yaml"; fi
echo "GPU resource diagnostics in compiler log:"
grep -m 3 'Function Name:' metrics.log || true
# The PR comparison evaluates every rule and reports all failures at the end.
- name: Check VGPR limit on master
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
run: python3 scripts/hip/gcn-cdna-metrics.py vgpr build/ggml/src/ggml-hip
# On master pushes, cache the device optimization records as the baseline for PR checks.
- name: Save master metrics baseline
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
run: |
mkdir -p hip-baseline-metrics
find build/ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} hip-baseline-metrics/ \;
- name: Cache master metrics baseline
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
run: |
if [ -n "$HF_TOKEN" ]; then
tar -czf hip-baseline-metrics.tar.gz -C hip-baseline-metrics .
.venv-hf/bin/hf buckets cp hip-baseline-metrics.tar.gz "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ github.sha }}.tar.gz" || echo "Failed to save HIP metrics baseline"
fi
- name: Remove old HIP metrics baselines
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
shell: bash
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
run: |
if [ -z "$HF_TOKEN" ]; then
exit 0
fi
if ! cache_files=$(.venv-hf/bin/hf buckets list "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-" --json | jq -r '
.[]
| select(.type == "file")
| select(.path | endswith(".tar.gz"))
| select(try ((.uploaded_at | .[:19]+"Z" | fromdateiso8601) < (now - 30 * 24 * 60 * 60)) catch false)
| .path
'); then
echo "Failed to list HIP metrics baselines"
exit 0
fi
while IFS= read -r cache_path; do
[ -n "$cache_path" ] || continue
.venv-hf/bin/hf buckets rm "hf://buckets/ggml-org/cache/$cache_path" -y || echo "Failed to remove $cache_path"
done <<< "$cache_files"
# Restore the device optimization records for the exact baseline commit.
- name: Restore master metrics baseline
if: ${{ github.event_name == 'pull_request' }}
id: baseline_cache
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
run: |
cache_url="hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ steps.master_sha.outputs.sha }}.tar.gz"
if .venv-hf/bin/hf buckets cp "$cache_url" hip-baseline-metrics.tar.gz; then
mkdir -p hip-baseline-metrics
if tar -xzf hip-baseline-metrics.tar.gz -C hip-baseline-metrics && [ -n "$(find hip-baseline-metrics -type f -name '*.opt.yaml' -print -quit)" ]; then
echo "cache-hit=true" >> "$GITHUB_OUTPUT"
echo "Restored HIP metrics baseline from HF Buckets"
else
rm -rf hip-baseline-metrics
echo "Invalid HIP metrics baseline cache"
fi
rm -f hip-baseline-metrics.tar.gz
else
echo "No HIP metrics baseline in HF Buckets; building from source"
fi
# Fallback when the baseline commit has no cached metrics.
- name: Checkout baseline (master)
if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }}
uses: actions/checkout@v6
with:
ref: ${{ steps.master_sha.outputs.sha }}
path: hip-baseline
- name: Build master metrics baseline
if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }}
shell: bash
run: |
cd hip-baseline
cmake -B build -S . \
-DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \
-DGPU_TARGETS=gfx908 \
-DGGML_HIP=ON \
-DGGML_HIP_EXPORT_METRICS=On \
-DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \
-DCMAKE_BUILD_TYPE=Release
cd build
set -o pipefail
CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d'
mkdir -p ../../hip-baseline-metrics
find ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} ../../hip-baseline-metrics/ \;
- name: Check kernel resource rules vs master
if: ${{ github.event_name == 'pull_request' }}
id: occupancy_check
env:
BASELINE_SHA: ${{ steps.master_sha.outputs.sha }}
PR_SHA: ${{ steps.master_sha.outputs.pr_sha }}
run: |
# The PR optimization records come from the VGPR spill check build above, so
# this step adds no extra build when the baseline cache hits.
python3 scripts/hip/gcn-cdna-metrics.py compare hip-baseline-metrics build/ggml/src/ggml-hip \
--dump hip-kernel-metrics-deltas.tsv || check_failed=true
if [ ! -s hip-kernel-metrics-deltas.tsv ]; then
echo "Kernel metrics comparison failed before producing a TSV report"
exit 1
fi
python3 scripts/hip/gcn-cdna-metrics.py report hip-kernel-metrics-deltas.tsv \
-o hip-kernel-metrics-report.md
sed -i "3i\\- Baseline commit: $BASELINE_SHA\\n- PR merge commit: $PR_SHA" hip-kernel-metrics-report.md
if [ -n "$check_failed" ]; then
echo "check_failed=true" >> "$GITHUB_OUTPUT"
fi
exit 0
- name: Upload kernel metrics report
if: ${{ github.event_name == 'pull_request' }}
id: metrics_report
uses: actions/upload-artifact@v7
with:
name: hip-kernel-metrics-report
path: hip-kernel-metrics-report.md
- name: Publish kernel metrics summary
if: ${{ github.event_name == 'pull_request' }}
shell: bash
env:
ARTIFACT_URL: ${{ steps.metrics_report.outputs.artifact-url }}
run: |
{
if [ "$(wc -c < hip-kernel-metrics-report.md)" -le 1000000 ]; then
cat hip-kernel-metrics-report.md
else
sed -n -e '/^# /p' -e '/^- Baseline/p' -e '/^- PR/p' -e '/^Kernels compared:/p' -e 's/^## /- /p' hip-kernel-metrics-report.md
printf '\nThe full report exceeds the GitHub job summary size limit.\n'
fi
printf '\n[Download the full kernel metrics report](%s)\n' "$ARTIFACT_URL"
} | tee -a "$GITHUB_STEP_SUMMARY"
- name: Fail on blocking regressions
if: ${{ github.event_name == 'pull_request' && steps.occupancy_check.outputs.check_failed == 'true' }}
run: |
echo "Blocking kernel metrics regressions detected, see the job summary and hip-kernel-metrics-report artifact"
exit 1
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}

View file

@ -0,0 +1,365 @@
#!/usr/bin/env python3
# Check HIP VGPR limits, compare kernel resource usage, and generate a report.
# Read Clang optimization records produced with -fsave-optimization-record=yaml
# and -Rpass-analysis=kernel-resource-usage.
import argparse
import sys
from collections import defaultdict
from pathlib import Path
from typing import cast
import yaml
try:
from itanium_demangler import parse as demangle # ty: ignore[import-not-found]
except ImportError:
demangle = None
METRICS = ('occupancy', 'vgpr_spill', 'sgpr_spill')
REPORT_METRICS = METRICS + ('vgpr_total',)
RULES = {
'vgpr_limit': 'blocking',
'vgpr_spill_increase': 'blocking',
'sgpr_spill_increase': 'blocking',
'occupancy_vgpr_increase': 'blocking',
'occupancy_drop': 'warning',
}
REMARK_NAMES = {'NumVGPR': 'vgprs', 'Occupancy': 'occupancy', 'VGPRSpill': 'vgpr_spill', 'SGPRSpill': 'sgpr_spill'}
METRIC_NAMES = {'occupancy': 'Occupancy [waves/SIMD]', 'vgpr_spill': 'VGPRs Spill', 'sgpr_spill': 'SGPRs Spill', 'vgpr_total': 'Total VGPRs (limit 256)'}
IGNORED_VGPR = {
'_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf',
}
class RemarkLoader(yaml.SafeLoader):
pass
def construct_remark(loader, tag, node):
return loader.construct_mapping(node)
RemarkLoader.add_multi_constructor('!', construct_remark)
def format_name(name):
if demangle is None:
return name
try:
demangled = demangle(name)
except Exception:
return name
return f'{name} [{demangled}]' if demangled is not None else name
def parse_remarks(filepath):
path = Path(filepath)
files = sorted(path.rglob('*.opt.yaml')) if path.is_dir() else [path] if path.is_file() else []
if not files:
raise ValueError(f'No optimization records found in {filepath}')
functions = defaultdict(lambda: {'vgprs': [], 'occupancy': [], 'vgpr_spill': [], 'sgpr_spill': [], 'location': ''})
for file in files:
with file.open('r') as f:
for remark in yaml.load_all(f, Loader=RemarkLoader):
if not isinstance(remark, dict) or remark.get('Pass') != 'kernel-resource-usage':
continue
key = remark.get('Name')
if key not in REMARK_NAMES:
continue
name = remark.get('Function')
if not isinstance(name, str) or not name:
continue
values = [arg[key] for arg in remark.get('Args', []) if isinstance(arg, dict) and key in arg]
if len(values) != 1:
raise ValueError(f'Invalid {key} remark for {name} in {file}')
try:
value = int(values[0])
except (TypeError, ValueError) as exc:
raise ValueError(f'Invalid {key} value for {name} in {file}') from exc
cast(list[int], functions[name][REMARK_NAMES[key]]).append(value)
location = remark.get('DebugLoc') or {}
if location.get('File') and location.get('Line'):
functions[name]['location'] = f"{Path(location['File']).name}:{location['Line']}"
if not functions:
raise ValueError(f'No kernel resource usage remarks found in {filepath}')
return functions
def load_ignore_file(filepath):
ignored = set()
with open(filepath, 'r') as f:
for line in f:
name = line.strip()
if name and not name.startswith('#'):
ignored.add(name)
return ignored
def check_vgpr(functions, filepath, rows=None):
found_issues = False
for ignored in (True, False):
for name, data in sorted(functions.items()):
if (name in IGNORED_VGPR) != ignored:
continue
vgprs = data['vgprs'][-1] if data['vgprs'] else 0
spill = data['vgpr_spill'][-1] if data['vgpr_spill'] else 0
total_vgprs = vgprs + spill
if total_vgprs <= 256:
continue
location = data['location'] or filepath
suffix = ' [IGNORED]' if ignored else ' '
message = f"{location}: {format_name(name)} - Total VGPRs: {total_vgprs} ({vgprs} + {spill}){suffix}"
blocking = RULES['vgpr_limit'] == 'blocking'
color = '91' if blocking else '93'
print(message if ignored else f'\033[{color}m{message}\033[0m') # noqa: NP100
if not ignored:
found_issues |= blocking
if rows is not None:
rows.append(('vgpr_total', name, location, 256, total_vgprs, 'regression' if blocking else 'warning'))
return int(found_issues)
def worst(values, metric):
return min(values) if metric == 'occupancy' else max(values)
def compare_metric(base, pr, names, metric, tolerance=0):
regressions = []
gains = []
for name in names:
if not base[name][metric] or not pr[name][metric]:
continue
base_val = worst(base[name][metric], metric)
pr_val = worst(pr[name][metric], metric)
if metric == 'occupancy':
if pr_val < base_val - tolerance:
regressions.append((name, base_val, pr_val))
elif pr_val > base_val:
gains.append((name, base_val, pr_val))
else:
if pr_val > base_val:
regressions.append((name, base_val, pr_val))
elif pr_val < base_val:
gains.append((name, base_val, pr_val))
return regressions, gains
def dump_tsv(path, baseline_log, pr_log, base_count, pr_count, common_count, rows):
with open(path, 'w') as f:
f.write(f'#baseline_log\t{baseline_log}\n')
f.write(f'#pr_log\t{pr_log}\n')
f.write(f'#baseline_kernels\t{base_count}\n')
f.write(f'#pr_kernels\t{pr_count}\n')
f.write(f'#kernels_compared\t{common_count}\n')
f.write('metric\tkernel\tlocation\tbaseline\tpr\tstatus\n')
for row in rows:
f.write('\t'.join(str(col) for col in row) + '\n')
def check_comparison(base, pr, baseline_log, pr_log, tolerance=0, ignored=None, dump=None):
ignored = ignored or set()
base_names = {name for name, data in base.items() if any(data[metric] for metric in METRICS)} - ignored
pr_names = {name for name, data in pr.items() if any(data[metric] for metric in METRICS)} - ignored
common = base_names & pr_names
added = pr_names - base_names
removed = base_names - pr_names
locations = {name: data['location'] for name, data in base.items()}
locations.update({name: data['location'] for name, data in pr.items()})
changes = {metric: compare_metric(base, pr, common, metric, tolerance) for metric in METRICS}
issues = [] # metric, kernel, baseline, PR, severity, extra details
for metric, rule in (('vgpr_spill', 'vgpr_spill_increase'), ('sgpr_spill', 'sgpr_spill_increase')):
for name, base_val, pr_val in changes[metric][0]:
issues.append((metric, name, base_val, pr_val, RULES[rule], ''))
for name, base_val, pr_val in changes['occupancy'][0]:
base_vgprs = worst(base[name]['vgprs'], 'vgprs') if base[name]['vgprs'] else None
pr_vgprs = worst(pr[name]['vgprs'], 'vgprs') if pr[name]['vgprs'] else None
increasing = base_vgprs is not None and pr_vgprs is not None and pr_vgprs > base_vgprs
rule = 'occupancy_vgpr_increase' if increasing else 'occupancy_drop'
detail = f', VGPRs: {base_vgprs} -> {pr_vgprs}' if increasing else ''
issues.append(('occupancy', name, base_val, pr_val, RULES[rule], detail))
print(f'Kernels compared: {len(common)} (baseline {len(base_names)}, PR {len(pr_names)})') # noqa: NP100
print(f'Added kernels: {len(added)}, removed kernels: {len(removed)}') # noqa: NP100
for severity, color, label in (('blocking', '91', 'REGRESSION'), ('warning', '93', 'WARNING')):
for metric, name, base_val, pr_val, level, detail in sorted(issues):
if level == severity:
print(f"\033[{color}m{locations[name]}: {name} - {METRIC_NAMES[metric]}: {base_val} -> {pr_val}{detail} ({label})\033[0m") # noqa: NP100
for metric in METRICS:
for name, base_val, pr_val in sorted(changes[metric][1]):
print(f"\033[92m{locations[name]}: {name} - {METRIC_NAMES[metric]}: {base_val} -> {pr_val} (improved)\033[0m") # noqa: NP100
for name in sorted(added):
print(f'note: new kernel in PR: {name}') # noqa: NP100
for name in sorted(removed):
print(f'note: kernel only in baseline: {name}') # noqa: NP100
# Check the absolute VGPR limit as well, even for kernels excluded from comparisons.
vgpr_rows = []
vgpr_failed = check_vgpr(pr, pr_log, vgpr_rows)
if dump:
rows = []
for metric, name, base_val, pr_val, severity, _ in issues:
rows.append((metric, name, locations[name], base_val, pr_val, 'regression' if severity == 'blocking' else 'warning'))
for metric in METRICS:
for name, base_val, pr_val in sorted(changes[metric][1]):
rows.append((metric, name, locations[name], base_val, pr_val, 'improved'))
rows.extend(vgpr_rows)
for name in sorted(added):
for metric in METRICS:
if pr[name][metric]:
rows.append((metric, name, locations[name], '', worst(pr[name][metric], metric), 'added'))
for name in sorted(removed):
for metric in METRICS:
if base[name][metric]:
rows.append((metric, name, locations[name], worst(base[name][metric], metric), '', 'removed'))
dump_tsv(dump, baseline_log, pr_log, len(base_names), len(pr_names), len(common), rows)
print(f'Deltas written to {dump}') # noqa: NP100
blocking = sum(severity == 'blocking' for _, _, _, _, severity, _ in issues)
warnings = sum(severity == 'warning' for _, _, _, _, severity, _ in issues)
blocking += sum(row[5] == 'regression' for row in vgpr_rows)
warnings += sum(row[5] == 'warning' for row in vgpr_rows)
if blocking or warnings:
print(f'{blocking} blocking regression(s), {warnings} warning(s)') # noqa: NP100
else:
print('No regressions found') # noqa: NP100
return int(bool(blocking or vgpr_failed))
def read_deltas(filepath):
meta = {}
rows = []
try:
with open(filepath, 'r') as f:
for line in f:
line = line.rstrip('\n')
if line.startswith('#'):
parts = line[1:].split('\t')
if len(parts) == 2:
meta[parts[0].strip()] = parts[1].strip()
continue
cols = line.split('\t')
if len(cols) == 6 and cols[0] in REPORT_METRICS:
rows.append(cols)
except FileNotFoundError:
print(f"Error: File {filepath} not found", file=sys.stderr) # noqa: NP100
sys.exit(1)
return meta, rows
def write_report(path, meta, rows):
tables = {} # (metric, status) -> list of (kernel, location, baseline, pr)
added = {} # kernel -> [location, {metric: value}]
removed = {} # kernel -> [location, {metric: value}]
for metric, kernel, location, baseline, pr, status in rows:
if status in ('regression', 'warning', 'improved'):
tables.setdefault((metric, status), []).append((kernel, location, baseline, pr))
elif status == 'added':
added.setdefault(kernel, [location, {}])[1][metric] = pr
elif status == 'removed':
removed.setdefault(kernel, [location, {}])[1][metric] = baseline
with open(path, 'w') as f:
f.write('# HIP kernel metrics comparison\n\n')
f.write(f"- Baseline: `{meta.get('baseline_log', '?')}`\n")
f.write(f"- PR: `{meta.get('pr_log', '?')}`\n\n")
f.write(f"Kernels compared: {meta.get('kernels_compared', '?')} "
f"(baseline {meta.get('baseline_kernels', '?')}, PR {meta.get('pr_kernels', '?')}). "
f"Added kernels: {len(added)}, removed kernels: {len(removed)}.\n\n")
for metric in REPORT_METRICS:
name = METRIC_NAMES[metric]
statuses = (('regression', 'regressions'), ('improved', 'improvements'))
if metric == 'occupancy':
statuses = (('regression', 'regressions'), ('warning', 'warnings'), ('improved', 'improvements'))
elif metric == 'vgpr_total':
statuses = (('regression', 'regressions'), ('warning', 'warnings'))
if metric == 'vgpr_total':
f.write('The baseline value for total VGPRs is the 256-register threshold.\n\n')
for status, title in statuses:
entries = tables.get((metric, status), [])
f.write(f'## {name} {title} ({len(entries)})\n\n')
if entries:
f.write('| Location | Kernel | Baseline | PR |\n|---|---|---|---|\n')
for kernel, location, baseline, pr in entries:
f.write(f'| {location} | `{kernel}` | {baseline} | {pr} |\n')
else:
f.write('None.\n')
f.write('\n')
for title, kernels in (('Added kernels', added), ('Removed kernels', removed)):
f.write(f'## {title} ({len(kernels)})\n\n')
if kernels:
f.write('| Location | Kernel | Occupancy | VGPRs Spill | SGPRs Spill |\n|---|---|---|---|---|\n')
for kernel in sorted(kernels):
location, values = kernels[kernel]
occupancy = values.get('occupancy', '')
vspill = values.get('vgpr_spill', '')
sspill = values.get('sgpr_spill', '')
f.write(f'| {location} | `{kernel}` | {occupancy} | {vspill} | {sspill} |\n')
else:
f.write('None.\n')
f.write('\n')
def main():
parser = argparse.ArgumentParser(description='Check HIP kernel resource usage and generate reports')
commands = parser.add_subparsers(dest='command', required=True)
vgpr = commands.add_parser('vgpr', help='check the 256 VGPR limit')
vgpr.add_argument('records', help='directory of Clang .opt.yaml files')
compare = commands.add_parser('compare', help='compare occupancy and register spills')
compare.add_argument('baseline_log', help='baseline optimization records')
compare.add_argument('pr_log', help='PR optimization records')
compare.add_argument('-t', '--tolerance', type=int, default=0, help='allowed occupancy drop in waves/SIMD')
compare.add_argument('--ignore', help='file with kernel symbols to exclude, one per line')
compare.add_argument('--dump', help='write all deltas to a TSV file')
report = commands.add_parser('report', help='generate the Markdown report from a TSV dump')
report.add_argument('deltas_tsv', help='TSV deltas from compare --dump')
report.add_argument('-o', '--output', default='hip-kernel-metrics-report.md', help='output Markdown file')
args = parser.parse_args()
try:
if args.command == 'vgpr':
return check_vgpr(parse_remarks(args.records), args.records)
if args.command == 'compare':
ignored = load_ignore_file(args.ignore) if args.ignore else set()
return check_comparison(parse_remarks(args.baseline_log), parse_remarks(args.pr_log), args.baseline_log, args.pr_log, args.tolerance, ignored, args.dump)
meta, rows = read_deltas(args.deltas_tsv)
write_report(args.output, meta, rows)
print(f'Report written to {args.output}') # noqa: NP100
return 0
except (OSError, ValueError, yaml.YAMLError) as exc:
print(f'Error: {exc}', file=sys.stderr) # noqa: NP100
return 1
if __name__ == '__main__':
sys.exit(main())

View file

@ -1,132 +0,0 @@
#!/usr/bin/env python3
import sys
from collections import defaultdict
import re
try:
from itanium_demangler import parse as demangle # ty: ignore[import-not-found]
except ImportError:
demangle = None
def format_name(name):
if demangle is None:
return name
try:
demangled = demangle(name)
except Exception:
return name
return f"{name} [{demangled}]" if demangled is not None else name
def parse_log_file(filepath):
functions = defaultdict(lambda: {'vgprs': 0, 'spill': 0, 'location': ''})
func_stack = []
try:
with open(filepath, 'r') as f:
for line in f:
# Match function name lines
func_match = re.search(r'remark: ([^:]+):(\d+):\d+: Function Name: (\S+)', line)
if func_match:
location = func_match.group(1) + ':' + func_match.group(2)
func_name = func_match.group(3)
# Extract just the filename and line number
parts = location.split('/')
short_location = parts[-1] if len(parts) > 0 else location
functions[func_name]['location'] = short_location
# Push function onto stack with its location
func_stack.append({'name': func_name, 'location': location})
continue
# Match VGPR usage lines (only if we have functions in stack)
vgpr_match = re.search(r'remark: ([^:]+):(\d+):\d+:\s+VGPRs: (\d+)', line)
if vgpr_match:
location = vgpr_match.group(1) + ':' + vgpr_match.group(2)
# Find the most recent function with matching location
for i in range(len(func_stack) - 1, -1, -1):
if func_stack[i]['location'] == location:
functions[func_stack[i]['name']]['vgprs'] = int(vgpr_match.group(3))
break
continue
spill_match = re.search(r'remark: ([^:]+):(\d+):\d+:\s+VGPRs Spill: (\d+)', line)
if spill_match:
location = spill_match.group(1) + ':' + spill_match.group(2)
# Find the most recent function with matching location
for i in range(len(func_stack) - 1, -1, -1):
if func_stack[i]['location'] == location:
functions[func_stack[i]['name']]['spill'] = int(spill_match.group(3))
break
continue
except FileNotFoundError:
print(f"Error: File {filepath} not found", file=sys.stderr) # noqa: NP100
sys.exit(1)
return functions
def main():
if len(sys.argv) < 2:
print("Usage: ./vgpr_check.py <log_file>", file=sys.stderr) # noqa: NP100
sys.exit(1)
log_file = sys.argv[1]
ignored = {
'_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf',
}
functions = parse_log_file(log_file)
found_issues = False
# First print all ignored functions (deduplicated)
printed_ignored = set()
for func_name, data in sorted(functions.items()):
total_vgprs = int(data['vgprs']) + int(data['spill'])
if total_vgprs > 256 and func_name in ignored and func_name not in printed_ignored:
location = data.get('location', log_file)
print(f"{location}: {format_name(func_name)} - Total VGPRs: {total_vgprs} ({data['vgprs']} + {data['spill']}) [IGNORED]") # noqa: NP100
printed_ignored.add(func_name)
# Then print new functions with issues in red
for func_name, data in sorted(functions.items()):
total_vgprs = int(data['vgprs']) + int(data['spill'])
if total_vgprs > 256 and func_name not in ignored:
status = "[IGNORED]" if func_name in ignored else ""
location = data.get('location', log_file)
# Print in red if not ignored
color_code = "\033[91m" if func_name not in ignored else ""
reset_code = "\033[0m" if func_name not in ignored else ""
print(f"{color_code}{location}: {format_name(func_name)} - Total VGPRs: {total_vgprs} ({data['vgprs']} + {data['spill']}) {status}{reset_code}") # noqa: NP100
if func_name not in ignored:
found_issues = True
sys.exit(1 if found_issues else 0)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,253 @@
#!/usr/bin/env python3
import importlib.util
import io
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
import yaml
SCRIPT = Path(__file__).with_name('gcn-cdna-metrics.py')
spec = importlib.util.spec_from_file_location('gcn_cdna_metrics', SCRIPT)
if spec is None or spec.loader is None:
raise RuntimeError(f'Cannot load {SCRIPT}')
metrics = importlib.util.module_from_spec(spec)
spec.loader.exec_module(metrics)
def write_records(directory, filename, kernels):
path = directory / filename
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('w') as f:
for name, values in kernels.items():
for key, value in values.items():
f.write('--- !Analysis\n')
yaml.safe_dump({'Pass': 'kernel-resource-usage', 'Name': key, 'Function': name,
'DebugLoc': {'File': 'wkv.cu', 'Line': 69, 'Column': 1},
'Args': [{'String': key + ': '}, {key: str(value)}]}, f, sort_keys=False)
f.write('...\n')
return path
class MetricsTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.base = self.root / 'baseline'
self.pr = self.root / 'pr'
self.base.mkdir()
self.pr.mkdir()
def compare(self, **kwargs):
with redirect_stdout(io.StringIO()) as out:
result = metrics.check_comparison(metrics.parse_remarks(self.base), metrics.parse_remarks(self.pr),
'baseline', 'PR', **kwargs)
return result, out.getvalue()
def test_same_source_location_does_not_swap_kernel_specializations(self):
write_records(self.pr, 'kernels.opt.yaml', {'_Zkernel64': {'NumVGPR': 64, 'VGPRSpill': 360},
'_Zkernel128': {'NumVGPR': 64, 'VGPRSpill': 0}})
data = metrics.parse_remarks(self.pr)
self.assertEqual(data['_Zkernel64']['vgpr_spill'], [360])
self.assertEqual(data['_Zkernel128']['vgpr_spill'], [0])
self.assertEqual(data['_Zkernel64']['location'], 'wkv.cu:69')
def test_vgpr_limit_and_allowlist(self):
write_records(self.pr, 'kernels.opt.yaml', {'bad': {'NumVGPR': 255, 'VGPRSpill': 2},
'allowed': {'NumVGPR': 256, 'VGPRSpill': 4},
'good': {'NumVGPR': 256, 'VGPRSpill': 0}})
metrics.IGNORED_VGPR.add('allowed')
self.addCleanup(metrics.IGNORED_VGPR.discard, 'allowed')
with redirect_stdout(io.StringIO()) as out:
code = metrics.check_vgpr(metrics.parse_remarks(self.pr), 'PR')
self.assertEqual(code, 1)
self.assertIn('allowed - Total VGPRs: 260 (256 + 4) [IGNORED]', out.getvalue())
self.assertIn('bad - Total VGPRs: 257 (255 + 2)', out.getvalue())
self.assertNotIn('good - Total VGPRs', out.getvalue())
def test_occupancy_spill_regressions_and_tolerance(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'VGPRSpill': 0, 'SGPRSpill': 1}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'VGPRSpill': 1, 'SGPRSpill': 0}})
code, output = self.compare()
self.assertEqual(code, 1)
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
self.assertIn('VGPRs Spill: 0 -> 1 (REGRESSION)', output)
self.assertIn('SGPRs Spill: 1 -> 0 (improved)', output)
code, output = self.compare(tolerance=1)
self.assertEqual(code, 1)
self.assertNotIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
def test_duplicate_kernel_uses_worst_per_metric(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 6, 'VGPRSpill': 0}})
write_records(self.base, 'sub/b.opt.yaml', {'same': {'Occupancy': 5, 'VGPRSpill': 2}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 6, 'VGPRSpill': 1}})
code, output = self.compare()
self.assertEqual(code, 0)
self.assertIn('VGPRs Spill: 2 -> 1 (improved)', output)
self.assertIn('Occupancy [waves/SIMD]: 5 -> 6 (improved)', output)
def test_added_removed_deltas_and_markdown(self):
write_records(self.base, 'a.opt.yaml', {'removed': {'Occupancy': 5, 'VGPRSpill': 2}, 'same': {'Occupancy': 4}})
write_records(self.pr, 'a.opt.yaml', {'added': {'Occupancy': 6, 'SGPRSpill': 1}, 'same': {'Occupancy': 5}})
tsv = self.root / 'diff.tsv'
report = self.root / 'report.md'
code, _ = self.compare(dump=tsv)
self.assertEqual(code, 0)
self.assertIn('occupancy\tadded\twkv.cu:69\t\t6\tadded', tsv.read_text())
meta, rows = metrics.read_deltas(tsv)
metrics.write_report(report, meta, rows)
result = report.read_text()
self.assertIn('# HIP kernel metrics comparison', result)
self.assertIn('## Occupancy [waves/SIMD] improvements (1)', result)
self.assertIn('## Added kernels (1)', result)
self.assertIn('## Removed kernels (1)', result)
self.assertIn('| wkv.cu:69 | ' + chr(96) + 'same' + chr(96) + ' | 4 | 5 |', result)
def test_ignore_only_comparison_not_vgpr(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 1}})
code, output = self.compare(ignored={'same'})
self.assertEqual(code, 0)
self.assertIn('Kernels compared: 0', output)
def test_vgpr_only_records_are_not_compared(self):
write_records(self.base, 'a.opt.yaml', {'vgpr_only': {'NumVGPR': 64}, 'same': {'Occupancy': 4}})
write_records(self.pr, 'a.opt.yaml', {'vgpr_only': {'NumVGPR': 128}, 'same': {'Occupancy': 4}})
code, output = self.compare()
self.assertEqual(code, 0)
self.assertIn('Kernels compared: 1 (baseline 1, PR 1)', output)
def test_occupancy_drop_with_more_vgprs_blocks(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 64}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 96}})
tsv = self.root / 'diff.tsv'
code, output = self.compare(dump=tsv)
self.assertEqual(code, 1)
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4, VGPRs: 64 -> 96 (REGRESSION)', output)
self.assertIn('1 blocking regression(s), 0 warning(s)', output)
self.assertIn('occupancy\tsame\twkv.cu:69\t5\t4\tregression', tsv.read_text())
def test_occupancy_drop_with_fewer_vgprs_warns(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 96}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 64}})
tsv = self.root / 'diff.tsv'
report = self.root / 'report.md'
code, output = self.compare(dump=tsv)
self.assertEqual(code, 0)
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
self.assertIn('0 blocking regression(s), 1 warning(s)', output)
self.assertIn('occupancy\tsame\twkv.cu:69\t5\t4\twarning', tsv.read_text())
meta, rows = metrics.read_deltas(tsv)
metrics.write_report(report, meta, rows)
self.assertIn('## Occupancy [waves/SIMD] warnings (1)', report.read_text())
self.assertIn('| wkv.cu:69 | `same` | 5 | 4 |', report.read_text())
def test_occupancy_drop_without_vgpr_increase_warns(self):
write_records(self.base, 'a.opt.yaml', {'unchanged': {'Occupancy': 5, 'NumVGPR': 64},
'missing': {'Occupancy': 5}})
write_records(self.pr, 'a.opt.yaml', {'unchanged': {'Occupancy': 4, 'NumVGPR': 64},
'missing': {'Occupancy': 4}})
code, output = self.compare()
self.assertEqual(code, 0)
self.assertEqual(output.count('(WARNING)'), 2)
self.assertIn('0 blocking regression(s), 2 warning(s)', output)
def test_vgpr_and_sgpr_spill_increases_block_independently(self):
write_records(self.base, 'a.opt.yaml', {'vgpr': {'VGPRSpill': 0}, 'sgpr': {'SGPRSpill': 0}})
write_records(self.pr, 'a.opt.yaml', {'vgpr': {'VGPRSpill': 1}, 'sgpr': {'SGPRSpill': 1}})
code, output = self.compare()
self.assertEqual(code, 1)
self.assertIn('vgpr - VGPRs Spill: 0 -> 1 (REGRESSION)', output)
self.assertIn('sgpr - SGPRs Spill: 0 -> 1 (REGRESSION)', output)
self.assertIn('2 blocking regression(s), 0 warning(s)', output)
def test_vgpr_limit_blocks_comparison_and_appears_in_report(self):
write_records(self.base, 'a.opt.yaml', {'same': {'NumVGPR': 256, 'VGPRSpill': 0}})
write_records(self.pr, 'a.opt.yaml', {'same': {'NumVGPR': 256, 'VGPRSpill': 1}})
tsv = self.root / 'diff.tsv'
report = self.root / 'report.md'
code, output = self.compare(dump=tsv)
self.assertEqual(code, 1)
self.assertIn('Total VGPRs: 257 (256 + 1)', output)
self.assertIn('2 blocking regression(s), 0 warning(s)', output)
self.assertIn('vgpr_total\tsame\twkv.cu:69\t256\t257\tregression', tsv.read_text())
meta, rows = metrics.read_deltas(tsv)
metrics.write_report(report, meta, rows)
self.assertIn('## Total VGPRs (limit 256) regressions (1)', report.read_text())
self.assertIn('| wkv.cu:69 | `same` | 256 | 257 |', report.read_text())
def test_existing_vgpr_allowlist_preserves_comparison_checks(self):
write_records(self.base, 'a.opt.yaml', {'allowed': {'NumVGPR': 255, 'VGPRSpill': 3}})
write_records(self.pr, 'a.opt.yaml', {'allowed': {'NumVGPR': 255, 'VGPRSpill': 4}})
metrics.IGNORED_VGPR.add('allowed')
self.addCleanup(metrics.IGNORED_VGPR.discard, 'allowed')
code, output = self.compare()
self.assertEqual(code, 1)
self.assertIn('Total VGPRs: 259 (255 + 4) [IGNORED]', output)
self.assertIn('VGPRs Spill: 3 -> 4 (REGRESSION)', output)
self.assertIn('1 blocking regression(s), 0 warning(s)', output)
def test_comparison_ignore_does_not_disable_vgpr_limit(self):
write_records(self.base, 'a.opt.yaml', {'ignored': {'NumVGPR': 256, 'VGPRSpill': 0}})
write_records(self.pr, 'a.opt.yaml', {'ignored': {'NumVGPR': 256, 'VGPRSpill': 1}})
code, output = self.compare(ignored={'ignored'})
self.assertEqual(code, 1)
self.assertIn('Kernels compared: 0 (baseline 0, PR 0)', output)
self.assertIn('Total VGPRs: 257 (256 + 1)', output)
def test_occupancy_tolerance_applies_to_blocking_rule(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 64}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 96}})
code, output = self.compare(tolerance=1)
self.assertEqual(code, 0)
self.assertNotIn('Occupancy [waves/SIMD]: 5 -> 4', output)
self.assertIn('No regressions found', output)
def test_all_rules_complete_and_return_error_after_dump(self):
write_records(self.base, 'a.opt.yaml', {'occb': {'Occupancy': 5, 'NumVGPR': 64},
'occw': {'Occupancy': 5, 'NumVGPR': 80},
'spill': {'SGPRSpill': 0}})
write_records(self.pr, 'a.opt.yaml', {'occb': {'Occupancy': 4, 'NumVGPR': 96},
'occw': {'Occupancy': 4, 'NumVGPR': 64},
'spill': {'SGPRSpill': 1}})
tsv = self.root / 'diff.tsv'
code, output = self.compare(dump=tsv)
self.assertEqual(code, 1)
self.assertIn('occb - Occupancy [waves/SIMD]: 5 -> 4, VGPRs: 64 -> 96 (REGRESSION)', output)
self.assertIn('occw - Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
self.assertIn('spill - SGPRs Spill: 0 -> 1 (REGRESSION)', output)
self.assertIn('2 blocking regression(s), 1 warning(s)', output)
self.assertTrue(tsv.is_file())
def test_cli_returns_success_for_warnings_and_generates_report_after_failure(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 96}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 64}})
tsv = self.root / 'diff.tsv'
report = self.root / 'report.md'
argv = ['gcn-cdna-metrics.py', 'compare', str(self.base), str(self.pr), '--dump', str(tsv)]
with patch('sys.argv', argv), redirect_stdout(io.StringIO()):
self.assertEqual(metrics.main(), 0)
self.assertIn('warning', tsv.read_text())
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 128}})
with patch('sys.argv', argv), redirect_stdout(io.StringIO()):
self.assertEqual(metrics.main(), 1)
self.assertIn('regression', tsv.read_text())
with patch('sys.argv', ['gcn-cdna-metrics.py', 'report', str(tsv), '-o', str(report)]), redirect_stdout(io.StringIO()):
self.assertEqual(metrics.main(), 0)
self.assertIn('## Occupancy [waves/SIMD] regressions (1)', report.read_text())
def test_missing_or_invalid_records_fail(self):
with self.assertRaisesRegex(ValueError, 'No optimization records'):
metrics.parse_remarks(self.pr)
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 'invalid'}})
with self.assertRaisesRegex(ValueError, 'Invalid Occupancy value'):
metrics.parse_remarks(self.pr)
if __name__ == '__main__':
unittest.main()