radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+75 -81
View File
@@ -1,10 +1,9 @@
# libr4d/isa -- reading the machine code the kernels actually became
# libr4d/isa: reading the machine code the kernels 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.
Nine scripts and four microbenchmarks. A wall-clock timer cannot tell "this kernel is slow" from
"this kernel is at the memory wall"; the disassembly plus one calibration number can, without a GPU
run. The trace tools are the exception: they need the GPU, and they are the only instruments here
that report the geometry a kernel was launched with rather than every geometry it could have had.
BUILD=/path/to/build ./res.sh | head -40 # every kernel: vgpr/lds/scratch
BUILD=... ./dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E
@@ -12,123 +11,118 @@ with rather than the geometries it could have been.
./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.
`res.sh` prints mangled names; the substring `dis.sh` takes picks one template instantiation, and
the parameter order is in the kernel's declaration (`gemm_fp8a8_kernel` is
`<Full, AW, NT, MT, MW, FK, GATED, I8>`, so `ILb1ELb0ELj8ELj1ELj8ELj64ELb0E` is the prefill tile).
`loop.sh` anchors on `v_wmma` by default and takes the smallest backward branch containing every
anchor, because a largest-loop search finds the epilogue, a long unrolled store chain.
## The tools
## 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 |
| `co.sh` | extracts the gfx1201 code object from one built `.hip.o`; the other scripts read that |
| `dis.sh` | disassembles one template instantiation from 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 |
| `gaps.sh` | 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 |
| `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.
Each script's header states its traps and how to read its output. The microbenchmarks are built by
hand: `clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 <name>.hip -o <name>` for `isarate`,
`graphrate` and `blockcopy`, and `build_launchreg.sh` for the two-object launchreg pair.
## What an instruction slot is worth on gfx1201
## Instruction slot cost 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.
`isarate.hip` runs each instruction back to back in eight independent chains, so nothing stalls
but issue. It reports a ratio, which is clock-independent, so 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
One `v_wmma_f32_16x16x16_fp8_fp8` costs about 12.9 plain VALU issue slots, and this holds with
36 KiB of LDS limiting occupancy to what a real prefill tile gets (there it measures nearer 11.6,
for a peak of about 434 TFLOP/s). A kernel's ceiling is therefore
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`.
with `wmma_slots = 12.9 * (wmma count)`, both counts per loop iteration from `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.
This is a ceiling, not a prediction. A kernel cannot beat it, and a kernel far below it is held
back by something else. Issue is often 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.
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`, the 2:4 sparse one, so the GEMMs here already use the
widest dense op there is.
## The profiler: what works and what does not
## The profiler
`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
`rocprofv3 --pmc` does not work on this platform. With any counter set and 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
`--kernel-trace` works without masking any device. 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.
comes from counter enumeration and appears only under `--pmc`. It names an integrated display GPU,
which has no counter support; masking it does not make `--pmc` work. `trace.sh` sets
`ROCR_VISIBLE_DEVICES=0,1` when it is unset, only to pin the agent set and keep that line out of
the log. It runs `$ROCM/bin/rocprofv3`, with `ROCM` defaulting to `/opt/rocm`.
`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.
**A killed `rocprofv3` can outlive its own `timeout`.** The hang is in finalisation, after the
alarm has fired, so the child ignores the timeout and waits in queue sync indefinitely. It holds no
CUs, so it does not disturb a timing, but it holds VRAM, so the next tool reports allocation
failures that look like miscompiled kernels. 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
* Tracing costs about 2 us per dispatch per rank. The ranks are separate host threads and slow down
in parallel, so per-rank dispatch counts are what matter, not the total.
* Kernel durations are hardware timestamps and do not change 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 use 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
* Busy is not utilisation. A dispatch counts as busy if it is resident at all, so a 5 us kernel on
1 of 64 CUs reads the same as a GEMM saturating the card. "96% busy" says the step is almost never
waiting for a launch, 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 as soon as
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.
the model should issue before trusting any table built from it.
## What the instruments say in general
## General results
Two results recur often enough to be worth stating up front, because they decide which levers are
worth pulling at all.
Two results recur and decide which levers are worth pulling.
**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,
**Every dispatch has a fixed cost of a few microseconds.** Across the shapes a decode step asks of
the narrow fp8 GEMM, the time follows 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.
fixed cost shows on every small op (rmsnorm, quant_act, add, gated_quant) whatever it moves. A
"slow" small shape is usually a fixed cost that does not amortise, not a kernel with bandwidth left,
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.
**Most 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 about four times more issue capacity
than the card has bandwidth, and runs at the achievable stream rate. Assembly-level work on such a
kernel does not pay; confirm with `loop.sh` before starting.
**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.
**Read a kernel's own header before proposing changes to it.** Each hot kernel's source records
its ablations, sweeps and rejected variants with the reason for each, and most assembly-level ideas
are already answered there.
+5 -12
View File
@@ -1,13 +1,7 @@
// 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).
// Cost of a scattered KV eviction. The prefix cache is block-granular and its blocks are scattered
// through the paged pool, so a bulk device-to-host bandwidth figure does not price it. Compares one
// contiguous copy of N*B bytes, N copies of B bytes from scattered offsets with a sync after each,
// and the same N copies issued back-to-back on one stream (the batched form an eviction would use).
//
// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 blockcopy.hip -o blockcopy
#include <hip/hip_runtime.h>
@@ -35,8 +29,7 @@ int main(int argc, char** argv) {
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. */
/* Shuffled order: a pool hands out blocks in free 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;
+38 -53
View File
@@ -1,30 +1,25 @@
// WHAT A DISPATCH COSTS THE HOST TO SUBMIT, and what capturing a fixed sequence saves.
// Host cost of submitting a dispatch, 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.
// The device-side gap between dependent kernels is well under a microsecond on this part. In the
// MTP draft loop the host is on the critical path instead: each pass embeds the token the previous
// pass sampled, so nothing overlaps the submit and the device idles through it. The trunk runs
// over a thousand dispatches ahead of the device and never pays this. So this times the submit
// loop itself, separate from the sync.
//
// 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 drift between runs exceeds
// the differences being measured.
//
// 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.
// individual 45 separate hipLaunchKernelGGL, as an uncaptured pass issues them.
// graph one captured graph replayed. The floor; unreachable, since 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.
// operand pointer every step, and three (qsa_work, qsa_score, qsa_select) also
// move a shape, because the QSA extents grow with context.
// graph+Kg+s the same, reading the params back from the node first, because the engine holds
// no launch geometry (the shim marshals its own arguments). If this costs what
// Kset costs, no ABI change is needed.
// 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.
// knowledge of which arg moved, so it is the smallest engine change, if appending
// nodes is cheap enough.
//
// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 graphrate.hip -o graphrate
// ./graphrate 45 300 10
@@ -38,11 +33,9 @@
__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. */
/* `tiny` with a real argument list, to separate HIP's argument marshalling from the shim's own
* prologue (band checks, grid derivation, template switch) as the cause of an engine issue costing
* several times `tiny`. The signature matches r4d_qsa_score_bf16: six pointers, 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) {
@@ -50,12 +43,10 @@ __global__ void fat(const float* q, const float* bk, const int* bt, const int* c
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. */
/* Slow enough to back the queue up. The other arms sync each iteration, so the command ring is
* empty and a submit costs only the runtime's write. A serving engine runs far ahead of a busy
* device, and a submit into a full ring waits for the device to retire a slot; if that dominates,
* host-side shim tidying cannot help. */
__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);
@@ -67,7 +58,7 @@ 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. */
/* Median, not mean: a single descheduled iteration skews a mean. */
static double med(std::vector<double>& v) {
if (v.empty()) return 0.0;
std::sort(v.begin(), v.end());
@@ -113,9 +104,8 @@ int main(int argc, char** argv) {
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. */
/* Warm the clocks, the runtime's lazy module load and every path below. The cards
* idle-suspend, and a cold start times the clock governor ramping (up to ~2x). */
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)
@@ -134,10 +124,9 @@ int main(int argc, char** argv) {
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. */
/* Four graphs over the same 45 nodes: three all-reduces and a gather cut the real pass into
* segments. A graph launch has a roughly fixed cost whatever it contains, paid per segment,
* and that may eat the saving. */
hipGraphExec_t gef[4] = {nullptr, nullptr, nullptr, nullptr};
{
const int seg[4] = {3, 17, 13, 12};
@@ -161,10 +150,8 @@ int main(int argc, char** argv) {
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. */
/* ---- fifteen arguments plus the hipGetLastError check libr4d makes after every launch;
* one op's path can make several. Prices that check against the plain 15-argument arm. */
t0 = clk::now();
for (int i = 0; i < N; ++i) {
hipLaunchKernelGGL(fat, dim3(1), dim3(64), 0, s, d, d, (const int*)d,
@@ -175,10 +162,9 @@ int main(int argc, char** argv) {
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. */
/* ---- fifteen arguments through hipLaunchKernel + kernelParams, as R4D_EMIT's launch path
* does. Every ordinary dispatch pays this while a graph only pays back on replay, so if
* it costs more than `fat` it loses more on the normal path than it saves on capture. */
t0 = clk::now();
for (int i = 0; i < N; ++i) {
void* pv[15];
@@ -202,7 +188,7 @@ int main(int argc, char** argv) {
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 */
/* ---- 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);
@@ -258,15 +244,14 @@ int main(int argc, char** argv) {
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. */
/* ---- Submit under backpressure: the device cannot keep up, so the ring stays full. */
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. */
/* No sync: the queue stays deep across iterations, as in a decode step. */
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();
+8 -12
View File
@@ -1,14 +1,11 @@
// What one instruction slot is worth on gfx1201, so that an instruction COUNT taken out of a
// disassembly can be turned into a time.
// Issue cost of one instruction slot on gfx1201, to turn an instruction count from a disassembly
// into a time. A staged GEMM K tile is a few dozen v_wmma among several hundred other
// instructions, so the wmma-to-VALU cost ratio decides whether trimming the rest pays; no public
// table gives it for this part. Each instruction runs in independent back-to-back chains (issue
// bound) and the rate is reported. The ratio is clock-independent, so no clock is read.
//
// 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.
// LDS is a parameter because occupancy matters: a tile kernel runs at 2 waves a SIMD (36864 B of
// LDS), and 8 waves would answer a different question.
#include <hip/hip_runtime.h>
#include <cstdio>
#include <cstdlib>
@@ -46,8 +43,7 @@ __global__ __launch_bounds__(256) void valu_rate(float* out, int iters) {
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.
// Same shape as the wmma loop (eight independent chains) so only the instruction differs.
for (int i = 0; i < iters; ++i) {
x0 *= k; x1 *= k; x2 *= k; x3 *= k; x4 *= k; x5 *= k; x6 *= k; x7 *= k;
}
+15 -20
View File
@@ -1,17 +1,14 @@
// DOES A LAUNCH COST MORE WHEN THE MODULE REGISTERS MORE KERNELS, and does crossing into a shared
// object cost anything at all?
// Does a launch cost more when the module registers more kernels, and does crossing into a shared
// object cost anything?
//
// 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.
// An engine launch costs roughly twice what the same shape costs in a self-contained binary, and
// the excess is roughly constant across kernel shapes: a fixed per-issue tax. The per-launch error
// check, a full command ring and the argument count 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.
// This isolates the module. libr4d is a .so holding every kernel instantiation, entered through a
// function pointer; a self-contained harness compiles a handful of kernels into the binary. HIP
// resolves a launch by looking the host stub up in the table __hipRegisterFunction fills, so a
// bigger table is a plausible tax, and then the lever is fewer instantiations.
//
// see build_launchreg.sh
#include <hip/hip_runtime.h>
@@ -65,13 +62,13 @@ int main(int argc, char** argv) {
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; }
if (!L->fn || !L->dfn || !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. */
/* 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);
@@ -107,12 +104,10 @@ int main(int argc, char** argv) {
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. */
/* ---- A second submitting thread. --tp 2 runs two rank threads, each issuing onto its own
* stream. A process-wide lock on HIP's submit path would add a fixed tax to every launch,
* the same shape as the excess. The second thread runs the same 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};
+8 -13
View File
@@ -1,16 +1,13 @@
// 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.
// Library half of the registered-kernel test, built at -DNK=2 and -DNK=512 and dlopen'd, which
// matches libr4d's shape: one shared object holding every kernel instantiation, entered through a
// function pointer. Both builds launch the same kernel k<0> with the same arguments; only the
// number of other instantiations in the module differs.
#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. */
/* Keeps the instantiations alive; without a use the compiler drops every unlaunched k<I>. */
static const void* g_tab[NK];
template <int I>
@@ -22,11 +19,9 @@ 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. */
/* One thunk per instantiation. A decode step issues ~45 different kernels, each with its
* own shim, argument buffer and host stub, so code, stub and args are cold on each launch; a
* loop over one kernel keeps them in L1. lr_launch_distinct measures that difference. */
typedef void (*Thunk)(float*, hipStream_t);
template <int I>
static void thunk(float* p, hipStream_t st) {