radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
# libr4d/isa -- reading the machine code the kernels actually became
Seven scripts and four microbenchmarks. They exist because "this kernel is slow" and "this kernel
is at the wall" look identical from a wall-clock timer, while the disassembly plus one calibration
number tells them apart without a GPU run at all. The trace tools are the exception: they need the
GPU, and they are the only instruments here that report the geometry a kernel was ACTUALLY launched
with rather than the geometries it could have been.
BUILD=/path/to/build ./res.sh | head -40 # every kernel: vgpr/lds/scratch
BUILD=... ./dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E
BUILD=... ./waterfall.sh # divergent VGPR indices, per kernel
./loop.sh # its K loop, classified
./trace.sh traces/dec -- ./bin/radiance ... # then: ./tsum.sh traces/dec/k_kernel_trace.csv
`res.sh` prints the mangled name; the substring `dis.sh` takes is a template instantiation out of
it, and the parameter order is in the kernel's own declaration (`gemm_fp8a8_kernel` is
`<Full, AW, NT, MT, MW, FK, GATED>`, so `ILb1ELb0ELj8ELj1ELj8ELj64ELb0E` is the prefill tile).
`loop.sh` anchors on `v_wmma` by default and takes the SMALLEST backward branch containing every
anchor -- a plain largest-loop search finds the epilogue, which is a long unrolled store chain.
## The tools
| tool | what it answers |
|---|---|
| `co.sh` | extracts the gfx1201 code object out of one built `.hip.o`; everything else reads that |
| `dis.sh` | disassembles ONE template instantiation out of one translation unit |
| `loop.sh` | isolates the working loop of that disassembly and classifies its body by instruction class |
| `res.sh` | one row per device kernel in a build tree: VGPRs, SGPRs, LDS, scratch, spills, waves a SIMD, workgroup size |
| `waterfall.sh` | every kernel that indexes a VGPR array with an index the compiler could not prove uniform |
| `trace.sh` | runs a command under `rocprofv3 --kernel-trace` and leaves a CSV |
| `tsum.sh` | summarises that CSV over a steady-state window: where device time goes, per (kernel, grid) |
| `gaps.sh` | the other half -- where the device is IDLE, and which op it was waiting for |
| `rskew.sh` | per-kernel device time on each agent, and the skew between ranks |
| `isarate.hip` | what one instruction slot is worth on gfx1201 (below) |
| `graphrate.hip` | what a dispatch costs the HOST to submit, and what capturing a fixed sequence saves |
| `launchreg.hip` + `launchreg_lib.hip` | whether a launch costs more when the module registers more kernels, and what crossing into a `.so` costs |
| `blockcopy.hip` | contiguous versus scattered device-to-host copy, at KV-block granularity |
Each script's own header states its traps and how to read its output. The microbenchmarks are built
by hand; the command line is in each file's header, and `build_launchreg.sh` builds the two-object
pair the registration test needs.
## What an instruction slot is worth on gfx1201
`isarate.hip` runs each instruction back to back in eight independent chains, so nothing stalls but
issue. The ratio it reports is clock-independent, which is why it reads no clock.
**One `v_wmma_f32_16x16x16_fp8_fp8` costs about 12.9 plain VALU issue slots**, and that does not
change when 36 KiB of LDS holds occupancy down to what a real prefill tile gets (at that occupancy
it measures nearer 11.6, for a peak of about 434 TFLOP/s). So a kernel's ceiling is
TFLOP/s = 434 * wmma_slots / (wmma_slots + other_instructions_issued)
with `wmma_slots = 12.9 * (wmma count)`, both counts per loop iteration out of `loop.sh`.
**It is a CEILING and not a prediction**, and the difference matters: a kernel cannot beat it, and a
kernel far under it is under it for some other reason that then has to be found. Issue is frequently
not the binding constraint. Cutting a kernel's non-WMMA instruction count by more than half can make
it SLOWER, because the removed work was covering memory and LDS latency and its removal raises
register pressure; and a memory-bound kernel moves by about a percent under the same cut. Use the
model to rule a lever out, not to predict a gain.
gfx1201 has **no dense 16x16x32 fp8 WMMA** -- `llvm-mc -mcpu=gfx1201` rejects it. The only 32-deep
fp8 form is `v_swmmac_f32_16x16x32_fp8_fp8`, which is the 2:4 sparse one. The GEMMs here are already
on the widest dense op that exists.
## The profiler: what works and what does not
`rocprofv3 --pmc` does not work on this platform. Any counter set, any kernel filter, on this tree
or on `isarate` alone: it collects, then hangs in `queue.cpp:939 Timeout while waiting for queue
sync: 1 kernels still active` and aborts on SIGABRT. **There are no hardware counters**, so the
dynamic instruction count is not directly observable -- `loop.sh` plus knowing which blocks are
predicated is how to get it.
`--kernel-trace` works, unmasked. The abort that names an unsupported agent
rocprofiler_iterate_agent_supported_counters failed for agent 3 (gfx1036)
:: Agent HW architecture is not supported, no counter metrics found.
is **counter** enumeration and appears only under `--pmc`. It names a display GPU integrated on the
CPU, which has no counter support; masking it does not make `--pmc` work, and `--kernel-trace` never
needed it masked. `trace.sh` sets `ROCR_VISIBLE_DEVICES=0,1` only to pin the agent set and keep that
line out of the log.
`rocprofv3` is not on `PATH`; it is `/opt/rocm/bin/rocprofv3`.
**A killed `rocprofv3` leaves a zombie that outlives its own `timeout`.** The hang is in
finalisation, after the alarm has fired, so the child ignores the timeout and sits in queue-sync
indefinitely. It does not hold CUs, so it does not poison a timing measurement -- but it does hold
VRAM, which makes the *next* tool report allocation failures that read like miscompiled kernels.
Always follow a `--pmc` attempt with `pkill -9 -f rocprofv3`; `trace.sh` does this itself.
### Reading a trace
* Tracing costs about 2 us per dispatch per RANK. The ranks are separate host threads and inflate in
parallel, so per-rank dispatches are what count, not the total.
* Kernel **durations** are hardware timestamps and do not move under tracing. The **gaps** absorb the
whole interception cost, so busy time is real and idle time is an upper bound. `tsum.sh` does that
subtraction and prints both.
* Generated text does not change under tracing, so a traced run can be pointed at a real serving
configuration rather than a proxy.
* **Busy is not utilisation, and this is the easiest number here to misread.** A dispatch counts as
busy if it is resident at all, so a 5 us kernel holding 1 of 64 CUs reads exactly like a GEMM
saturating the card. "96% busy" says the step is almost never *waiting* for a launch. It says
nothing about occupancy -- for that, read the blocks column, where anything under ~64 cannot fill
the device however long it runs.
* **A trace can go quiet and still look complete.** A run that idles before its workload records the
startup and nothing else, and the CSV is well formed either way. Send the workload the moment
health answers, keep the run short, and check `dispatches/step` in `tsum.sh`'s header against what
the model should issue before believing any table built from it.
## What the instruments say in general
Two results recur often enough to be worth stating up front, because they decide which levers are
worth pulling at all.
**Every dispatch costs a few microseconds before it does anything.** Across the shapes a decode step
asks the narrow fp8 GEMM for, the time is not six different rates but one line,
t = fixed + bytes / achievable_stream_rate
with a fixed term of roughly 4.5 us and a stream rate near the card's achievable bandwidth. The same
fixed cost shows on every small op -- rmsnorm, quant_act, add, gated_quant -- whatever it moves. So
a "slow" small shape is usually a fixed cost failing to amortise, not a kernel with bandwidth left
in it, and **fewer kernels** is the only lever that reaches it.
**Most of the weight-streaming kernels are at the memory wall.** A narrow GEMM whose K loop issues a
few hundred instructions per few kilobytes of weight per wave has roughly four times more issue
capacity than the card has bandwidth, and measures at the achievable stream rate. Assembly-level
work on such a kernel is not worth doing; confirm the reading with `loop.sh` before spending any.
**Read the kernel's own header before proposing anything about it.** Each hot kernel's source
carries its own ablations, sweeps and rejected arms with the reason each was rejected, and the
answer to most assembly-level ideas is already recorded there.
+75
View File
@@ -0,0 +1,75 @@
// WHAT A SCATTERED KV EVICTION COSTS.
//
// Pricing a host-tiered prefix cache from a bulk device-to-host bandwidth figure assumes the
// context moves as ONE transfer. It does not: the prefix cache is block-granular, the blocks are
// scattered through the paged pool, and a long context is many thousands of them. A scattered copy
// is a different machine from a contiguous one, and any such estimate rests on which one it is.
//
// So: one contiguous copy of N*B bytes, against N separate copies of B bytes from scattered
// offsets, against N copies issued back-to-back on one stream (the batched form a real eviction
// would use).
//
// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 blockcopy.hip -o blockcopy
#include <hip/hip_runtime.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <vector>
using clk = std::chrono::steady_clock;
static double ms_since(clk::time_point a, clk::time_point b) {
return std::chrono::duration<double, std::milli>(b - a).count();
}
int main(int argc, char** argv) {
const long long bytes = (argc > 1 ? std::atoll(argv[1]) : 1382) * 1024LL * 1024LL; /* ~1.35 GiB */
const int blk = argc > 2 ? std::atoi(argv[2]) : 122880; /* bytes a block */
const int iters = argc > 3 ? std::atoi(argv[3]) : 5;
const long long n = bytes / blk;
void* dev = nullptr;
if (hipMalloc(&dev, (size_t)bytes) != hipSuccess) { std::printf("hipMalloc %lld failed\n", bytes); return 1; }
void* host = nullptr;
if (hipHostMalloc(&host, (size_t)bytes) != hipSuccess) { std::printf("hipHostMalloc failed\n"); return 1; }
hipStream_t s; hipStreamCreate(&s);
/* SCATTERED, not sequential: a real pool hands out blocks in whatever order they were freed,
* so the eviction walks them in an order uncorrelated with address. */
std::vector<long long> order((size_t)n);
for (long long i = 0; i < n; ++i) order[(size_t)i] = i;
unsigned seed = 12345;
for (long long i = n - 1; i > 0; --i) {
seed = seed * 1103515245u + 12345u;
std::swap(order[(size_t)i], order[(size_t)(seed % (unsigned)(i + 1))]);
}
std::printf("%lld MiB, block %d B, %lld blocks, %d iters\n", bytes >> 20, blk, n, iters);
auto run = [&](const char* nm, bool scattered, bool sync_each) {
double best = 1e30;
for (int it = 0; it < iters; ++it) {
const auto t0 = clk::now();
if (!scattered) {
hipMemcpyAsync(host, dev, (size_t)bytes, hipMemcpyDeviceToHost, s);
} else {
for (long long i = 0; i < n; ++i) {
const long long off = order[(size_t)i] * blk;
hipMemcpyAsync((char*)host + off, (char*)dev + off, (size_t)blk,
hipMemcpyDeviceToHost, s);
if (sync_each) hipStreamSynchronize(s);
}
}
hipStreamSynchronize(s);
best = std::min(best, ms_since(t0, clk::now()));
}
std::printf(" %-28s %8.1f ms %6.2f GB/s\n", nm, best,
(double)bytes / (best * 1e6));
};
run("one contiguous copy", false, false);
run("scattered, batched on a stream", true, false);
run("scattered, sync each block", true, true);
return 0;
}
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Builds the registered-kernel test: two shared objects differing ONLY in how many template
# instantiations they hold, and a driver that dlopens both and launches k<0> from each.
#
# gfx1201 is libr4d's target architecture, so the probe is built for it and no other: a launch
# cost measured on a different part would not describe this library.
set -e
CXX=/opt/rocm/lib/llvm/bin/clang++
F="-x hip -O3 -std=c++17 --offload-arch=gfx1201 -isystem /opt/rocm/include --rocm-path=/opt/rocm"
D=$(dirname "$0")
O=${O:-$HOME}
$CXX $F -DNK=2 -fPIC -shared "$D/launchreg_lib.hip" -o "$O/liblr_few.so"
$CXX $F -DNK=512 -fPIC -shared "$D/launchreg_lib.hip" -o "$O/liblr_many.so"
$CXX $F "$D/launchreg.hip" -o "$O/launchreg" -ldl -pthread -Wl,-rpath,"$O"
echo "built in $O"
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# Extract the gfx1201 device code object out of one built HIP host object.
#
# co.sh <path/to/x.hip.o> -> prints the path of the .co it wrote
#
# The device code is a clang offload bundle in the host object's .hip_fatbin section. The bundler
# will not read the host object directly (it finds no bundles and says so), so dump the section
# first and unbundle that. Everything else here reads the .co.
: "${ROCM:=/opt/rocm}"
: "${ISA_ARCH:=gfx1201}"
: "${ISA_OUT:=/tmp/r4disa}"
O="$1"; [ -f "$O" ] || { echo "co.sh: no such object: $O" >&2; exit 1; }
N=$(basename "$O" .hip.o); mkdir -p "$ISA_OUT"
"$ROCM/llvm/bin/llvm-objcopy" --dump-section=.hip_fatbin="$ISA_OUT/$N.fb" "$O" /dev/null 2>/dev/null \
|| { echo "co.sh: $O has no .hip_fatbin (host-only object?)" >&2; exit 1; }
"$ROCM/llvm/bin/clang-offload-bundler" --type=o --unbundle --input="$ISA_OUT/$N.fb" \
--targets="hipv4-amdgcn-amd-amdhsa--$ISA_ARCH" --output="$ISA_OUT/$N.co" || exit 1
rm -f "$ISA_OUT/$N.fb"; echo "$ISA_OUT/$N.co"
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# Disassemble ONE kernel out of one translation unit, into $ISA_OUT/one.s.
#
# BUILD=... dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E
#
# The pattern is a substring of the MANGLED name, which is how a template instantiation is named:
# res.sh prints those, and the template parameter order is in the kernel declaration. llvm-objdump
# --symbolize-operands prints basic-block labels in the same shape as a real symbol header
# (`0000...45110 <L1201>:`), so the kernel ends at the next header that is not an <Lnnn>.
: "${ROCM:=/opt/rocm}"
: "${BUILD:=build}"
: "${ISA_OUT:=/tmp/r4disa}"
TU="$1"; PAT="$2"
here=$(cd "$(dirname "$0")" && pwd)
O=$(find "$BUILD" -name "$TU.hip.o" | head -1)
[ -n "$O" ] || { echo "dis.sh: no translation unit $TU under $BUILD" >&2; exit 1; }
if [ ! -f "$ISA_OUT/$TU.all.s" ] || [ "$O" -nt "$ISA_OUT/$TU.all.s" ]; then
"$here/co.sh" "$O" >/dev/null || exit 1
"$ROCM/llvm/bin/llvm-objdump" -d --symbolize-operands --no-show-raw-insn \
"$ISA_OUT/$TU.co" > "$ISA_OUT/$TU.all.s"
fi
awk -v pat="$PAT" '
/^[0-9a-f]+ <.*>:$/ { if ($2 !~ /^<L[0-9]+>:$/) ink = (index($0, pat) > 0) }
ink { print }
' "$ISA_OUT/$TU.all.s" > "$ISA_OUT/one.s"
n=$(grep -c " " "$ISA_OUT/one.s")
[ "$n" -gt 0 ] || { echo "dis.sh: no kernel matched $PAT in $TU" >&2; exit 1; }
echo "$ISA_OUT/one.s: $n instructions, $(grep -c '^[0-9a-f]* <L' "$ISA_OUT/one.s") blocks"
+50
View File
@@ -0,0 +1,50 @@
#!/bin/sh
# WHERE THE DEVICE IS IDLE, and which op it is waiting for. tsum.sh answers "where does the device
# time go"; this answers the other half.
#
# gaps.sh traces/dec/k_kernel_trace.csv [window_s] [agent]
#
# A gap is start(i) - max(end(0..i-1)) on ONE agent, attributed to the kernel that FOLLOWS it,
# because a kernel that starts late is the one whose dependency was not ready. Two populations come
# out and they want different fixes:
#
# the floor a few microseconds before nearly everything, times the dispatch count. That is
# the hardware launch floor plus rocprofv3's own per-dispatch interception, so
# most of this column is the instrument. Differences of a few tenths of a
# microsecond between kernels here are not results.
# the joins hundreds of microseconds, a handful of times a step, before the SAME few
# kernels. Those are host-site ops and host round trips: the issue thread stopped,
# so the device drained. Interception cannot manufacture a gap that size.
#
# THE CONTEXT COLUMNS ARE THE POINT. A gap before `embed_lookup` says nothing on its own; the three
# kernels BEFORE it name the join -- `rowtopk_merge | copyBuffer => embed_lookup` is a draft loop
# reading a sampled id back to the host, and `ngram_ids => gemm_bf16_nt` is the PLE's host gather
# with the host op invisible in the middle of it.
#
# RESTRICT TO A WINDOW. A traced run is model load, then prefill, then decode; over the whole span
# the busy fraction is dominated by load and means nothing. The default takes the last 3 seconds,
# which on a short generation is decode.
C="$1"; W="${2:-3}"; AG="${3:-Agent 1}"
[ -f "$C" ] || { echo "gaps.sh: no trace $C" >&2; exit 1; }
MX=$(awk -F'"' 'NR>1 && $6 != "" { split($7,p,","); if (p[4]+0>mx) mx=p[4]+0 } END { printf "%.0f", mx }' "$C")
awk -F'"' -v MX="$MX" -v W="$W" -v AG="$AG" '
NR>1 && $6 != "" { split($7,p,","); if (p[3]+0 < MX - W*1e9) next; if ($4 != AG) next
n=$6; gsub(/[ \t]/,"",n); print p[3] "\t" p[4] "\t" substr(n,1,30) }' "$C" \
| sort -n \
| awk -F'\t' '
{ s=$1+0; e=$2+0; k=$3
if (NR>1 && s > pe) { g=s-pe; tot+=g; ng++
if (g > 50000) { key = p2 " | " p1 " => " k; bc[key]++; bt[key]+=g/1000 }
else { fk[k]+=g; fn[k]++ } }
if (e > pe) pe = e
p2=p1; p1=k
}
END {
S = "sort -k1 -nr"
printf "idle %.1f ms over %d gaps in the window\n\nJOINS (gap > 50 us), the context is three kernels deep:\n", tot/1e6, ng
for (q in bc) printf " %7.1f ms %5d %8.1f us %s\n", bt[q]/1000, bc[q], bt[q]/bc[q], q | S
close(S)
printf "\nFLOOR (gap <= 50 us), top by total:\n"
for (q in fn) printf " %7.1f ms %7d %6.2f us %s\n", fk[q]/1e6, fn[q], fk[q]/fn[q]/1000, q | S
close(S)
}'
+296
View File
@@ -0,0 +1,296 @@
// WHAT A DISPATCH COSTS THE HOST TO SUBMIT, and what capturing a fixed sequence saves.
//
// Capture is usually priced against the DEVICE-side gap between dependent kernels, which on this
// part is well under a microsecond and not worth chasing. That is the wrong question for the MTP
// draft loop. There the HOST is on the critical path: every pass embeds the token the previous
// pass sampled, so nothing overlaps the submit, and the device sits idle for the whole of it. The
// trunk never pays that, because it runs well over a thousand dispatches ahead of the device.
//
// So this measures the HOST half: the wall time of the submit loop itself, separated from the sync.
//
// EVERY ARM RUNS ONCE PER ITERATION, IN ONE LOOP. Clock and scheduler state drift between runs by
// more than the differences being measured, so arms taken in sequence are not comparable to each
// other; sharing one loop is what makes them comparable.
//
// individual 45 separate hipLaunchKernelGGL, one per op, as an uncaptured pass issues them.
// graph one captured graph replayed. The floor, and unreachable: the pass is not static.
// graph+Kset replay after rewriting K nodes. About ten of the draft pass's 45 issues move an
// operand pointer every step, and three of those (qsa_work, qsa_score, qsa_select)
// also move a SHAPE, because the QSA extents grow with context and no arena
// discipline makes them stand still. This is the shape a real implementation has.
// graph+Kg+s the same with the params READ BACK from the node first, because the engine holds
// no launch geometry of its own -- the shim marshals its own kernel arguments and
// the runtime never sees the signature. If this costs what Kset costs, that
// ignorance is free and the design needs no ABI change.
// recap+updat re-issue the whole pass under capture and hipGraphExecUpdate the exec. Needs no
// knowledge of which arg slot moved at all, so it is the smallest engine change --
// if appending a node is cheap enough to pay for itself.
//
// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 graphrate.hip -o graphrate
// ./graphrate 45 300 10
#include <hip/hip_runtime.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <vector>
__global__ void tiny(float* p) { if (threadIdx.x == 0) p[blockIdx.x] = 1.0f; }
/* THE SAME KERNEL WITH A REAL ARGUMENT LIST. An engine issue costs several times what `tiny`
* above submits in, and the difference has two possible homes: HIP marshalling more arguments, or
* the plugin shim's own prologue (band checks, grid derivation, the switch that picks a template
* instantiation). They call for completely different work, so they have to be told apart. This
* signature is r4d_qsa_score_bf16's, argument for argument: six pointers and nine scalars. */
__global__ void fat(const float* q, const float* bk, const int* bt, const int* cu, const int* nc,
float* out, int n, int heads, int nb, int nseq, int bpw, int q_ld, int bk_ld,
int bt_ld, int out_ld) {
if (threadIdx.x == 0 && q && bk && bt && cu && nc)
out[blockIdx.x] = (float)(n + heads + nb + nseq + bpw + q_ld + bk_ld + bt_ld + out_ld);
}
/* A kernel SLOW ENOUGH TO BACK THE QUEUE UP. Every arm above syncs each iteration, so the command
* ring is always empty and a submit only ever costs what the runtime spends writing it. A serving
* engine is not in that state: the host runs far ahead of a device that is nearly always busy, and
* a submit into a FULL ring waits for the device to retire a slot. If backpressure is what an
* engine's launch cost actually is, then the shim prologue is not the story and no amount of
* host-side tidying moves it. */
__global__ void slow(float* p, int n) {
float a = (float)threadIdx.x;
for (int i = 0; i < n; ++i) a = fmaf(a, 1.0000001f, 1.0f);
if (a == 12345.678f) p[blockIdx.x] = a;
}
using clk = std::chrono::steady_clock;
static double us_since(clk::time_point a, clk::time_point b) {
return std::chrono::duration<double, std::micro>(b - a).count();
}
/* The median, not the mean: one descheduled iteration is worth thirty clean ones to a mean. */
static double med(std::vector<double>& v) {
if (v.empty()) return 0.0;
std::sort(v.begin(), v.end());
return v[v.size() / 2];
}
int main(int argc, char** argv) {
const int N = argc > 1 ? std::atoi(argv[1]) : 45;
const int iters = argc > 2 ? std::atoi(argv[2]) : 300;
const int K = argc > 3 ? std::atoi(argv[3]) : 10;
float* d = nullptr;
if (hipMalloc(&d, 1024 * sizeof(float)) != hipSuccess) { std::printf("hipMalloc\n"); return 1; }
hipStream_t s;
if (hipStreamCreate(&s) != hipSuccess) { std::printf("hipStreamCreate\n"); return 1; }
std::printf("%d kernels a sequence, %d iterations, %d nodes updated, medians\n", N, iters, K);
hipGraph_t g = nullptr;
hipGraphExec_t ge = nullptr;
if (hipStreamBeginCapture(s, hipStreamCaptureModeGlobal) != hipSuccess) {
std::printf(" capture unsupported\n"); return 0;
}
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
if (hipStreamEndCapture(s, &g) != hipSuccess) { std::printf(" end capture\n"); return 1; }
if (hipGraphInstantiate(&ge, g, nullptr, nullptr, 0) != hipSuccess) {
std::printf(" instantiate\n"); return 1;
}
size_t nn = 0;
if (hipGraphGetNodes(g, nullptr, &nn) != hipSuccess || nn == 0) {
std::printf(" GetNodes\n"); return 1;
}
std::vector<hipGraphNode_t> nodes(nn);
if (hipGraphGetNodes(g, nodes.data(), &nn) != hipSuccess) { std::printf(" nodes\n"); return 1; }
const int k = std::min(K, (int)nn);
std::vector<hipKernelNodeParams> cached(k);
for (int i = 0; i < k; ++i)
if (hipGraphKernelNodeGetParams(nodes[i], &cached[i]) != hipSuccess) {
std::printf(" GetParams -- update arms unavailable\n"); return 1;
}
std::vector<double> a_emit;
std::vector<double> a_frag;
std::vector<double> a_ind, a_fat, a_err, a_gra, a_set, a_gs, a_rec, a_cap, a_upd;
a_ind.reserve(iters);
/* Warm the clocks, the runtime's lazy module load, and every path below. The cards
* idle-suspend, so a timed loop that starts cold reads the governor ramping rather than the
* steady-state rate -- worth most of a factor of two. */
for (int w = 0; w < 400; ++w) {
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
for (int i = 0; i < N; ++i)
hipLaunchKernelGGL(fat, dim3(1), dim3(64), 0, s, d, d, (const int*)d,
(const int*)d, (const int*)d, d, 1, 2, 3, 4, 5, 6, 7, 8, 9);
hipStreamSynchronize(s);
for (int i = 0; i < k; ++i) hipGraphExecKernelNodeSetParams(ge, nodes[i], &cached[i]);
hipGraphLaunch(ge, s);
hipStreamSynchronize(s);
hipGraph_t g2 = nullptr;
hipStreamBeginCapture(s, hipStreamCaptureModeGlobal);
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
hipStreamEndCapture(s, &g2);
hipGraphExecUpdateResult r; hipGraphNode_t bad = nullptr;
hipGraphExecUpdate(ge, g2, &bad, &r);
hipGraphDestroy(g2);
}
/* FOUR GRAPHS OVER THE SAME 45 NODES, because that is the shape the real pass has: three
* all-reduces and a gather cut it into segments, and a graph launch costs about the same
* whatever it contains. Whether that fixed cost, paid once per segment, eats the whole saving
* is what decides whether capturing the pass pays at all. */
hipGraphExec_t gef[4] = {nullptr, nullptr, nullptr, nullptr};
{
const int seg[4] = {3, 17, 13, 12};
for (int q = 0; q < 4; ++q) {
hipGraph_t gq = nullptr;
hipStreamBeginCapture(s, hipStreamCaptureModeGlobal);
for (int i = 0; i < seg[q]; ++i)
hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
hipStreamEndCapture(s, &gq);
hipGraphInstantiate(&gef[q], gq, nullptr, nullptr, 0);
hipGraphDestroy(gq);
}
}
for (int it = 0; it < iters; ++it) {
/* ---- individual, one argument */
auto t0 = clk::now();
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
auto t1 = clk::now();
hipStreamSynchronize(s);
a_ind.push_back(us_since(t0, t1));
/* ---- fifteen arguments, with the error check libr4d puts after every launch. There are
* dozens of those call sites across the library and a single op's path can make several of
* them. If hipGetLastError is a cheap TLS read this arm sits on top of the one above; if
* it is not, it is a tax on every dispatch in the library. */
t0 = clk::now();
for (int i = 0; i < N; ++i) {
hipLaunchKernelGGL(fat, dim3(1), dim3(64), 0, s, d, d, (const int*)d,
(const int*)d, (const int*)d, d, 1, 2, 3, 4, 5, 6, 7, 8, 9);
if (hipGetLastError() != hipSuccess) std::printf(" launch failed\n");
}
t1 = clk::now();
hipStreamSynchronize(s);
a_err.push_back(us_since(t0, t1));
/* ---- fifteen arguments through hipLaunchKernel + kernelParams: EXACTLY what a shim's
* R4D_EMIT does on its LAUNCH path. Every ordinary dispatch pays this while a graph only
* pays back on replay, so if this sits above `fat` the kernelParams path costs the normal
* path more than it can save the captured one. */
t0 = clk::now();
for (int i = 0; i < N; ++i) {
void* pv[15];
void* p0 = d; const int* p1 = (const int*)d;
int i1 = 1, i2 = 2, i3 = 3, i4 = 4, i5 = 5, i6 = 6, i7 = 7, i8 = 8, i9 = 9;
pv[0] = &p0; pv[1] = &p0; pv[2] = &p1; pv[3] = &p1; pv[4] = &p1; pv[5] = &p0;
pv[6] = &i1; pv[7] = &i2; pv[8] = &i3; pv[9] = &i4; pv[10] = &i5;
pv[11] = &i6; pv[12] = &i7; pv[13] = &i8; pv[14] = &i9;
hipLaunchKernel((const void*)fat, dim3(1), dim3(64), pv, 0, s);
}
t1 = clk::now();
hipStreamSynchronize(s);
a_emit.push_back(us_since(t0, t1));
/* ---- individual, fifteen arguments */
t0 = clk::now();
for (int i = 0; i < N; ++i)
hipLaunchKernelGGL(fat, dim3(1), dim3(64), 0, s, d, d, (const int*)d,
(const int*)d, (const int*)d, d, 1, 2, 3, 4, 5, 6, 7, 8, 9);
t1 = clk::now();
hipStreamSynchronize(s);
a_fat.push_back(us_since(t0, t1));
/* ---- the same 45 nodes as FOUR graphs, plus the five dispatches the cuts leave behind */
t0 = clk::now();
for (int q = 0; q < 4; ++q) hipGraphLaunch(gef[q], s);
for (int i = 0; i < 5; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
t1 = clk::now();
hipStreamSynchronize(s);
a_frag.push_back(us_since(t0, t1));
/* ---- graph replay */
t0 = clk::now();
hipGraphLaunch(ge, s);
t1 = clk::now();
hipStreamSynchronize(s);
a_gra.push_back(us_since(t0, t1));
/* ---- graph + K set */
t0 = clk::now();
for (int i = 0; i < k; ++i) hipGraphExecKernelNodeSetParams(ge, nodes[i], &cached[i]);
hipGraphLaunch(ge, s);
t1 = clk::now();
hipStreamSynchronize(s);
a_set.push_back(us_since(t0, t1));
/* ---- graph + K get+set */
t0 = clk::now();
for (int i = 0; i < k; ++i) {
hipKernelNodeParams p;
hipGraphKernelNodeGetParams(nodes[i], &p);
hipGraphExecKernelNodeSetParams(ge, nodes[i], &p);
}
hipGraphLaunch(ge, s);
t1 = clk::now();
hipStreamSynchronize(s);
a_gs.push_back(us_since(t0, t1));
/* ---- recapture + ExecUpdate */
t0 = clk::now();
hipGraph_t g2 = nullptr;
hipStreamBeginCapture(s, hipStreamCaptureModeGlobal);
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(tiny, dim3(1), dim3(64), 0, s, d);
hipStreamEndCapture(s, &g2);
auto tc = clk::now();
hipGraphExecUpdateResult r; hipGraphNode_t bad = nullptr;
const hipError_t e = hipGraphExecUpdate(ge, g2, &bad, &r);
auto tu = clk::now();
hipGraphLaunch(ge, s);
t1 = clk::now();
hipStreamSynchronize(s);
hipGraphDestroy(g2);
if (e != hipSuccess && it == 0) std::printf(" ExecUpdate says %d\n", (int)e);
a_cap.push_back(us_since(t0, tc));
a_upd.push_back(us_since(tc, tu));
a_rec.push_back(us_since(t0, t1));
}
/* ---- SUBMIT UNDER BACKPRESSURE. The same launch, but the device cannot keep up, so the ring
* fills and stays full. Reported per dispatch against the empty-ring arms above. */
std::vector<double> a_bp;
for (int w = 0; w < 20; ++w) {
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(slow, dim3(8), dim3(256), 0, s, d, 4000);
hipStreamSynchronize(s);
}
for (int it = 0; it < iters; ++it) {
/* Do NOT sync: let the queue stay deep across iterations, the way a decode step does. */
const auto t0 = clk::now();
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(slow, dim3(8), dim3(256), 0, s, d, 4000);
const auto t1 = clk::now();
a_bp.push_back(us_since(t0, t1));
}
hipStreamSynchronize(s);
const double ind = med(a_ind);
auto row = [&](const char* nm, std::vector<double>& v) {
const double m = med(v);
std::printf(" %-12s submit %7.1f us (%5.2f us a dispatch) %+6.1f us vs individual\n",
nm, m, m / N, m - ind);
};
row("individual", a_ind);
row("ind 15 args", a_fat);
row("emit 15 args", a_emit);
row("+GetLastError", a_err);
row("graph", a_gra);
row("4 graphs+5", a_frag);
row("graph+set", a_set);
row("graph+get+set", a_gs);
row("recap+update", a_rec);
row("full ring", a_bp);
std::printf(" %-12s of which capture %6.1f us (%4.2f us a node), ExecUpdate %6.1f us\n",
"", med(a_cap), med(a_cap) / N, med(a_upd));
return 0;
}
+95
View File
@@ -0,0 +1,95 @@
// What one instruction slot is worth on gfx1201, so that an instruction COUNT taken out of a
// disassembly can be turned into a time.
//
// A GEMM's staged K tile is a few dozen v_wmma inside several hundred other instructions, so
// whether trimming the shell is worth anything depends entirely on what a wmma costs relative to a
// plain VALU op -- and that ratio is not in any public table for this part. So measure it: run each
// instruction back to back in independent chains (nothing to stall on but issue) and report the
// rate. The RATIO is what matters and it is clock-independent, which is why no clock is read here.
//
// Occupancy is a parameter because a real tile kernel runs at 2 waves a SIMD (36864 B of LDS) and a
// microbenchmark at 8 would answer a different question.
#include <hip/hip_runtime.h>
#include <cstdio>
#include <cstdlib>
typedef int i2v __attribute__((ext_vector_type(2)));
typedef float f8v __attribute__((ext_vector_type(8)));
template <int LDS>
__global__ __launch_bounds__(256) void wmma_rate(float* out, int iters) {
__shared__ char pad[LDS ? LDS : 4];
pad[threadIdx.x & 3] = (char)threadIdx.x;
i2v a, b;
a[0] = 0x01010101; a[1] = 0x02020202;
b[0] = 0x03030303; b[1] = 0x04040404;
f8v c0{}, c1{}, c2{}, c3{}, c4{}, c5{}, c6{}, c7{};
for (int i = 0; i < iters; ++i) {
c0 = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c0);
c1 = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c1);
c2 = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c2);
c3 = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c3);
c4 = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c4);
c5 = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c5);
c6 = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c6);
c7 = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c7);
}
float s = 0;
for (int t = 0; t < 8; ++t) s += c0[t] + c1[t] + c2[t] + c3[t] + c4[t] + c5[t] + c6[t] + c7[t];
if (s == -1.0f) out[0] = s + (float)pad[0];
}
template <int LDS>
__global__ __launch_bounds__(256) void valu_rate(float* out, int iters) {
__shared__ char pad[LDS ? LDS : 4];
pad[threadIdx.x & 3] = (char)threadIdx.x;
float x0 = threadIdx.x, x1 = x0 + 1, x2 = x0 + 2, x3 = x0 + 3;
float x4 = x0 + 4, x5 = x0 + 5, x6 = x0 + 6, x7 = x0 + 7;
const float k = 1.0000001f;
// Eight independent chains, eight ops an iteration -- the same shape as the wmma loop so the
// two numbers differ only in the instruction being issued.
for (int i = 0; i < iters; ++i) {
x0 *= k; x1 *= k; x2 *= k; x3 *= k; x4 *= k; x5 *= k; x6 *= k; x7 *= k;
}
const float s = x0 + x1 + x2 + x3 + x4 + x5 + x6 + x7;
if (s == -1.0f) out[0] = s + (float)pad[0];
}
static float bench(void (*k)(float*, int), float* d, int iters, int blocks, int reps) {
hipEvent_t a, b; hipEventCreate(&a); hipEventCreate(&b);
hipLaunchKernelGGL(k, dim3(blocks), dim3(256), 0, 0, d, iters); // warm
hipDeviceSynchronize();
float best = 1e30f;
for (int r = 0; r < reps; ++r) {
hipEventRecord(a);
hipLaunchKernelGGL(k, dim3(blocks), dim3(256), 0, 0, d, iters);
hipEventRecord(b); hipEventSynchronize(b);
float ms = 0; hipEventElapsedTime(&ms, a, b);
if (ms < best) best = ms;
}
return best;
}
int main(int argc, char** argv) {
const int iters = argc > 1 ? atoi(argv[1]) : 20000;
const int blocks = argc > 2 ? atoi(argv[2]) : 1024;
float* d = nullptr; hipMalloc(&d, 4);
printf(" gfx1201 issue rate, %d blocks x 256 threads, %d iterations x 8 instructions\n\n",
blocks, iters);
printf(" %-22s %10s %14s %12s %10s\n", "instruction", "ms", "Ginstr/s", "TFLOP/s", "vs VALU");
const double n = (double)iters * 8.0 * blocks * 8.0; // 8 waves a block, 8 instr an iteration
struct { const char* nm; float ms; double flop; } row[4];
row[0] = { "v_wmma fp8 (0 LDS)", bench(wmma_rate<0>, d, iters, blocks, 5), 8192.0 };
row[1] = { "v_wmma fp8 (36 KiB)", bench(wmma_rate<36864>, d, iters, blocks, 5), 8192.0 };
row[2] = { "v_mul_f32 (0 LDS)", bench(valu_rate<0>, d, iters, blocks, 5), 64.0 };
row[3] = { "v_mul_f32 (36 KiB)", bench(valu_rate<36864>, d, iters, blocks, 5), 64.0 };
double vbase = 0;
for (int i = 0; i < 4; ++i) {
const double gi = n / (row[i].ms * 1e6);
if (i == 2) vbase = gi;
printf(" %-22s %10.3f %14.2f %12.1f %9.2fx\n", row[i].nm, row[i].ms, gi,
n * row[i].flop / (row[i].ms * 1e-3) / 1e12, vbase > 0 ? vbase / gi : 0.0);
}
printf("\n \"vs VALU\" is how many v_mul_f32 issue slots one of these costs.\n");
return 0;
}
+156
View File
@@ -0,0 +1,156 @@
// DOES A LAUNCH COST MORE WHEN THE MODULE REGISTERS MORE KERNELS, and does crossing into a shared
// object cost anything at all?
//
// The engine issues a launch for roughly twice what the same shape costs in a self-contained
// binary, and the excess is roughly CONSTANT across kernels of very different shapes -- the
// signature of a fixed per-issue tax rather than of anything a particular shim does. The error
// check after every launch, a full command ring and the argument count together do not account for
// it.
//
// The structural difference this isolates is the MODULE. libr4d is a .so holding every template
// instantiation of every kernel, entered through a function pointer; a self-contained harness has
// a handful of kernels compiled into the binary that launches them. HIP resolves a launch by
// looking the host stub up in the table __hipRegisterFunction fills, so a bigger table is a
// plausible tax -- and if it is the tax, the lever is fewer instantiations, not tidier shims.
//
// see build_launchreg.sh
#include <hip/hip_runtime.h>
#include <dlfcn.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <atomic>
#include <thread>
#include <vector>
__global__ void local_k(float* p) { if (threadIdx.x == 0) p[blockIdx.x] = 1.0f; }
using clk = std::chrono::steady_clock;
static double us_since(clk::time_point a, clk::time_point b) {
return std::chrono::duration<double, std::micro>(b - a).count();
}
static double med(std::vector<double>& v) {
if (v.empty()) return 0.0;
std::sort(v.begin(), v.end());
return v[v.size() / 2];
}
typedef int (*LaunchFn)(void*, void*);
typedef int (*DistinctFn)(void*, void*, int);
typedef int (*CountFn)(void);
struct Lib {
const char* path;
void* h = nullptr;
LaunchFn fn = nullptr;
DistinctFn dfn = nullptr;
int nreg = 0;
};
int main(int argc, char** argv) {
const int N = argc > 1 ? std::atoi(argv[1]) : 45;
const int iters = argc > 2 ? std::atoi(argv[2]) : 300;
float* d = nullptr;
if (hipMalloc(&d, 1024 * sizeof(float)) != hipSuccess) { std::printf("hipMalloc\n"); return 1; }
hipStream_t s;
if (hipStreamCreate(&s) != hipSuccess) { std::printf("hipStreamCreate\n"); return 1; }
Lib few{"./liblr_few.so"}, many{"./liblr_many.so"};
for (Lib* L : {&few, &many}) {
L->h = dlopen(L->path, RTLD_NOW);
if (!L->h) { std::printf("dlopen %s: %s\n", L->path, dlerror()); return 1; }
L->fn = (LaunchFn)dlsym(L->h, "lr_launch");
L->dfn = (DistinctFn)dlsym(L->h, "lr_launch_distinct");
CountFn c = (CountFn)dlsym(L->h, "lr_registered");
if (!L->fn || !c) { std::printf("dlsym %s\n", L->path); return 1; }
L->nreg = c();
}
std::printf("%d launches a sequence, %d iterations, medians\n", N, iters);
std::printf(" few = %d instantiations, many = %d\n", few.nreg, many.nreg);
/* Warm every path: clocks, lazy module load for BOTH objects, and the code itself. */
for (int w = 0; w < 400; ++w) {
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(local_k, dim3(1), dim3(64), 0, s, d);
for (int i = 0; i < N; ++i) few.fn(d, s);
for (int i = 0; i < N; ++i) many.fn(d, s);
many.dfn(d, s, N);
hipStreamSynchronize(s);
}
std::vector<double> a_loc, a_few, a_many, a_dist;
for (int it = 0; it < iters; ++it) { /* interleaved, one loop, shared clock state */
auto t0 = clk::now();
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(local_k, dim3(1), dim3(64), 0, s, d);
auto t1 = clk::now();
hipStreamSynchronize(s);
a_loc.push_back(us_since(t0, t1));
t0 = clk::now();
for (int i = 0; i < N; ++i) few.fn(d, s);
t1 = clk::now();
hipStreamSynchronize(s);
a_few.push_back(us_since(t0, t1));
t0 = clk::now();
for (int i = 0; i < N; ++i) many.fn(d, s);
t1 = clk::now();
hipStreamSynchronize(s);
a_many.push_back(us_since(t0, t1));
t0 = clk::now();
many.dfn(d, s, N);
t1 = clk::now();
hipStreamSynchronize(s);
a_dist.push_back(us_since(t0, t1));
}
/* ---- A SECOND SUBMITTING THREAD. The last structural difference between this harness and the
* engine: --tp 2 runs two rank threads, each issuing onto its own stream, and every arm above
* is single-threaded. If HIP takes a process-wide lock on the submit path then a launch costs
* what it costs plus whatever the other rank is holding -- which would be a fixed tax, present
* on every kernel however small, which is exactly the shape the excess has. The second
* thread runs the identical loop on its OWN stream and is not measured; only rank 0 is. */
hipStream_t s2;
if (hipStreamCreate(&s2) != hipSuccess) { std::printf("second stream\n"); return 1; }
std::atomic<bool> run{true};
std::atomic<long> other{0};
std::thread rank1([&] {
while (run.load(std::memory_order_relaxed)) {
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(local_k, dim3(1), dim3(64), 0, s2, d);
hipStreamSynchronize(s2);
other.fetch_add(N, std::memory_order_relaxed);
}
});
std::vector<double> a_tp2;
for (int w = 0; w < 200; ++w) {
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(local_k, dim3(1), dim3(64), 0, s, d);
hipStreamSynchronize(s);
}
for (int it = 0; it < iters; ++it) {
const auto t0 = clk::now();
for (int i = 0; i < N; ++i) hipLaunchKernelGGL(local_k, dim3(1), dim3(64), 0, s, d);
const auto t1 = clk::now();
hipStreamSynchronize(s);
a_tp2.push_back(us_since(t0, t1));
}
run.store(false);
rank1.join();
const double loc = med(a_loc);
auto row = [&](const char* nm, std::vector<double>& v) {
const double m = med(v);
std::printf(" %-22s %7.1f us (%5.3f us a launch) %+6.3f us a launch vs in-binary\n",
nm, m, m / N, (m - loc) / N);
};
row("in-binary", a_loc);
row("so, few kernels", a_few);
row("so, many kernels", a_many);
row("so, 45 DISTINCT", a_dist);
row("in-binary, 2 threads", a_tp2);
std::printf(" the second thread submitted %ld launches while that arm ran\n",
other.load());
return 0;
}
+61
View File
@@ -0,0 +1,61 @@
// THE LIBRARY HALF of the registered-kernel test. Built twice, at -DNK=2 and -DNK=512, and
// dlopen'd -- because that is libr4d's actual shape: a shared object holding every template
// instantiation of every kernel, entered through a function pointer.
//
// Both builds launch THE SAME kernel, k<0>, with the same arguments. The only difference is how
// many other instantiations sit in the module beside it.
#include <hip/hip_runtime.h>
template <int I>
__global__ void k(float* p) { if (threadIdx.x == 0) p[blockIdx.x] = (float)I; }
/* The table exists to keep the instantiations alive. Without a use, the compiler drops every k<I>
* that is never launched and both builds register one kernel. */
static const void* g_tab[NK];
template <int I>
struct Reg {
static void go() { g_tab[I] = (const void*)k<I>; Reg<I - 1>::go(); }
};
template <>
struct Reg<0> {
static void go() { g_tab[0] = (const void*)k<0>; }
};
/* A THUNK PER INSTANTIATION. The arms above launch one kernel over and over, which is the one
* thing a decode step never does: it issues forty-five DIFFERENT kernels, each through its own
* shim, each with its own argument buffer and its own host stub. Everything the tight loop keeps
* in L1 -- the code, the stub, the args -- is cold on every one of those. This makes that
* difference, and only that difference, measurable. */
typedef void (*Thunk)(float*, hipStream_t);
template <int I>
static void thunk(float* p, hipStream_t st) {
hipLaunchKernelGGL(k<I>, dim3(1), dim3(64), 0, st, p);
}
static Thunk g_thunk[NK];
template <int I>
struct RegT {
static void go() { g_thunk[I] = &thunk<I>; RegT<I - 1>::go(); }
};
template <>
struct RegT<0> {
static void go() { g_thunk[0] = &thunk<0>; }
};
extern "C" int lr_launch_distinct(void* p, void* stream, int n) {
for (int i = 0; i < n; ++i) g_thunk[i % NK]((float*)p, (hipStream_t)stream);
return 0;
}
extern "C" int lr_registered(void) {
Reg<NK - 1>::go();
RegT<NK - 1>::go();
int live = 0;
for (int i = 0; i < NK; ++i) live += g_tab[i] != 0;
return live;
}
extern "C" int lr_launch(void* p, void* stream) {
hipLaunchKernelGGL(k<0>, dim3(1), dim3(64), 0, (hipStream_t)stream, (float*)p);
return 0;
}
+46
View File
@@ -0,0 +1,46 @@
#!/bin/sh
# Isolate the working loop of $ISA_OUT/one.s and classify its body.
#
# loop.sh [anchor-regex] default anchor: v_wmma
#
# A "largest backward branch" search finds the EPILOGUE, not the K loop -- the epilogue is a long
# unrolled store chain and the K loop is short. So anchor on the instruction that defines the loop
# and take the smallest backward branch that contains every one of them.
: "${ISA_OUT:=/tmp/r4disa}"
A="${1:-v_wmma}"
awk -v anchor="$A" -v out="$ISA_OUT" '
/^[0-9a-f]+ <L[0-9]+>:$/ { lbl = $2; gsub(/[<>:]/, "", lbl); line[lbl] = NR; next }
$0 ~ anchor { anc[++na] = NR }
/s_cbranch|s_branch/ { for (i = 1; i <= NF; i++) if ($i ~ /^L[0-9]+$/) { t = $i
if (t in line && line[t] < NR) { nl++; lo[nl] = line[t]; hi[nl] = NR; nm[nl] = t } } }
END {
if (na == 0) { print "loop.sh: no " anchor " in this kernel" > "/dev/stderr"; exit 1 }
best = -1
for (i = 1; i <= nl; i++) { c = 0
for (j = 1; j <= na; j++) if (anc[j] >= lo[i] && anc[j] <= hi[i]) c++
if (c == na && (best < 0 || hi[i] - lo[i] < best)) { best = hi[i] - lo[i]; bi = i } }
if (best < 0) { print "loop.sh: no single loop holds every " anchor > "/dev/stderr"; exit 1 }
printf "loop %s: %d instructions, %d %s\n", nm[bi], best, na, anchor
printf "%d %d\n", lo[bi], hi[bi] > (out "/range")
}' "$ISA_OUT/one.s" || exit 1
read LO HI < "$ISA_OUT/range"
sed -n "${LO},${HI}p" "$ISA_OUT/one.s" > "$ISA_OUT/loop.s"
awk '{ sub(/^[ \t]+/, "", $0); split($0, a, /[ \t]/); op = a[1]
if (op == "" || op ~ /^[;\/]/) next
if (op ~ /^global_load/) c = "global_load"
else if (op ~ /^global_store/) c = "global_store"
else if (op ~ /^ds_load/) c = "ds_load"
else if (op ~ /^ds_store/) c = "ds_store"
else if (op ~ /^scratch_/) c = "SCRATCH"
else if (op ~ /^v_wmma/) c = "wmma"
else if (op ~ /^s_wait/) c = "s_wait"
else if (op ~ /^s_delay/) c = "s_delay"
else if (op ~ /^s_barrier/) c = "barrier"
else if (op ~ /^v_/) c = "valu"
else if (op ~ /^s_/) c = "salu"
else c = "other"
cnt[c]++; tot++; det[c "|" op]++ }
END { for (k in cnt) printf " %-13s %5d\n", k, cnt[k] | "sort -k2 -nr"; close("sort -k2 -nr")
printf " %-13s %5d\n\n top ops:\n", "TOTAL", tot
for (k in det) { split(k, p, "|"); printf " %-34s %4d\n", p[2], det[k] | "sort -k2 -nr" } }' \
"$ISA_OUT/loop.s" | head -34
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# One row per device kernel in a build tree: VGPRs, SGPRs, LDS bytes, scratch bytes, spilled
# registers, the waves a SIMD the VGPR count alone allows, and the workgroup size.
#
# BUILD=/path/to/build res.sh
#
# SPILL IS THE LOUD COLUMN, and SCRATCH after it: spilled registers are a memory round trip the
# source does not show, and scratch without spills is a private array the compiler could not keep
# in registers. WAVES is the other one: on gfx1201 a SIMD has 1536 VGPRs in wave32 allocated in
# groups of 8, so 256 VGPRs is 6 waves and 128 is 12 -- and LDS can cut it further, which this
# column does NOT model.
#
# The metadata is msgpack printed as YAML and its keys are ALPHABETICAL, so .vgpr_count comes after
# .symbol and .sgpr_count before it. Emitting a row at .symbol prints the previous kernel's VGPR
# count. The row is flushed at .wavefront_size, which is last.
: "${ROCM:=/opt/rocm}"
: "${BUILD:=build}"
: "${ISA_OUT:=/tmp/r4disa}"
D="$ISA_OUT/res"; rm -rf "$D"; mkdir -p "$D"
here=$(cd "$(dirname "$0")" && pwd)
for o in $(find "$BUILD" -name '*.hip.o'); do
n=$(basename "$o" .hip.o)
ISA_OUT="$D" "$here/co.sh" "$o" >/dev/null 2>&1 || continue
"$ROCM/llvm/bin/llvm-readelf" --notes "$D/$n.co" 2>/dev/null > "$D/$n.md"
done
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' vgpr sgpr lds scratch spill waves wg kernel
awk -v OFS='\t' '
/^ *\.group_segment_fixed_size:/ { lds = $2 }
/^ *\.private_segment_fixed_size:/ { sc = $2 }
/^ *\.sgpr_count:/ { s = $2 }
/^ *\.sgpr_spill_count:/ { ss = $2 }
/^ *\.vgpr_count:/ { v = $2 }
/^ *\.vgpr_spill_count:/ { vs = $2 }
/^ *\.max_flat_workgroup_size:/ { wg = $2 }
/^ *\.name:/ { nm = $2 }
/^ *\.wavefront_size:/ { if (nm != "") { g = int((v + 7) / 8) * 8; w = (g > 0) ? int(1536 / g) : 16
if (w > 16) w = 16
print v, s, lds, sc, vs + ss, w, wg, nm; nm = "" } }
' "$D"/*.md | sort -k5,5nr -k4,4nr -k1,1nr
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# Per-kernel device time on each agent, and the gap between them. A rank-asymmetric all-reduce is
# a work imbalance somewhere ELSE, and this is what says where.
#
# ./rskew.sh traces/dec/k_kernel_trace.csv
#
# READ THE ALL-REDUCE ROW FIRST AND READ IT BACKWARDS. The rank with MORE time inside the
# collective is the one that arrived early and waited; the slow rank is the other one. Every other
# row then says what the slow rank is doing that the fast one is not.
#
# ONLY ROWS OVER 20 ms TOTAL ARE PRINTED. Below that the gap is dominated by how many dispatches
# happened to land either side of the trace window and means nothing.
#
# WHAT A REAL IMBALANCE LOOKS LIKE: five rows well outside 1% and everything else inside it. If
# EVERY row is skewed by a similar percentage you are looking at two cards at different clocks or
# one driving a display, not at a work imbalance -- check that the rows reading VRAM-resident
# weights (hc_read_a, hc_up, lm_wmma) are symmetric before believing any of the rest.
#
# The CSV is trace.sh's. Commas inside the quoted kernel name break -F, so this splits on the
# quote: $4 is the agent, $6 the kernel name, $7 the tail, and p[3]/p[4] its start and end.
awk -F'"' '
NR>1 && NF>=7 {
nm=$6; split($7,p,","); d=(p[4]-p[3])/1000.0; ag=$4;
sub(/^void /,"",nm); gsub(/\(anonymous namespace\)::/,"",nm); sub(/[<(].*/,"",nm);
if (ag=="Agent 1") { a[nm]+=d } else { b[nm]+=d }
}
END{
printf "%-42s %10s %10s %9s %7s\n", "kernel", "agent1 ms", "agent2 ms", "gap ms", "gap%";
for (k in a) {
if (a[k]+b[k] < 20000) continue;
g=(b[k]-a[k])/1000.0; m=(a[k]>b[k]?a[k]:b[k])/1000.0;
printf "%-42s %10.1f %10.1f %9.1f %6.1f%%\n", k, a[k]/1000.0, b[k]/1000.0, g, 100.0*g/m;
}
}' "$1" | sort -k4 -g
+77
View File
@@ -0,0 +1,77 @@
#!/bin/sh
# Run a command under rocprofv3's kernel trace and leave a CSV that tsum.sh reads.
#
# ./trace.sh traces/dec -- ./bin/radiance --model ... --port 8113
# ./trace.sh traces/perf -- build/bin/r4d_selftest libr4d.so --perf 17408 5120 8
#
# WHAT IT IS FOR. Device-side, per-kernel dispatch records: begin/end timestamps off the hardware
# dispatch packet, plus the VGPR/LDS/scratch/grid of the instantiation that ACTUALLY ran. res.sh
# can only report every instantiation in the object and leave the reader to guess which one the
# engine picked; the engine's own --profile-ops is host-side and per-issue-site and restores a sync
# per call, which is what makes it oversell collectives.
#
# --kernel-trace WORKS UNMASKED; --pmc DOES NOT WORK AT ALL. There are no hardware counters
# available here: any counter set, any kernel filter, hangs in queue-sync and aborts. The abort
# that names an unsupported agent
#
# rocprofiler_iterate_agent_supported_counters failed for agent 3 (gfx1036)
# terminate called after throwing an instance of 'std::out_of_range'
#
# is COUNTER enumeration and appears only under --pmc. It names a display GPU integrated on the
# CPU, which has no counter support; masking it does not make --pmc work, and --kernel-trace never
# needed it masked. ROCR_VISIBLE_DEVICES=0,1 below pins the agent set to the two discrete cards and
# keeps that line out of the log, nothing more. rocprofv3 is NOT on PATH; it is $ROCM/bin/rocprofv3.
#
# THE TRACE CAN GO QUIET AND STILL LOOK COMPLETE, and nothing in the file says so. A server that
# idles before its request records the STARTUP and nothing else -- contiguous dispatch ids, a
# well-formed CSV, and not one of the decode steps that followed. Drive the workload the MOMENT
# health answers, keep the run short, and check tsum.sh's "dispatches/step" against what the model
# should issue before believing any table built from it. A live decode trace of ~110 steps is about
# 80 MB; a much smaller file has not recorded what it appears to have.
#
# IT IS NOT FREE, AND THE TWO HALVES OF THE ANSWER ARE PERTURBED DIFFERENTLY. Interception costs a
# couple of microseconds per dispatch per RANK. The ranks are separate host threads and inflate in
# parallel, so it is per-rank dispatches that count, not the total. Kernel DURATIONS are hardware
# timestamps and do not move; the GAPS between them absorb all of the overhead. So read busy time
# as real and idle time as an upper bound -- tsum.sh prints both and says so. Generated text is
# unchanged under tracing, so a traced run can be pointed at a real serving configuration.
#
# TO TRACE THE ENGINE, LET THE SERVER EXIT CLEANLY. The CSV is written in rocprofv3's finalisation,
# so start the server under this script, drive it with curl, then `pkill -f "bin/radianc[e]"` --
# SIGTERM. A `pkill -9` kills the process before it finalises and there is no trace at all. Budget
# ~20 s after the kill before the file appears; a decode run writes about 85 MB a minute.
#
# ALWAYS CHECK FOR A ZOMBIE AFTERWARDS -- this script does it, and it matters because a hung
# rocprofv3 ignores its own `timeout`: the hang is in finalisation, after the alarm has fired, so
# the process can outlive its harness indefinitely.
#
# AND THE ZOMBIE'S SYMPTOM IS NOT "TRACING IS BROKEN", IT IS A CORRECTNESS FAILURE IN THE NEXT TOOL
# RUN. A traced server that survived its harness still holds both cards' VRAM, so a rad-kbench gate
# after it reports a mass of skips and FAIL lines against named kernels -- which is what a
# miscompiled kernel looks like. The tell is in the reasons: `no device memory for this case`,
# `device error` and `refused a geometry its constraints accept` on kernels nothing touched. Kill
# the zombie and the same binary passes. Check `pgrep -af bin/radiance` BEFORE believing a gate.
: "${ROCM:=/opt/rocm}"
[ $# -ge 3 ] || { echo "usage: trace.sh OUTDIR -- cmd [args...]" >&2; exit 2; }
OUT=$1; shift
[ "$1" = "--" ] || { echo "trace.sh: expected -- before the command" >&2; exit 2; }
shift
rm -rf "$OUT"; mkdir -p "$OUT" || exit 1
# A decode run writes ~85 MB of CSV a minute. Refuse rather than fill the disk out from under the
# engine.
free=$(df -Pk "$OUT" | awk 'NR==2 { print int($4 / 1024) }')
[ "${free:-0}" -ge 4096 ] || { echo "trace.sh: only ${free} MiB free under $OUT, refusing" >&2; exit 1; }
ROCR_VISIBLE_DEVICES="${ROCR_VISIBLE_DEVICES:-0,1}" "$ROCM/bin/rocprofv3" \
--kernel-trace --output-format csv -d "$OUT" -o k -- "$@"
rc=$?
# The hang is in finalisation; nothing else clears it.
if pgrep -f rocprofv3 >/dev/null 2>&1; then
echo "trace.sh: rocprofv3 did not finalise, killing" >&2
pkill -9 -f rocprofv3
fi
ls "$OUT"/k_kernel_trace.csv >/dev/null 2>&1 || { echo "trace.sh: no trace written (did the command launch any kernels?)" >&2; exit 1; }
echo "trace.sh: rc=$rc $(wc -l < "$OUT/k_kernel_trace.csv") dispatches $(du -h "$OUT/k_kernel_trace.csv" | cut -f1)"
exit $rc
+142
View File
@@ -0,0 +1,142 @@
#!/bin/sh
# Summarise a trace.sh kernel trace over a STEADY-STATE window: where the device time goes, what
# each kernel was actually launched as, and how much of the step is not kernel time at all.
#
# ./tsum.sh traces/dec/k_kernel_trace.csv
# MARK=r4d_rowtopk_stage1 STEPS=20 TOP=40 ./tsum.sh traces/dec/k_kernel_trace.csv
#
# WHY A WINDOW AND NOT THE WHOLE RUN. A traced engine run is model load, then prefill, then decode,
# then whatever the harness did last, and rocprofv3's own --stats averages all of it together, so
# its per-kernel shares describe no step that ever ran. This picks a marker kernel that fires
# exactly ONCE PER DECODE STEP (the sampler's stage-1 top-k), finds the longest contiguous run of
# intervals within 25% of the median, and reports per-step numbers over STEPS of them taken from
# the middle -- steady state, with the clock ramp at the start of a run excluded.
# The marker fires once per rank per step, so the scan takes the FIRST rank it sees and ignores
# the other -- interleaving two ranks' markers would make every second interval near zero and the
# median meaningless. The window is then a wall-clock range and the table covers both ranks in it.
# If the marker never fires -- an r4d_selftest --perf run has no sampler in it -- it falls back to
# the whole trace and every number is per RUN rather than per step, which is what isolation wants.
#
# READ BUSY AND IDLE DIFFERENTLY. Kernel durations come off the hardware dispatch packet and are
# not perturbed by tracing. The gaps between them absorb the whole interception cost, so IDLE IS
# AN UPPER BOUND. OVERUS is that cost per dispatch per rank, and it is a CALIBRATION: it is the
# traced-minus-untraced step time divided by the dispatches one rank issues in a step, and it has
# to be re-derived for a configuration that differs. The ranks are separate host threads and
# inflate in parallel, so it is per-RANK dispatches that count, not the total. A traced ms/step is
# not a result -- take the step time from an untraced harness and use this to say where the time
# inside it went.
#
# BUSY IS A UNION, NOT A SUM. Two dispatches can overlap on one agent, so busy is the union of the
# intervals. The per-kernel column IS a plain sum across BOTH ranks, and pct is that kernel's share
# of all device time, so the column sums to 100% and a rank's share of it is half that.
#
# AND BUSY IS OCCUPANCY-BLIND, WHICH IS THE EASIEST WAY TO MISREAD THIS TABLE. A dispatch counts
# as busy if it is resident at all, so a 5 us kernel holding 1 of 64 CUs reads exactly like the
# GEMM saturating the card. "96% busy" therefore means the step is almost never WAITING for a
# launch -- it does NOT mean the machine is 96% utilised, and it is not an argument that there is
# no headroom. The blocks column is what to look at for that: blocks below ~64 is a kernel that
# cannot fill the device no matter how long it runs.
: "${ISA_OUT:=/tmp/r4disa}"
: "${MARK:=r4d_rowtopk_stage1}"
: "${STEPS:=20}"
: "${TOP:=32}"
: "${OVERUS:=2.0}"
F="${1:?usage: tsum.sh k_kernel_trace.csv}"
D="$ISA_OUT/trace"; rm -rf "$D"; mkdir -p "$D" || exit 1
# agent start end vgpr lds scratch blocks name
# Names arrive as a full C++ signature. "(anonymous namespace)::" has to come off BEFORE the
# signature is cut at its first '(' -- otherwise every kernel in that namespace truncates to
# "void " and the whole trace lands in one empty bucket. The SPACES have to go too: the
# aggregating awk below splits on whitespace and a template argument list is full of them, so
# "<false, true, 1u," would collapse every fp8 GEMM shape into a single row.
awk -F'"' -v OFS='\t' '
function blocks(b, x, y, z) { x = (b[10] > 0) ? b[13] / b[10] : 0; y = (b[11] > 0) ? b[14] / b[11] : 1
z = (b[12] > 0) ? b[15] / b[12] : 1; return int(x * y * z) }
NR == 1 || $2 != "KERNEL_DISPATCH" { next }
{ split($7, b, ",")
n = $6
gsub(/\(anonymous namespace\)::/, "", n)
sub(/^void /, "", n)
sub(/\(.*$/, "", n)
gsub(/ /, "", n)
a = $4; gsub(/[^0-9]/, "", a)
print a, b[3], b[4], b[7], b[5], b[6], blocks(b), n }
' "$F" > "$D/rec" || exit 1
[ -s "$D/rec" ] || { echo "tsum.sh: no KERNEL_DISPATCH rows in $F" >&2; exit 1; }
sort -k1,1n -k2,2n "$D/rec" > "$D/srec"
awk -v mark="$MARK" -v want="$STEPS" '
{ if (lo0 == 0 || $2 < lo0) lo0 = $2; if ($3 > hi0) hi0 = $3 }
$8 ~ mark { if (ma == "") ma = $1; if ($1 == ma) m[++n] = $2 } # ONE rank: see the note above
END {
if (n < 4) { print "tsum.sh: marker " mark " fired " n + 0 " times -- whole trace, per-run numbers" > "/dev/stderr"; printf "%d %d 1 run\n", lo0, hi0; exit 0 }
for (i = 1; i < n; i++) { d[i] = m[i+1] - m[i]; s[i] = d[i] }
for (i = 1; i < n - 1; i++) for (j = i + 1; j < n; j++) if (s[j] < s[i]) { t = s[i]; s[i] = s[j]; s[j] = t }
med = s[int(n / 2)]
run = 0; best = 0
for (i = 1; i < n; i++) {
if (d[i] > med * 0.75 && d[i] < med * 1.25) { if (++run > best) { best = run; be = i } }
else run = 0 }
if (best < 3) { print "tsum.sh: no steady run at median " med / 1e6 " ms -- whole trace, per-run numbers" > "/dev/stderr"; printf "%d %d 1 run\n", lo0, hi0; exit 0 }
bs = be - best + 1
k = (best < want) ? best : want
lo = bs + int((best - k) / 2); hi = lo + k
printf "%d %d %d step\n", m[lo], m[hi], k }
' "$D/srec" > "$D/win" || exit 1
read T0 T1 NSTEP MODE < "$D/win"
awk -v t0="$T0" -v t1="$T1" -v nstep="$NSTEP" -v top="$TOP" -v overus="$OVERUS" -v mode="$MODE" '
# THE ROW IS ONE (KERNEL, GRID), NOT ONE KERNEL. One instantiation serves many shapes -- the
# narrow fp8 GEMM runs six distinct N a step -- and averaging them together produces a rate that
# describes none of them, which is the same mistake as averaging prefill into decode. The grid is
# the only shape the trace carries, and for the narrow GEMM it IS N: blocks * MW * 16.
# `min us` is there because a decision rests on the minimum, never the mean: a traced run throws
# multi-microsecond outliers that are not independent between repeats, so a mean of them is not
# a rate.
$2 >= t0 && $3 <= t1 {
dur = $3 - $2; k = $8 "\t" $7
c[k]++; tot[k] += dur; nd++; all += dur
if (!(k in mn) || dur < mn[k]) mn[k] = dur
vg[k] = $4; lds[k] = $5; sc[k] = $6; bl[k] = $7; nm[k] = $8
a = $1
if (!(a in seen)) { seen[a] = 1; na++ }
nda[a]++
if ($2 > hiend[a]) { busy[a] += dur; hiend[a] = $3 }
else if ($3 > hiend[a]) { busy[a] += $3 - hiend[a]; hiend[a] = $3 }
}
END {
st = (mode == "step") ? "step" : "run"
wall = (t1 - t0) / 1e6 / nstep
printf "%s %d %ss %.3f ms/%s traced %d dispatches/%s over %d ranks (%d a rank)\n\n",
(mode == "step") ? "window" : "whole trace,", nstep, st, wall, st,
int(nd / nstep + 0.5), st, na, int(nd / na / nstep + 0.5)
printf "%8s %9s %8s %8s %7s %5s %6s %5s %7s %s\n",
"calls/" st, "us/" st, "avg us", "min us", "pct", "vgpr", "lds", "scr", "blocks",
"kernel"
for (k in c)
printf "%8.1f %9.1f %8.1f %8.1f %6.2f%% %5d %6d %5d %7d %s\n",
c[k] / nstep, tot[k] / 1000.0 / nstep, tot[k] / 1000.0 / c[k], mn[k] / 1000.0,
100.0 * tot[k] / all, vg[k], lds[k], sc[k], bl[k], nm[k] | "sort -k2 -rn | head -" top
close("sort -k2 -rn | head -" top)
mb = 0
printf "\n"
for (a in seen) {
printf "rank %d busy %6.2f ms/%s %5.1f%% of the traced %s\n",
a, busy[a] / 1e6 / nstep, st, 100.0 * busy[a] / (t1 - t0), st
if (busy[a] > mb) mb = busy[a] }
mb /= 1e6 * nstep
ov = (nd / na / nstep) * overus / 1000.0
# In whole-trace mode the idle is mostly the harness between iterations, not a launch gap,
# so subtracting the instrument from it would be a made-up number. Say nothing instead.
if (mode != "step") {
printf "\nbusiest rank %.2f ms busy of %.2f ms traced. The rest is whatever the harness\n", mb, wall
printf "did between launches, NOT a launch gap -- run the engine if you want that number.\n"
} else {
printf "\nbusiest rank %.2f ms/step busy, %.2f idle traced; ~%.2f of that idle is the\n",
mb, wall - mb, ov
printf "instrument, so the real step is ~%.2f ms with ~%.2f ms of launch gap (%.1f%% busy).\n",
mb + (wall - mb - ov), wall - ov - mb, 100.0 * mb / (wall - ov)
}
}
' "$D/srec"
+46
View File
@@ -0,0 +1,46 @@
#!/bin/sh
# Every kernel in libr4d that indexes a VGPR array with an index the compiler could not prove
# uniform -- and what that costs.
#
# BUILD=/path/to/build ./waterfall.sh
#
# WHY THIS IS ITS OWN INSTRUMENT. A divergent VGPR index is not an addressing mode on gfx12. The
# compiler emits `v_movrels_b32` inside an exec-masked loop that re-runs once per distinct index in
# the wave -- a waterfall -- and nothing about the source says so. The shape that produces one is
#
# for (e = lane; e < n_expert; e += kWave) v[n_own++] = ...;
# ... later ... for (i = 0; i < n_own; ++i) ... v[i] ...
#
# where `n_own` is derived from `lane`, so every `v[i]` after it indexes divergently and becomes a
# waterfall costing tens of thousands of cycles over a wave. The fix is to unroll to the
# compile-time bound so the indices are constants. res.sh cannot see any of this -- such a kernel
# has no scratch, a modest VGPR count and an unremarkable instruction count. Only the disassembly
# says it.
#
# The count is STATIC, so read it as "look here", not as a cost. A `v_movrels` with a genuinely
# uniform index is cheap and appears here too; what makes it a waterfall is the `s_cbranch_execnz`
# back-edge around it, which the second column reports. And a waterfall in a cold kernel is worth
# nothing: most of what this finds is far below the noise of a step. Check the kernel against a
# trace before touching it.
: "${ROCM:=/opt/rocm}"
: "${BUILD:=build}"
: "${ISA_OUT:=/tmp/r4disa}"
here=$(cd "$(dirname "$0")" && pwd)
mkdir -p "$ISA_OUT"
printf "%-22s %6s %6s %s\n" "translation unit" "movrel" "loops" "kernel"
for o in $(find "$BUILD" -name '*.hip.o' | sort); do
tu=$(basename "$o" .hip.o)
"$here/co.sh" "$o" >/dev/null 2>&1 || continue
"$ROCM/llvm/bin/llvm-objdump" -d --symbolize-operands --no-show-raw-insn \
"$ISA_OUT/$tu.co" 2>/dev/null > "$ISA_OUT/$tu.scan.s" || continue
awk -v tu="$tu" '
function flush( ) {
if (n > 0) printf "%-22s %6d %6d %s\n", tu, n, loops, k
n = 0; loops = 0
}
/^[0-9a-f]+ <.*>:$/ { if ($2 !~ /^<L[0-9]+>:$/) { flush(); k = $2 } }
/movrel/ { n++; seen = 1 }
/s_cbranch_exec(nz|z)/ { if (seen) { loops++; seen = 0 } }
END { flush() }
' "$ISA_OUT/$tu.scan.s"
done