radiance 1.14.0

New models and formats:
- libr3d: a kernel library for RDNA3 (gfx11) cards
- nomic-embed-text-v2-moe (the nomicbert plugin)
- Gemma 4 E2B with its per-layer MLP width, and Google's unmodified E2B/E4B directories in bf16
- DeepSeek-V4.1-Flash converted straight from its release: the Engram tables, the fused imatrix and
  rad-convert --chat-template for a release that ships no template
- GGUF Q8_0, Q4_K and Q6_K tensors import as their planes; rad-convert writes them without a recipe
- Qwen3.8-Flash-Next-FP8 converts and serves through qwen4exp_fp8

Speed:
- hc_read's decode kernels as one grid (34.7 -> 25.2 us at 4 rows) and its tiled up-mix pipelined
- gemm_fp8a8: the narrow form's scales staged through LDS (Flash-Next int8 at 32 rows 83.6 -> 68.3
  us), the gated three-tile form at 8 waves (gate_up at 48 rows 272.9 -> 180.6 us)
- Qwen3.8-27B: the delta net's out-projection read beside its decode recurrent update (x1 19.40 ->
  19.10 ms a step), and the verify's split-KV attention sized by context depth (x3 at 180K 42.4 ->
  40.3 ms a step)
- Hy-Memory (HYV3) decode: fused QK norm, RoPE and KV store, residual adds folded into the norms,
  coalesced one-token expert GEMMs
- spechub: the coupled verify walks the live candidates only (151 -> 31 us a launch)

Speculation:
- DFlash2: lossless coupled acceptance at T > 0 (--draft-coupling on)
- A block drafter's proposals verified as a tree, on by default for the Gemma 4 31B's DFlash2, with
  a block-16 tree that runs its short block under load

Features:
- Decode-hot residency: --draft-expert-placement host, --expert-profile, --expert-pin-top, and
  --expert-stats FILE for the routed experts each layer selects
- --ngram-placement ram=DIR: one n-gram table shared by engines on separate cards
- Prefix cache: --prefix-resume exact (default) resumes a hit on the cold run's own chunk grid, so it
  answers bit-identically; snapshots at a head other prompts share, from 528-token prompts, and for
  tip-only one drafter window below the tip; hits on models whose KV groups have different block
  sizes; the snapshot store keeps a floor of 8 ahead of --host-headroom-mib
- Typed tool-call argument tags; rad-chatparse --request renders and reads back one request as the
  server does
- MiniMax-H3: keyframes ride a latent upscale
- Gemma 3's fused all-reduce junction on the lossy wire

Fixes:
- A speculative step shorter than its band (an MTP step of 4 rows at gqa 8) no longer stops the
  engine with a scratch refusal at issue (#293)
- --p2p off: prefill back to 1.12.0's rate; 1.13.0's push check read a host-memory slot over the link
  twice (#323)
- A chat template that cannot render a conversation is refused at load, not mid-request
- imatrix entries found under llama.cpp's spelling; the W4A8 prefill's tail scale read; the GDN conv
  kernels on an f32 weight; dense integer rows at the group they compute (a Q8_0 weight at group 32)
- --expert-profile refuses a profile recorded on another model
- hc_read's one-grid wait traps past its deadline instead of reading a stale value

Changes: Plugin ABI 31, unchanged. RADIANCE_DRAFT_TREE, DFLASH2_TREE_NODES, DFLASH2_TREE_TEMP and
DFLASH_Q_TEMP are gone (trees run where the probe says they pay; temperatures 1.25 / 0.6).
This commit is contained in:
Deadcode committed 2026-10-29 12:04:24 +01:00
1 parent 481fcd5df0
commit 4a61d7296b
160 files changed
+8790 -6819

No files matched your search

+250 -322
View File
@@ -1,52 +1,44 @@
/* r3d_rows.cpp -- what libr3d can compute, and for which geometry.
/* r3d_rows.cpp -- the libr3d row table: what each kernel computes and for which geometry.
*
* One row per (kernel, band). A row is a `RadKernelInfo`: names, prose, the geometry it serves as
* constraints, the tuning axes, and the entry points that launch it. The engine reads this table at
* load, matches a requested op and geometry against it, and ranks the candidates by `priority`; it
* never calls a function in this file to do that, and it never looks at a kernel's name. Nothing in
* the engine, the graph, the containers or a test names libr3d's kernels: a card runs this library
* because the rows say they cover its ops, and it stops running them when they do not.
* constraints, the tuning axes and the entry points that launch it. The engine reads this table at
* load, matches a requested op and geometry against it and ranks the candidates by `priority`. It
* never calls into this file to select, and nothing outside libr3d names libr3d's kernels.
*
* ============================================================ the schema table
*
* The first plugin in hierarchy order to declare an op fixes its schema, and a plugin whose schema
* disagrees is refused at load, both plugins named (rad_abi.h, spec §2.3): arguments are positional,
* so two schemas for one op would make one call mean two things depending on which row won. libref
* declares the vocabulary in `docs/OPS.md`, so every schema below is libref's -- the same keys, the
* same types, the same requiredness, the same operand roles and optionality, in the same order. The
* prose is ours, because it states what *this* row computes; the loader's comparison
* covers the positional slots and not the documents.
* disagrees is refused at load (rad_abi.h, spec §2.3): arguments are positional, so two schemas
* would give one call two meanings. libref declares the vocabulary (`docs/OPS.md`), so every schema
* below is libref's: the same keys, types, requiredness, operand roles and optionality, in the same
* order. The prose describes this library's rows; the loader compares only the positional slots.
*
* An op libr3d invents needs a schema here too, and libref's side of it: an op whose schema is
* declared only by a kernel plugin cannot be checked against a reference, and an op that exists in
* two kernels with two schemas breaks the rule above. That is why libr3d declares no new op: every
* row below implements an op libref declares.
* libr3d declares no new op: an op declared only by a kernel plugin has no reference to be checked
* against.
*
* ============================================================ the constraint table
*
* A constraint is a necessary condition on the geometry (spec §2.1). "bf16 only" is not one: the
* dtype of an operand is a property of the call, and the shim reads the tensor. What goes here is
* what the *kernel* cannot do -- the divisibility its lane map assumes, the band its grid is sized
* for, the scheme its decoders implement -- and what the selector needs to choose between rows.
* A constraint the shim also checks costs nothing; a constraint the kernel does not actually
* enforce is a promise the tests will break.
* A constraint is a necessary condition on the geometry (spec §2.1). An operand's dtype is a
* property of the call, and the shim checks it on the tensor. Constraints state what the kernel
* cannot do (the divisibility its lane map assumes, the band its grid is sized for, the scheme its
* decoders implement) and what the selector needs to choose between rows. A constraint the kernel
* does not actually honour is a promise the tests will break.
*
* ============================================================ rows are positional
*
* `RadKernelInfo` is initialised positionally, as `rad_abi.h` requires: a field added anywhere but
* the end shifts every later initialiser, and `nullptr` converts to any function pointer, so part
* of the shift compiles. The order below is the struct's; the trailing slots a row does not use are
* left off, which aggregate initialisation zeroes. A row's entry points are, in order: init, fini,
* launch, scratch, layout, relayout, opd_shape, unrelayout, replaces.
* the end shifts every later initialiser, and because `nullptr` converts to any function pointer,
* part of the shift still compiles. Unused trailing slots are left off and zero-initialised. A row's
* entry points are, in order: init, fini, launch, scratch, layout, relayout, opd_shape, unrelayout,
* replaces.
*
* The only `layout` and `relayout` hooks in this table present the container's own planes as the
* joined operands they store -- the w2a8 row's `b_scale`, the fp8 weight's codes and scale, the
* logits head -- and repack nothing, so a container converted on this card keeps row-major codes
* against row-major scales. A dot2 GEMM reads a weight in the order it is stored; libr4d's fragment
* permutations are a WMMA fact, and RDNA3's wave-matrix instructions use a 16x16 fragment layout
* this table's dot2 kernels do not (r3d_common.h has the measurements).
* The `layout` and `relayout` hooks here only present the container's own planes as the joined
* operands they store (the w2a8 row's `b_scale`, the fp8 weight's codes and scale, the logits head)
* and repack nothing, so a container converted on this card keeps row-major codes and scales. A
* dot2 GEMM reads a weight in stored order; libr4d's fragment permutations exist for WMMA, which
* these kernels do not use (see r3d_common.h).
*
* Pure host C++: no r3d.h, no HIP, so this table compiles and can be read and tested without ROCm.
* Pure host C++ (no r3d.h, no HIP), so the table compiles and can be tested without ROCm.
*/
#include "r3d_plugin.h"
@@ -83,9 +75,8 @@
/* ================================================================== schemas
*
* Operand names are diagnostics only; roles and optionality are positional and must match. Where
* libref's array carries a name libr3d's reads differently (`b` for a gate, say) the names differ
* and the schema does not.
* Operand names are diagnostics only; roles and optionality are positional and must match.
* Operand names may differ from libref's (`b` for a gate, say) without changing the schema.
*/
/* --- norms and elementwise --- */
@@ -112,11 +103,10 @@ static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_
static const RadParamSpec pCast[] = { P_INT("M"), P_INT("n"), P_STR("from"), P_STR("to") };
static const RadParamSpec pScale[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
/* `s` is a WEIGHT, which is what the reference declares and what the core acts on: a weight operand
* has its issue resolve a handle and wait on the mover, and a scale plane comes from the container
* or from a quantiser, not from a buffer the planner allocated for this step. Declaring it IN is
* not a cosmetic difference -- the loader compares roles positionally and refuses the library that
* disagrees, every row with it. */
/* `s` is a weight operand, as the reference declares it: the issue resolves a handle and waits on
* the mover, because a scale plane comes from the container or a quantiser, not from a buffer the
* planner allocated for the step. The loader compares roles positionally, so declaring it IN would
* get the whole library refused. */
static const RadOperandSpec oScale[] = { { "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 } };
@@ -189,38 +179,28 @@ static const RadOperandSpec oGemmQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RA
/* ================================================================== the vocab and the sampler
*
* The vocab and sampler bands, transcribed from libref. A schema is inert on its own -- the loader
* matches a row to a schema, and a row naming an entry point no unit defines is an undefined symbol
* that kills `dlopen` and takes every row in the library with it -- so `r3d_selftest`'s schema phase
* compares every declared schema against libref's, slot for slot, the moment the library loads, and
* a misspelled key is refused at load, not when a row first meets it.
* The vocab and sampler schemas, transcribed from libref. `r3d_selftest`'s schema phase compares
* every declared schema against libref's, slot for slot, when the library loads, so a misspelled
* key is caught at load rather than when a row first uses it.
*
* The sampler is a law, not a shape: the candidate set, the tie-break in the top-k, the order of the
* renormalisations and the seeded draw are all observable, and libref is the oracle for all of them.
* The sampler's behaviour is fully specified: the candidate set, the top-k tie-break, the order of
* the renormalisations and the seeded draw are all observable, and libref is the oracle for each.
*/
/* The gated MLP's activation, as the llama-family graphs emit it: one fused [M, 2n] projection, the
* gate's half activated and multiplied by the other. `act_mul` is the same arithmetic over two
* operands; these are different ops, and an architecture emits one or the other. */
/* The gated MLP's activation as llama-family graphs emit it: one fused [M, 2n] projection, the
* gate half activated and multiplied by the other half. `act_mul` is the same arithmetic over two
* operands; an architecture emits one op or the other. */
static const RadOperandSpec oGateUp[] = { { "gate_up", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
/* Paged attention. `block_size` is RAD_DERIVED here (the container's cache geometry, admitted by a
* constraint that only refuses its absence), and `n_head`, `max_seqs`, `max_ctx` and `prefill_fp8`
* are on the list because a plugin's scratch hook sizes a split-KV buffer from them and both
* libraries must agree on the parameter list -- libref ignores them. */
/* DFlash2's candidate walk: a draft block of `steps` proposals, `top_k` candidates at each step,
* rescored against the target's rank-d codebooks. `anchor_stride` is optional and defaults to 1;
* `hp` is the optional per-edge scaling of the predecessor's codebook row, and absent it is a plane
* of ones, which is what the reference computes. */
/* The gated MLP band: one weight of N = 2n rows (gate first, then up), the GEMM, the gate and the
* output quantiser in one launch, so the [M, N] intermediate the unfused chain writes and re-reads
* never exists. `act` is a required string: an implementation compiles one gate, and an optional
* would let a row resolve for the gate it does not have. */
/* The gated MLP band: one weight of N = 2n rows (gate first, then up), with the GEMM, the gate and
* the output quantiser in one launch so the [M, N] intermediate is never stored. `act` is a required
* string because an implementation compiles one gate; an optional key would let a row resolve for a
* gate it does not have. */
static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"),
P_INT("group"), P_STR("dtype"), P_STR("act") };
/* The vocabulary projection's schema, slot for slot with the reference's: the geometry is the head's
* (`n_vocab` x `n_embd`), the dtype is the activation's, and `logits` is f32 -- the op exists
* separately from gemm_nt for that reason, and the row that serves it narrows nothing. */
/* The vocabulary projection's schema, slot for slot with the reference's: the geometry is the
* head's (`n_vocab` x `n_embd`), the dtype is the activation's, and `logits` is f32, which is why
* the op is separate from gemm_nt. */
static const RadParamSpec pLogits[] = { P_INT("M"), P_INT("n_vocab"), P_INT("n_embd"),
P_STR("dtype") };
static const RadOperandSpec oLogits[] = {
@@ -233,6 +213,10 @@ static const RadOperandSpec oGemmQGated[] = {
{ "out_bf16", RAD_OPD_OUT, 1 },
};
/* DFlash2's candidate walk: a draft block of `steps` proposals with `top_k` candidates each,
* rescored against the target's rank-d codebooks. `anchor_stride` is optional and defaults to 1.
* `hp` is an optional per-edge scaling of the predecessor's codebook row; absent, it is a plane of
* ones, as the reference computes. */
static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"),
P_INT("rank"), P_INT("n_vocab"),
P_INTO("anchor_stride"), P_STR("dtype") };
@@ -243,6 +227,10 @@ static const RadOperandSpec oDflashSelect[] = {
{ "tokens", RAD_OPD_OUT, 0 },
};
/* Paged attention. `block_size` is RAD_DERIVED (the container's cache geometry, admitted by a
* constraint that only refuses its absence). `n_head`, `max_seqs`, `max_ctx` and `prefill_fp8` are
* listed because a plugin's scratch hook sizes the split-KV buffer from them and both libraries must
* agree on the parameter list; libref ignores them. */
static const RadParamSpec pAttnPaged[] = {
P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"),
P_INT("window"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"),
@@ -305,13 +293,12 @@ static const RadOperandSpec oPick[] = { { "cand_idx", RAD_OPD_IN, 0 },
{ "token", RAD_OPD_OUT, 0 } };
/* The fused MLP activation and the fused norm-quantiser, both from the model unit. The first takes
* one [M, 2n] operand and produces [M, n]; the second is libref's, slot for slot, with `residual`
* INOUT because the sum it stores is the one the variance reads. */
/* The fused norm-quantiser from the model unit, libref's slot for slot. `residual` is INOUT because
* the sum it stores is the one the variance reads. */
static const RadParamSpec pRmsQuantFp8[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
P_STR("dtype"), P_F64O("wadd") };
/* `residual` is optional because the op has a no-residual form, which is what the launcher's `res`
* pointer being 0 means; libref spells it INOUT_O and the loader compares the flag. */
/* `residual` is optional because the op has a no-residual form (the launcher's `res` pointer is 0);
* libref declares it INOUT optional and the loader compares the flag. */
static const RadOperandSpec oRmsQuantFp8[] = {
{ "x", RAD_OPD_IN, 0 }, { "residual", RAD_OPD_INOUT, 1 }, { "w", RAD_OPD_WEIGHT, 0 },
{ "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 }
@@ -361,8 +348,8 @@ static const RadOpSchema kSchemas[] = {
"Symmetric per-(row, group) E4M3: scale = amax * (1/448) with the reciprocal "
"multiplied, not divided; an all-zero group gets scale 1 and the codes 0."),
SCHEMA("quant_act_i8", pQuant, oQuant,
"Symmetric int8 with ONE SCALE PER ROW, max(amax, 1e-8) / 127, codes round-to-nearest-"
"ties-to-even and saturating, stored in the STEP ORDER the int8 WMMA reads. `asum` takes "
"Symmetric int8 with one scale per row, max(amax, 1e-8) / 127, codes round-to-nearest-"
"ties-to-even and saturating, stored in the step order the int8 WMMA reads. `asum` takes "
"the group-major row sums the zero-pointed GEMMs reduce."),
SCHEMA("quant_act_i8g", pQuant, oQuantFp8,
"The same int8 code at `group` granularity: one f32 scale per (row, group), amax / 127, "
@@ -383,17 +370,17 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("rmsnorm_quant_fp8", pRmsQuantFp8, oRmsQuantFp8,
"RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The "
"residual add is STORED BEFORE THE VARIANCE READS IT, so the sum the norm is taken over "
"is the bf16 one and not the f32 one -- that is what makes this the `add` + `rmsnorm` "
"pair and not `rmsnorm_add`, which normalises the unrounded sum. `wadd` is added to every "
"residual sum is stored as bf16 before the variance reads it, so the norm is taken over "
"the rounded sum, as the `add` + `rmsnorm` pair computes it (`rmsnorm_add` normalises "
"the unrounded sum). `wadd` is added to every "
"gain in f32. `out_bf16` holds exactly the value the codes were taken over."),
/* ---- the vocabulary and the sampler: schemas first, rows with their kernels ---- */
SCHEMA("silu_mul", pMnDtype, oGateUp,
"y[i] = silu(gate_up[i]) * gate_up[n + i] over one fused [M, 2n] plane, the gate the "
"first half -- rad-convert's fusion order -- and the product of an activation that was "
"never narrowed. act_mul is the same arithmetic over two operands, narrowing first, "
"because the pair it replaces stored the activation."),
"never narrowed. act_mul is the same arithmetic over two operands, narrowing the "
"activation first, as a stored activation is."),
SCHEMA("attn_paged", pAttnPaged, oAttnPaged,
"Scaled dot-product attention over a paged KV cache: q [tokens, n_head, head_dim], the "
"cache [blocks, kv_heads, block_size, 2*head_dim], `block_table` a row's block list, "
@@ -473,37 +460,32 @@ extern "C" const RadOpSchema* rad_kernel_schema_at(int i) {
/* ================================================================== tuning
*
* The axes a kernel is instantiated along, measured on this card (`rad-tune`, spec §15). Every row
* without a matrix instruction to size a tile against has few axes: what is left to measure is how
* the work is split across the card, and how the weight stream is read.
* The axes a kernel is instantiated along, measured per card by `rad-tune` (spec §15). Without a
* matrix instruction to size a tile against, the rows have few axes: how the work is split across
* the card and how the weight stream is read.
*/
/* Split-K. 0 is not a point in the space, it is the kernel's own law: "the largest split legal at
* this K", because no fixed default is legal at every shape and an illegal default would make an
* untuned install fail rather than run slowly. */
/* Split-K. 0 is not a point in the space but the kernel's rule, "the largest split legal at this
* K" (r3d_args.h: libr3d's tunables). */
static const int64_t kSk[] = { 0, 1, 2, 4, 8, 16 };
/* Waves per block. 8 is 256 threads, which is the largest block that keeps the register budget of
* a wave-per-N-tile kernel inside gfx11's 1024 VGPRs a SIMD at four waves. */
static const int64_t kWv[] = { 1, 2, 4, 8 };
/* Non-temporal weight streaming: a decode GEMM reads a weight once per token, so the L2 is a
* latency cache and not a reuse cache. RDNA3 has no transposed-load instruction, so this axis
* selects the plain 128-bit stream with the cache hints off -- a knob worth measuring, not an
* instruction. */
/* Non-temporal weight streaming: a decode GEMM reads a weight once per token, so the L2 serves
* latency, not reuse. RDNA3 has no transposed-load instruction, so this axis only switches the cache
* hints on the plain 128-bit stream. */
static const int64_t kNt[] = { 0, 1 };
/* No `kb` axis. Only a GEMM that stages a K slab through LDS has a slab width to measure, and
* the skinny rows stream the weight through registers; the axis joins the table with the tiled
* row. */
/* No `kb` axis: only a GEMM that stages a K slab through LDS has a slab width to tune, and the
* skinny rows stream the weight through registers. */
static const RadTunable tGemmM16[] = {
{ "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" },
{ "wv", kWv, NELEM(kWv), 8, "waves per block" },
{ "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" },
};
/* No `wv` here. The quantised kernel's launcher takes a fixed block of eight waves -- its weight
* decode, sixteen codes a lane into eight dot2, is the whole of a wave's issue budget at any block
* size -- so an axis the tuner would sweep is an axis the kernel ignores, and a tunable that changes
* nothing is worse than none: it spends the tuner on a knob and teaches the reader that the table
* lies. The axis joins the row with a launcher that takes it. */
/* No `wv` axis: the quantised kernel's launcher uses a fixed block of eight waves, because its
* weight decode (sixteen codes a lane into eight dot2) fills a wave's issue budget at any block
* size. An axis the kernel ignores would only spend tuner time. */
static const RadTunable tGemmQ[] = {
{ "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" },
{ "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" },
@@ -524,8 +506,8 @@ static int gemm_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_
return sk >= 0 && (sk == 0 || K % (sk * unit) == 0);
}
/* The chosen point, read back. `TUNE` falls to the axis's default when the core appended nothing,
* so a checker with no tuned key runs what an untuned install runs. */
/* The chosen point, read back. `TUNE` falls back to the axis's default when the core appended
* nothing, so a caller with no tuned key runs what an untuned install runs. */
static long long tune_i(const RadArgs* a, const RadTunable* t, int n, const char* key) {
if (a && a->p)
for (int i = 0; i < a->n_p; ++i)
@@ -551,21 +533,15 @@ extern "C" void r3d_cfg_topk(const RadArgs* a, R3dTopkCfg* out) {
out->nch = 0;
}
/* A split's partials are f32 over the output, plus one arrival counter per split. Sized at the
* band's bounds and the axis's widest split, because a scratch hook runs at declare, where the
* range may still be open: the buffer must hold any point the tuner can pick. */
/* Split-KV's partials: one record of 128 accumulator floats plus the running max and sum -- 132
* floats -- per (query row, head, slice). The shim takes the slice count from the bytes the engine
* offers and halves it until they fit, so this is the want, stated at the slice count the walk
* benefits from and capped at what these bands can carry: 15 MB at the decode band (1792 rows over
* 16 heads) and 17 MB at the prefill band. Attaching scratch makes the row non-concurrent, which is
* the ABI's rule (rad_kernel_concurrent is `scratch == nullptr`) and the price of the split. */
/* Split-KV partials: one record of 128 accumulator floats plus the running max and sum (132
* floats) per (query row, head, slice). The shim takes the slice count from the bytes the engine
* offers, halving it until they fit, so this is the request at the slice count the walk benefits
* from, capped at 16 MiB. Attaching scratch makes the row non-concurrent (rad_kernel_concurrent is
* `scratch == nullptr`), which is the cost of the split. */
static int64_t attn_scratch(const RadArgs* a) {
/* The size comes from the SHAPE, and a scratch hook runs at declare, where the engine has bound
* the operands' shapes and has no bytes to hand out yet -- `data` is null at declare for every
* tensor in the plan. A hook that requires bytes answers 0 for the whole run, the engine
* allocates an arena of 0 bytes, and the shim's split pass finds no partials to write. The
* sibling `gemm_scratch` sizes off `RadParam` dims for exactly this reason. */
/* Sized from the shape: a scratch hook runs at declare, when the operands' shapes are bound
* but every tensor's `data` is still null. A hook that required data would answer 0 and the
* split pass would find no buffer. gemm_scratch sizes from RadParam dims for the same reason. */
if (!a || a->n_t < 1 || a->t[0].rank == 0) return 0;
long long n_head = 0, head_dim = 0;
const int64_t nh = rad_args_geti(a, "n_head", &n_head) ? n_head : 0;
@@ -577,6 +553,9 @@ static int64_t attn_scratch(const RadArgs* a) {
return want < cap ? want : cap;
}
/* A split's partials are f32 over the output, plus one arrival counter per split. Sized at the
* band's bounds and the axis's widest split, because a scratch hook runs at declare, where the
* range may still be open: the buffer must hold any point the tuner can pick. */
static int64_t gemm_scratch(const RadParam* p, int n_p) {
const long long M = rad_param_getdim(p, n_p, "M", 0), N = rad_param_getdim(p, n_p, "N", 0);
const long long sk = kSk[NELEM(kSk) - 1];
@@ -586,9 +565,9 @@ static int64_t gemm_scratch(const RadParam* p, int n_p) {
/* ================================================================== constraints
*
* What the kernel cannot do, and what the selector needs. The divisibility in each is the lane map
* in the unit: a wave covering a bf16 row reads four elements a lane (two pairs), so a row of 4m
* elements needs no tail; where the kernel has a tail path the constraint says 2, not 4.
* What the kernel cannot do, and what the selector needs. Divisibility follows the unit's lane map:
* a wave covering a bf16 row reads four elements a lane (two pairs), so a row of 4m elements needs
* no tail; where the kernel has a tail path the constraint says 2, not 4.
*/
/* bf16 elementwise, norms and the GEMMs: rows of an even width, so a lane owns a pair. */
@@ -630,14 +609,12 @@ static const RadConstraint cFillF32[] = { C_IN("dtype", "f32") };
static const RadConstraint cFillI32[] = { C_IN("dtype", "i32") };
static const RadConstraint cFillI64[] = { C_IN("dtype", "i64") };
/* rope: the two modes this kernel implements, and a rotary width that is a whole even head. The
* yarn, llama3 and ladder parameters are absent from these rows' bands, so a geometry carrying them
* is not routed here. */
/* `rotary_dim` is optional on the op, and a constraint on a parameter a band does not carry does
* not hold -- the engine's rule, quoted in r3d_selftest.cpp's band-reachability phase -- so it
* cannot appear here: an architecture that rotates the whole head, which is every llama-family
* graph, emits a band without the parameter and would find no row. Its evenness is the shim's to
* refuse (RAD_E_SHAPE), and `rotary_dim` absent is head_dim, which is even by the constraint above. */
/* rope: the two modes this kernel implements and an even head_dim. The yarn, llama3 and ladder
* parameters are absent from these rows' bands, so a geometry carrying them is not routed here.
* `rotary_dim` cannot be constrained: it is optional, a constraint on a key the band does not carry
* does not hold (see r3d_selftest.cpp's band-reachability phase), and llama-family graphs, which
* rotate the whole head, omit it. The shim refuses an odd rotary_dim (RAD_E_SHAPE); absent, it is
* head_dim, which the constraint keeps even. */
static const RadConstraint cRope[] = { C_IN("mode", "neox gptj"), C_DIV("head_dim", 2) };
/* The cache's dtype is the row: a bf16 cache stores the value, an E4M3 cache encodes it with the
@@ -661,17 +638,17 @@ static const RadConstraint cScatterBf16[] = { C_IN("dtype", "bf16"), C_DIV("n",
* wave's four-elements-a-lane store is whole. */
static const RadConstraint cQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK),
C_DIV("n", 4) };
/* `quant_act_i8` is the per-row int8 whose codes the int8 WMMA reads, so its width is a whole
* 16-byte step, not a lane's four. `quant_act_i8g` is the per-group one whose codes are row-major,
* which is what a dot2 GEMM reads; it is the activation of this library's i8a8 row. */
/* `quant_act_i8` is the per-row int8 whose codes are in the int8 WMMA's step order, so its width
* is a whole 16-byte step. `quant_act_i8g` is per group with row-major codes, as a dot2 GEMM reads
* them; it is the activation of this library's i8a8 row. */
static const RadConstraint cQuantI8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP),
C_DIV("n", 16) };
static const RadConstraint cQuantI8g[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP),
C_DIV("n", 4) };
/* Not `C_IN("act", "silu sigmoid")`: `act` is optional on the op (a graph may carry libref's integer
* `mode` instead, and libref's own default is silu), and a band that states neither would resolve to
* nothing. The shim reads `act`, falls back to `mode`, then to silu, and refuses a gelu -- the
* activation whose kernel this unit does not carry -- with RAD_E_UNSUPPORTED. */
/* Not `C_IN("act", "silu sigmoid")`: `act` is optional on the op (a graph may carry libref's
* integer `mode` instead, and libref defaults to silu), so a band with neither would match no row.
* The shim reads `act`, then `mode`, then defaults to silu, and refuses gelu, which this unit has no
* kernel for, with RAD_E_UNSUPPORTED. */
static const RadConstraint cGateQuant[] = { C_IN("dtype", "bf16"),
C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) };
static const RadConstraint cDequantFp8[] = { C_IN("dtype", "fp8_e4m3"),
@@ -681,50 +658,35 @@ static const RadConstraint cDequantE5[] = { C_IN("dtype", "fp8_e5m2"),
static const RadConstraint cDequantI8[] = { C_IN("dtype", "i8"), C_EQ("group", R3D_W8_GROUP),
C_DIV("n", 4) };
/* The GEMMs. The skinny row's band is the decode and verify height: 16 rows, which is a speculative
* verify's ceiling with room to spare, and below the height where staging the activations through
* LDS starts to pay. K even, because the inner loop consumes pairs; N unconstrained, because a wave
* covering N tiles the tail.
*
* No upper bound on N: the vocabulary and the feed-forward widths are 11008, 14336, 128256 and
* whatever a given checkpoint's `intermediate_size` is, and a bound would refuse them. */
/* The GEMMs. The skinny row's band is the decode and verify height, M <= 16: it covers a
* speculative verify with room to spare and stays below the height where staging the activations
* through LDS pays. K even because the inner loop consumes pairs. N has no bound: a wave covering N
* handles the tail, and feed-forward and vocabulary widths (11008, 14336, 128256, a checkpoint's
* `intermediate_size`) vary. */
static const RadConstraint cGemmM16[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 16),
C_DIV("K", 2), C_GE("N", 1) };
/* The vocabulary projection. **No `dtype` constraint, and the reason is the engine's, not the
* kernel's**: the band this op is declared with carries the geometry (M, n_vocab, n_embd) and not a
* dtype key -- the head's dtype is a property of the weight, which is why libref's own logits row
* answers it with a `check_dtypes` hook and not with a constraint. A constraint on a key the
* geometry does not carry serves nobody: with `dtype in {bf16}` declared, the engine resolves a
* host kernel and no device one and refuses to start, so the dtype is refused where it is read, at
* the shim, naming the widening the kernel does.
* `n_embd` in 32-code chunks is the entry's own rule (K % 32), stated so a band outside it is
* refused at declare rather than at launch. `n_vocab`'s floor is the store's granularity: a row
* writes 16-byte runs, so a plane four ids wide is the narrowest it can read, and a band narrower
* than that -- a shard's padding, a 1-id test vocabulary -- is refused by the constraint and not by
* the launch. Above the floor the grid is vocab-wide at every M, so a 320-wide vocabulary and a
* 130560-wide one are the same kernel. */
/* The vocabulary projection has no `dtype` constraint because its band carries no `dtype` key: the
* head's dtype is a property of the weight (libref checks it with a `check_dtypes` hook). A
* constraint on a key the band lacks does not hold, which would leave only the host kernel and the
* engine would refuse to start, so the shim refuses an unsupported dtype instead.
* `n_embd % 32` is the entry's chunk rule, stated so a band outside it is refused at declare rather
* than at launch. `n_vocab >= 4` is the store's granularity (16-byte runs); a narrower band (a
* shard's padding, a 1-id test vocabulary) is refused here. Above that floor the grid spans the
* vocabulary at every M, so every vocabulary width runs the same kernel. */
static const RadConstraint cLogitsGemm[] = { C_GE("M", 1), C_GE("n_vocab", 4),
C_DIV("n_embd", 32) };
/* The tiled GEMM at prefill heights. M >= 17 is the complement of cGemmM16's M <= 16 by
* construction, so the two rows never compete for a band: the skinny shape (a wave a run of
* columns, the weight streamed past registers) is right up to 16 rows and wrong above it, and the
* 128x128 tile is the reverse. K % 32 is the tile's k-chunk and N >= 8 the bf16 store run, for the
* same reason cLogitsGemm states its floor: what the kernel cannot read is in the constraints. */
/* The quantised GEMM above the decode heights. Here `dtype` IS the operand scheme -- gemm_q_shape
* switches on it -- so C_IN filters, which is the distinction from logits_gemm, where the band's
* dtype names the activation and C_IN filters nothing. M >= 17 is the complement of
* gemm_nt_q_fp8a8_m16's M <= 16 -- read from its constraint, not from its name: a higher floor
* would leave 17..64 unserved, and a 209-row batched decode is the shape a serving card spends
* most of its life in. The tile's k-chunk (32) divides the container's scale
* block (128), which is why `group` is an equality and `K` a divisibility. */
/* The quantised GEMM above decode heights. Here `dtype` is the operand scheme (gemm_q_shape
* switches on it), so C_IN filters rows, unlike logits_gemm, where the band's dtype names the
* activation. M >= 17 complements gemm_nt_q_fp8a8_m16's M <= 16; a higher floor would leave batched
* decode at 17..64 rows unserved. The tile's k-chunk (32) divides the container's scale block
* (128), so `group` is an equality and `K` a divisibility. */
static const RadConstraint cGemmQFP8Tiled[] = { C_IN("dtype", "fp8a8 fp8a8f32"),
C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17),
C_DIV("K", 128) };
/* The OCP-MXFP4 rows: the weight is e2m1 with one e8m0 scale per 32 of K, the activation's
* scale per 128 -- both fixed by the format, so the `group` key carries no kernel-side meaning
* and the rows do not constrain it (the reference derives the planes from it). K dividing 128
* carries the 32-block; the band split is the fp8a8 one, 16 at the ceiling and 17 at the floor,
* and the dtype carries the whole scheme. */
/* The OCP-MXFP4 rows: e2m1 weight codes with one e8m0 scale per 32 of K, the activation scaled per
* 128. Both are fixed by the format, so the `group` key has no kernel-side meaning and is not
* constrained (the reference derives the planes from it). K % 128 covers the 32-block, the bands
* split at M = 16 / 17 as for fp8a8, and the dtype names the whole scheme. */
static const RadConstraint cGemmQMxfp4a8M16[] = { C_IN("dtype", "mxfp4a8"),
C_GE("M", 1),
C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) };
@@ -732,9 +694,8 @@ static const RadConstraint cGemmQMxfp4a8Tiled[] = { C_IN("dtype", "mxfp4a8"),
C_GE("M", 17),
C_DIV("K", 128) };
/* The symmetric int4 / int8 weight grids at decode heights: the block is the weight's scale
* group (128), and the band is the m16 one -- M > 16 is the tiled rows', and the 8-bit grid at
* prefill heights is declared out. */
/* The symmetric int4 / int8 weight grids at decode heights: the block is the weight's scale group
* (128) and the band is M <= 16. No row serves the 8-bit grid at prefill heights. */
static const RadConstraint cGemmQW4A8M16[] = { C_IN("dtype", "w4a8"),
C_GE("M", 1), C_LE("M", 16),
C_DIV("K", 128), C_GE("N", 1) };
@@ -742,26 +703,26 @@ static const RadConstraint cGemmQW8A8M16[] = { C_IN("dtype", "w8a8"),
C_GE("M", 1), C_LE("M", 16),
C_DIV("K", 128), C_GE("N", 1) };
/* The tiled bf16 GEMM at prefill heights. M >= 17 complements cGemmM16's M <= 16, so the two rows
* never compete for a band: the skinny shape (a wave a run of columns, the weight streamed through
* registers) suits up to 16 rows and the 128x128 tile suits more. K % 32 is the tile's k-chunk and
* N >= 8 the bf16 store run. */
static const RadConstraint cGemmNTTiled[] = { C_IN("dtype", "bf16"), C_GE("M", 17), C_DIV("K", 32),
C_GE("N", 8) };
/* The quantised GEMM: the scheme names the row, the weight's block is the container's, and a split
* must land on a block boundary (gemm_tune_valid). */
/* The block: `group` is required and every band names it, so the row states it. `pb1` and `pb2` are
* OPTIONAL, and a constraint on a key the band omits does not hold -- a model whose container
* declares the default block says nothing about pb1, and constraining it would make every one of
* that model's GEMM bands fall through to the reference and its host kernel -- 259 ops on one
* 2B model. The launcher defaults them to `group` (r3d_gemm_fp8a16_nt_m1.hip) and refuses a
* pb2 that is not the code group, which is the container's own invariant: the K block IS the code
* group, so a band naming pb2 unequal to group resolves to this row and is refused at launch. */
* must end on a block boundary (gemm_tune_valid). `group` is required and every band names it, so
* the row constrains it. `pb1` and `pb2` are optional, and a constraint on a key the band omits does
* not hold, so constraining them would send every GEMM band of a container using the default block
* to the reference's host kernel. The launcher defaults them to `group` (r3d_gemm_fp8a16_nt_m1.hip)
* and refuses a pb2 that differs from the code group, the container's own invariant. */
static const RadConstraint cGemmQFp8a16[] = { C_IN("dtype", "fp8a16"),
C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1),
C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) };
static const RadConstraint cGemmQFp8a8[] = { C_IN("dtype", "fp8a8"),
C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1),
C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) };
/* The int8 GEMM's constraints are written ahead of its row: a row naming an entry point that is
* not in the library is an undefined symbol, and the plugin would fail to load, taking every other
* row with it. */
/* The int8 GEMM's constraints. No row uses them: a row must name an entry point the library
* defines, or the plugin fails to load. */
static const RadConstraint cGemmQI8[] = { C_IN("dtype", "i8a8"),
C_EQ("group", R3D_W8_GROUP), C_GE("M", 1),
C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) };
@@ -771,30 +732,25 @@ static const RadConstraint cGemmQI8[] = { C_IN("dtype", "i8a8"),
* Declaration order is the tie-break within one priority, so rows that share an op are declared
* narrowest first.
*/
/* The constraints above are written ahead of the rows that use them, for the same reason the
* schemas are: the table reads as one document. A constraint array with no row is not an error, so
* the file builds; the comment above each says which row it serves. */
/* Constraint arrays are declared ahead of the rows that use them, each with a comment naming the
* row it serves. */
/* ================================================================== the fused-MLP rows
*
* The two rows the llama graphs ask for that the model unit serves. `silu_mul` constrains
* nothing but the dtype and an even `n`: `act` is not in this op's parameter list (it is the fused
* form of one fixed activation), and a constraint on a key the geometry lacks does not hold, so a
* row built on the act_mul constraints would resolve to no band at all. `rmsnorm_quant_fp8` states
* the group the kernel covers with a wave and requires it to divide `n`; the standalone quantiser's
* `n % 4` would admit a band this kernel refuses, and a row that resolves at declare and fails at
* launch is the shape of bug this file exists to prevent.
* Two rows llama graphs ask for that the model unit serves. `silu_mul` constrains only the dtype
* and an even `n`: `act` is not in this op's parameter list (the op fuses one fixed activation), and
* a constraint on a key the band lacks does not hold, so the act_mul constraints would match no band.
* `rmsnorm_quant_fp8` requires the group the kernel covers with a wave to divide `n`; the standalone
* quantiser's `n % 4` would admit bands this kernel refuses at launch.
*/
static const RadConstraint cSiluMul[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) };
static const RadConstraint cRmsQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK),
C_DIV("n", R3D_FP8_BLOCK) };
/* The sampler's pre-filters constrain `n_vocab` and nothing else. The bands an architecture emits
* for these ops carry `n_vocab` and `M` (plus `vocab_off`, and `k` for logprobs) and no `dtype`
* key, so a row that constrained a dtype would constrain a key the geometry lacks and resolve to no
* band at all. The dtype is f32; the shims check it on the tensor, which is where a dtype belongs
* when the geometry does not name it. `k <= 64` is the depth of the logprobs kernel's pool, so the
* row serves exactly the bands its launcher accepts.
/* The sampler's pre-filters constrain only `n_vocab`. Their bands carry `n_vocab` and `M` (plus
* `vocab_off`, and `k` for logprobs) and no `dtype` key, so a dtype constraint would match no band;
* the shims check that the tensors are f32. `k <= 64` is the depth of the logprobs kernel's pool, so
* the row serves exactly the bands its launcher accepts.
*/
static const RadConstraint cSampleF32[] = { C_GE("n_vocab", 1) };
static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) };
@@ -814,25 +770,18 @@ static const RadConstraint cAttnFp8Prefill[] = { C_IN("q_dtype", "bf16"),
C_IN("kv_dtype", "fp8_e4m3"),
C_EQ("head_dim", 128), C_GE("q_len", 17) };
/* `row_topk` is banded on dtype, so it gets two rows; the candidate stages are banded on `n_cand`,
* whose ceiling is the kernel's: five f32 arrays of n_cand in LDS is 20 KiB of the 64 KiB, and a
* wider band is refused by the shim (RAD_E_SHAPE), so the row states the ceiling and resolves for
* exactly what it serves. The vocab stages carry `n_vocab` and no dtype key, and the logits are f32
* by the shim's check on the tensor.
/* `row_topk` is banded on dtype, so it has two rows. The candidate stages are banded on `n_cand`,
* capped at the kernel's ceiling: five f32 arrays of n_cand in LDS is 20 KiB of the 64 KiB, and the
* shim refuses a wider band (RAD_E_SHAPE). The vocab stages carry `n_vocab` and no dtype key; the
* shim checks that the logits are f32.
*/
static const RadConstraint cRowTopkBf16[] = { C_IN("dtype", "bf16"), C_GE("N", 1), C_GE("R", 1) };
static const RadConstraint cRowTopkF32[] = { C_IN("dtype", "f32"), C_GE("N", 1), C_GE("R", 1) };
static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 1024) };
/* Every key the walk reads is required and in the band, so all of them are bound -- `top_k <= 256`
* is one lane a candidate. `anchor_stride` is deliberately NOT bound: it is optional, defaults to
* 1, and the kernel serves any value at or above 1, so a band that omits it must still resolve. */
/* The block is one key for three things at once: the weight's K block, its row block and the
* quantiser's group. `act` is C_IN because it is a required string here, not the optional `mode`
* form. M <= 64 is the ceiling the launcher serves; 47 of MiniCPM5-2B's 48 bands are M=64. */
/* The container's 2-bit vocab weights. `group` is one key for the weight's K block and the scale's
* block, as everywhere in this family; K must also be a multiple of the launcher's chunk
* (2048 / M-tile), which the launcher refuses and the row does not pretend to cover. */
/* The container's 2-bit vocab weights. `group` is both the weight's K block and the scale's block.
* K must also be a multiple of the launcher's chunk (2048 / M-tile), which the launcher refuses and
* the row does not express. */
static const RadConstraint cGemmQW2A8[] = { C_IN("dtype", "w2a8"), C_EQ("group", R3D_FP8_BLOCK),
C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128),
C_GE("N", 1) };
@@ -844,12 +793,18 @@ static const RadConstraint cGemmQW2A8Tiled[] = { C_IN("dtype", "w2a8 w4a8_asym")
C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17),
C_DIV("K", 128) };
/* `group` is one key for three things: the weight's K block, its row block and the quantiser's
* group. `act` is C_IN because it is a required string here, not the optional `mode` form. M <= 64
* is the launcher's ceiling. */
static const RadConstraint cGemmGated[] = { C_IN("dtype", "fp8a8"),
C_IN("act", "silu sigmoid"),
C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 2),
C_GE("N", 2) };
/* Every key the walk reads is required and in the band, so all are bound; `top_k <= 256` gives each
* candidate one lane. `anchor_stride` is deliberately unbound: it is optional, defaults to 1, and
* the kernel serves any value >= 1, so a band that omits it must still resolve. */
static const RadConstraint cDflashSelect[] = { C_IN("dtype", "bf16"), C_GE("M", 1),
C_GE("steps", 1), C_GE("top_k", 1),
C_LE("top_k", 256), C_GE("rank", 1),
@@ -1121,11 +1076,10 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_quant_fp8.hip
*
* Plain row-major code planes against one f32 scale per (row, group). No fragment permutation for
* the codes a dot2 GEMM reads: it reads them in the order they are stored, which is the whole
* reason a container converted on this card is readable by libref and by `rad-convert` on any other
* card. The one plane that keeps libref's permutation is `quant_act_i8`'s, whose order is part of
* what the op means -- see the row.
* Plain row-major code planes with one f32 scale per (row, group). A dot2 GEMM reads codes in
* stored order, so they carry no fragment permutation, and a container converted on this card is
* readable by libref and by `rad-convert` on any card. Only `quant_act_i8` keeps libref's
* permutation, because its order is part of the op (see the row).
*/
{ "quant_act_fp8_bf16", "quant_act_fp8", "quant",
"symmetric per-(row, group) E4M3: scale = amax * (1/448), the codes the value times 1/scale",
@@ -1136,12 +1090,11 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r3d_rad_quant_act_fp8, nullptr, nullptr, nullptr,
r3d_shape_quant_act_fp8 },
/* The per-row int8, in libref's step order. The order is the op's, not the kernel's convenience:
* the codes are the WMMA A-fragment's, and the plane is what the oracle compares, so this row keeps
* the permutation and the kernel's store address carries it. libr3d's own int8 GEMM reads the
* row-major `quant_act_i8g` plane two rows below, which is the pairing libref's comment states; a
* gfx11 card has no consumer for the step-ordered plane and serves the op so an architecture that
* emits it resolves to a kernel here rather than to the reference. */
/* The per-row int8, in libref's step order. The order belongs to the op: the codes are the WMMA
* A-fragment's and the oracle compares the plane, so the kernel's store address applies the
* permutation. libr3d's own int8 GEMM reads the row-major `quant_act_i8g` plane (two rows below);
* this row exists so an architecture that emits the op resolves to a kernel here rather than to the
* reference. */
{ "quant_act_i8_bf16", "quant_act_i8", "quant",
"symmetric int8 with one scale per row: scale = max(amax, 1e-8) / 127, ties to even, saturating",
"n a multiple of 16, a whole WMMA step; a wave a row of the row sums; the codes stored in the "
@@ -1199,8 +1152,8 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_gemm_bf16_nt_m16.hip
*
* The decode GEMM: M is 1 to 16, so a wave owns a run of N columns and streams the weight's rows
* past an activation kept in registers. There is no fragment layout to fill, which is why this
* kernel reads the checkpoint's rows in order.
* past an activation kept in registers. There is no fragment layout, so the kernel reads the
* checkpoint's rows in order.
*/
{ "gemm_nt_bf16_m16", "gemm_nt", "gemm",
"a[M,K] @ b[N,K]^T for the decode and verify heights, f32 accumulate, one narrowing at the store",
@@ -1218,9 +1171,9 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_gemm_fp8a16_nt_m1.hip
*
* The same shape against a block-scaled weight. The codes are E4M3, widened to f16 exactly and
* The same shape against a block-scaled weight. The E4M3 codes are widened to f16 exactly and
* accumulated by dot2; the block scale is applied once per 128-element slab, after the slab's
* products, which is where the reference applies it.
* products, where the reference applies it.
*/
{ "gemm_nt_q_fp8a16_m16", "gemm_nt_q", "gemm",
"a[M,K] @ b[N,K]^T against E4M3 codes with a scale per 128x128 block",
@@ -1286,8 +1239,8 @@ static const RadKernelInfo kKernels[] = {
{ "silu_mul_bf16", "silu_mul", "elem",
"silu(gate) * up over one fused gate_up plane, the gate the first half",
"any n; a workgroup a row; the activation is NOT narrowed before the product, as ref's is not "
"-- act_mul narrows it, over two operands, because the pair it replaces stored it",
"any n; a workgroup a row; the activation is not narrowed before the product, as ref's is not "
"(act_mul, over two operands, narrows it, as a stored activation is)",
"bf16 in and out, fp32 arithmetic",
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY,
ROW(cSiluMul), NOTUNE,
@@ -1309,8 +1262,8 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_sample_pre_f32.hip
*
* The sampler's pre-filters: one workgroup a row over the logits plane. The history stages are
* sparse -- a row's history is a few hundred tokens against a vocabulary of 130560, so the
* reference's own shape, walk the window and not the row, is the fast shape too.
* sparse (a row's history is a few hundred tokens against a vocabulary of about 130K), so walking
* the window rather than the row, the reference's shape, is also the fast one.
*/
{ "sample_penalties_f32", "sample_penalties", "sample",
"presence, frequency and repetition penalties from the row's history, in place",
@@ -1379,11 +1332,10 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_attn_paged_h128.hip
*
* Paged attention, head_dim 128, banded on q_len. The two kernels share the block walk and differ
* in what a workgroup is: decode is one head group over 16 query rows with split-KV, prefill stages
* a 16-token query tile. The walk's block bounds are the WORKGROUP's -- a tile is staged once into
* LDS and every wave of the workgroup consumes it, and waves that narrowed the walk to their own
* query positions would stage different blocks over the same LDS, the last writer per 16-byte chunk
* winning.
* in what a workgroup is: decode is one head group over 16 query rows with split-KV, prefill a
* 16-token query tile. The walk's block bounds are per workgroup: a tile is staged once into LDS
* and every wave consumes it, so a wave must not narrow the walk to its own query positions, or the
* waves would stage different blocks into the same LDS.
*/
{ "attn_paged_bf16_decode", "attn_paged", "attn",
"paged attention over a bf16 cache: one head group a workgroup, 16-token tiles, split-KV",
@@ -1432,14 +1384,14 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_sample_f32.hip
*
* The sampler's spine: the row's top-R, and the stages that turn the top-R's candidate plane into
* one token. The candidate set is the contract between them -- `cand_val` carries LOGITS, so each
* narrowing stage takes its own softmax and the stages compose in any order; a dropped candidate is
* `cand_idx` -1 and `cand_val` -inf; the set is descending by value then ascending by id; and every
* The sampler's spine: the row's top-R and the stages that turn its candidate plane into one token.
* The candidate set is the contract between them: `cand_val` carries logits, so each narrowing
* stage takes its own softmax and the stages compose in any order; a dropped candidate is
* `cand_idx` -1 and `cand_val` -inf; the set is descending by value, then ascending by id; and every
* stage leaves a greedy row byte-identical, because a greedy row's token is `sample_argmax`'s.
* `topk_next` is a sort by (-value, +column) wearing a loop -- the rule `v == *pv && i <= *pi` is
* "the next one in a run of equal values" -- so one pass keeping the best R returns the reference's
* R pairs, in its order, with its tie-breaks to the lower column.
* `topk_next` is a sort by (-value, +column) written as a loop (`v == *pv && i <= *pi` steps through
* a run of equal values), so one pass keeping the best R returns the reference's R pairs, in its
* order and with its tie-breaks to the lower column.
*/
{ "row_topk_bf16", "row_topk", "moe",
"the row's top R, with the reference's tie-breaks, in one scan of the row",
@@ -1561,30 +1513,25 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_dflash_f32.hip
*
* The speculative decoder's accept step. It is a gather, not arithmetic: two 63.8 MiB codebooks, a
* walk gathering `M * steps * rank` elements, so the score's rank sum is one lane's serial chain --
* there is nothing to hide the gather behind, and a tree would be a different sum for no gain.
* The speculative decoder's accept step. It is a gather, not arithmetic: two 63.8 MiB codebooks and
* `M * steps * rank` gathered elements, so each score's rank sum is one lane's serial chain. There
* is no work to hide the gather behind, and a tree reduction would change the sum for no gain.
*/
/* ------------------------------------------------------------------ r3d_gemm_nt_q_w2a8.hip
*
* `output.weight`: U2 codes, int8 activations, one f32 scale per activation ROW (ZP_I8_ROW), and a
* joined `b_scale` the container writes as two planes -- scale f16 and zero u8 -- behind one operand
* that only a layout hook can present. libref's shape hook declines the dtype for exactly that
* reason, so kbench has no case for the band: the row's opd_shape is null, which is the tool's
* named skip, and the joined plane is built with rad_planes_relayout, the same builder the driver
* uses.
* `output.weight`: U2 codes, int8 activations, one f32 scale per activation row (ZP_I8_ROW), and a
* joined `b_scale` stored as two planes (scale f16, zero u8) behind one operand, which only a layout
* hook can present. libref's shape hook declines the dtype for that reason, so kbench has no case
* for the band: the row's opd_shape is null (the tool's named skip), and the joined plane is built
* with rad_planes_relayout, the same builder the driver uses.
*
* Exactness, measured and not assumed: `v_fdot2_f32_f16` carries ~22 bits of mantissa on integer
* operands, not 24, so an integer dot through it is inexact above 2^20 (71027 of 262144 sampled dots
* at bias 1024, worst |err| 0.125; 70115 and 0.015625 at bias 128). The bias is 128 because the
* error's ratio to the magnitude is ~2^-22 and shrinking the bias shrinks the tail. The result is
* that 0.1-0.2% of outputs land one bf16 ulp off the reference: rel_l2 5.0e-3 at the band,
* max_abs 9.8e-4, no non-finite anywhere. This row is NOT bit-exact by construction, and the dot
* probe in the unit is the check that states it.
* Exactness: `v_fdot2_f32_f16` carries about 22 bits of mantissa on integer operands, not 24, so an
* integer dot through it is inexact above 2^20. The error is about 2^-22 of the magnitude, so a
* smaller bias shrinks the tail; the bias is 128 (sampled worst |err| 0.015625, against 0.125 at
* bias 1024). 0.1-0.2% of outputs land one bf16 ulp off the reference (rel_l2 5.0e-3, max_abs
* 9.8e-4, no non-finite values). This row is not bit-exact; the unit's dot probe states the bound.
*
* M <= 16 is decode. 46 of these per token, 135 GFLOP a token of CPU work that the host row puts on
* the card at 3.0-4.2 ms (66.8 MB of codes at the card's 22 GB/s is the floor; the warm-L2 run is
* 2.43 ms at 30 GB/s).
* M <= 16 is decode.
*/
{ "gemm_nt_q_w2a8_m16", "gemm_nt_q", "gemm",
"the vocab projection at decode: 2-bit codes, int8 activations, the zero removed with a_sum",
@@ -1612,17 +1559,15 @@ static const RadKernelInfo kKernels[] = {
"row needs it to lift the integer bias off its f16-as-int dot. The row's scale and zero are one "
"per ROW on a {1, group} plane, so the staging reads 128 scalars a chunk where the fp8a8 arm reads "
"one, at the row the grid puts it; issued one chunk ahead of the fold that consumes them, because "
"a scalar load with nothing to overlap it is the whole band (210.8 ms against 2.396 ms with the "
"answer hoisted, the same output bits). r3d_tiling.h's swizzle is shared, proven byte-identical",
"a scalar load with nothing to overlap it dominates the band otherwise (the output bits are "
"the same either way). r3d_tiling.h's swizzle is shared, proven byte-identical",
"M <= 16 is gemm_nt_q_w2a8_m16's by its declared C_LE(\"M\", 16); fp8a8 and fp8a16 take their own "
"rows, and the fp8a8 arm refuses a band carrying a_sum at its own line -- a row that silently "
"ignores a band operand passes a checkpoint whose a_sum is garbage. A zero plane stored sub-byte "
"(U2/U4) is refused and named, not approximated: rad_load_bits is the ten-line fix and it is "
"written for the codes, not the zero. Measured, VRAM: M=64 N=130560 K=2048 w2a8 24.151 ms, 1417 "
"GFLOP/s, 3.7 GB/s useful against a 0.449 ms read floor of the 73.1 MB operand -- at kKC=32 a "
"staged chunk draws 8 bytes from a row of pitch 512, so the band moves 8x the bytes it uses and "
"the lever is a wider k-chunk, not more loads in flight (the codes lead measured 0.6%, "
"bit-identical)",
"(U2/U4) is refused and named, not approximated (rad_load_bits reads codes, not zeros). At "
"kKC=32 a staged chunk draws 8 bytes from a row of pitch 512, so the band moves 8x the bytes it "
"uses and is far from its read floor; a wider k-chunk, not more loads in flight, is what would "
"close it",
RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1,
ROW(cGemmQW2A8Tiled), NOTUNE,
nullptr, nullptr, r3d_rad_gemm_nt_q_w2a8_tiled, nullptr,
@@ -1631,12 +1576,10 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_gemm_fp8a8_gated.hip
*
* The gate couples column i to column n+i, so a lane owns both dots and the coupling costs no extra
* weight traffic; the block is one group by 256/group rows so the group's amax closes in-block,
* which is also why there is nothing to tune (the block shape is the quantiser's rule, not a knob)
* and why the row keeps its M ceiling in the prose. At the band's own numbers this is ~341 GFLOP/s
* at M=64 -- 0.7% of the card's fp8 peak, 46 of these per forward pass -- and it is still the row
* the model wants, because the alternative it replaces is the reference's host GEMM: the same 3.2
* GFLOP per layer on the CPU, which is 135 GFLOP a token for this checkpoint.
* weight traffic. The block is one group by 256/group rows so the group's amax closes in-block. That
* block shape is the quantiser's rule, so there is nothing to tune, and the row states its M ceiling
* in the prose. Throughput is low (about 0.7% of the card's fp8 peak at M=64), but the alternative
* is the reference's host GEMM.
*/
{ "gemm_nt_q_gated_fp8a8", "gemm_nt_q_gated", "gemm",
"the gated MLP band's GEMM, its gate and its output quantiser in one launch",
@@ -1678,14 +1621,11 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_vocab_bf16.hip
*
* The head is the largest read in a decode step -- 510 MiB at this checkpoint's 130560 x 2048 -- and
* the sampler reads f32, which is why the store is typed rather than narrowed and why a prefill band
* writes 1.07 GB. Measured on the card: 3.29 ms a token at M=1 (163 GB/s of the head), 0.507 ms a
* token at M=16 (the head read once for sixteen rows), 269 ms for a 2048-token prefill at 4067
* GFLOP/s. Against the reference's law the f32 plane is 1.77e-6 in rel_l2, which is ~30 f32 ulps at
* K=2048 and is the pair-dot folding two products into one rounding -- measured identical against
* the same law with the operands widened to f16 first, so the widening contributes nothing and the
* head's own bf16 quantisation (4.9e-4 an element) is 300x coarser than the row.
* The head is the largest read in a decode step (510 MiB at 130560 x 2048), and the sampler reads
* f32, so the store is f32 rather than narrowed and a prefill band writes about 1 GB. Against the
* reference the f32 plane is at rel_l2 1.77e-6 (about 30 f32 ulps at K=2048), from dot2 folding two
* products into one rounding; widening the operands to f16 first changes nothing. The head's own
* bf16 quantisation (4.9e-4 an element) is 300x coarser.
*/
{ "logits_gemm_bf16", "logits_gemm", "vocab",
"logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T, the head read once a token",
@@ -1710,14 +1650,9 @@ static const RadKernelInfo kKernels[] = {
/* ------------------------------------------------------------------ r3d_gemm_fp8a8_tiled.hip
*
* The prefill projection: this checkpoint declares 176 of these a forward pass (44 of qkv, 44 of
* the gated MLP's 12288 columns, 44 of o, 44 of the 2048-wide one, three of the drafter at
* K=10240), and the reference does their 135 GFLOP a token in a host loop.
* Measured at the graph's own bands, weights in VRAM: 28.171 ms at N=12288 K=2048 (3659 GFLOP/s),
* 14.699 at N=2048 K=6144, 5.911 at N=2560, 4.381 at N=2048 K=2048, 29.798 at N=2048 K=10240 --
* 27 to 36% of the card's dense f16 peak against a byte floor of 0.051 to 0.257 ms. These are the
* first bands in this library where the dot, not the wire, is the limit, and it is the reason the
* E4M3 decoder is a table: at the tile's densities the decode ALU is on the critical path.
* The prefill projection. At these densities the dot product, not memory bandwidth, is the limit
* (about 27-36% of the card's dense f16 peak at the graph's bands), which is why the E4M3 decoder is
* a table: the decode ALU is on the critical path.
*/
{ "gemm_nt_q_fp8a8_tiled", "gemm_nt_q", "gemm",
"y[M,N] = a[M,K] @ dequant(b)^T at prefill heights, the group sub-sum from the raw codes and one "
@@ -1757,10 +1692,8 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r3d_rad_gemm_nt_q_mxfp4a8_tiled, nullptr,
nullptr, nullptr, r3d_shape_gemm_nt_q_mxfp4a8 },
/* The same tiling on gemm_nt's operands, the prefill projection the reference runs on the host: at
* M=2048 this checkpoint's q/k/v/o and the MLP's up/down are 135 GFLOP a token of f32-accumulating
* bf16, and the reference does them on the CPU. The exactness is the m16 row's, because it is the
* same dot. */
/* The same tiling on gemm_nt's bf16 operands, the prefill projection the reference runs on the
* host. The exactness is the m16 row's, because it is the same dot. */
{ "gemm_nt_bf16_tiled", "gemm_nt", "gemm",
"a[M,K] @ b[N,K]^T at prefill heights, f32 accumulate, one narrowing at the store",
"128x128 tiles through LDS, 8x8 f32 accumulators a lane, k ascending in 32-code chunks, the "
@@ -1769,7 +1702,7 @@ static const RadKernelInfo kKernels[] = {
"the other's band",
"bf16 a, b and y, fp32 accumulation; the pair is folded into the accumulator by one rounding, so "
"about 0.3% of a long-K output lands one bf16 store ulp from the reference's, and no output is "
"further. 99.93% bit-exact measured at the 512-column twin, 100% within two ulps",
"further",
RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED,
ROW(cGemmNTTiled), NOTUNE,
nullptr, nullptr, r3d_rad_gemm_nt_bf16_tiled, nullptr,
@@ -1779,17 +1712,16 @@ static const RadKernelInfo kKernels[] = {
/* ================================================================== the exports
*
* The two every plugin must export, the four that make a kernel library, and `rad_kernel_concurrent`.
* The two exports every plugin needs, the four that make a kernel library, and
* `rad_kernel_concurrent`.
*
* libr3d exports no `rad_kernel_chain`: chaining replaces the queue's ordering bit between two
* dependent launches with a spin in the kernel, and it pays where a wave is idle during that spin.
* Nothing here is built as a chained form, so the answer would be 0 for every row; the symbol is
* left out, which is the same answer with one less thing to keep in step (ABI,
* `rad_kernel_chain`: "without the symbol, or with 0, the engine never asks").
* No `rad_kernel_chain`: chaining replaces the queue's ordering between two dependent launches with
* a spin in the kernel, and no row here has a chained form, so every answer would be 0. Omitting the
* symbol means the same (ABI, `rad_kernel_chain`: "without the symbol, or with 0, the engine never
* asks").
*
* It exports no `rad_kernel_collective` either: there is no second rank in this plugin's world. The
* cards that run these rows are single-GPU cards, and an all-reduce over the PCIe x1 slot most of
* them sit in is slower than sending the bytes through the host.
* No `rad_kernel_collective`: these rows run on single-GPU cards, and an all-reduce over the PCIe x1
* slot most of them sit in is slower than going through the host.
*/
extern "C" int rad_kernel_count(void) {
return (int)(sizeof(kKernels) / sizeof(kKernels[0]));
@@ -1799,18 +1731,16 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
return &kKernels[i];
}
/* Which rows touch nothing but their operands and the scratch they were handed.
/* Which rows touch nothing but their operands and their scratch.
*
* The elementwise, norm, quant, cast, rope, cache and gather rows do: one launch, one pass, no
* state between launches, so two of them may run at once and the engine can start a row before an
* independent earlier one finishes.
* The elementwise, norm, quant, cast, rope, cache and gather rows: one launch, one pass, no state
* between launches, so two may run at once and the engine can start one before an independent
* earlier one finishes.
*
* The GEMM rows do not, and the reason is the scratch, not the kernel. The scratch arena belongs to
* the op instance, so two layers' decode GEMMs launched at the same time share it: a split-K row's
* partials and arrival counters from the two launches would land on each other. With sk = 1 a GEMM
* launch has no partials and is safe, but the promise is per row and the axis is chosen per
* geometry, so the row states the worst case. When split-K is off on a given card (a tuned point of
* sk = 1 for every shape), the loss is one overlap the engine would have taken.
* Not the GEMM rows, because of the scratch: the arena belongs to the op instance, so two layers'
* decode GEMMs launched together share it and their split-K partials and arrival counters would
* collide. With sk = 1 a GEMM has no partials, but the promise is per row and sk is chosen per
* geometry, so the row states the worst case.
*/
extern "C" int rad_kernel_concurrent(int i) {
const RadKernelInfo* k = rad_kernel_at(i);
@@ -1824,14 +1754,12 @@ static const RadPluginInfo kInfo = {
"0.1.0",
"the RDNA3 (gfx11) kernel library: the elementwise, norm, rope, cache and embedding rows, fp8 "
"and int8 activation quantisation with its dequant and gated forms, and the skinny bf16 and "
"fp8a16 GEMMs, every one of them through v_dot2acc_f32_f16 because RDNA3 has no matrix "
"instruction a compiler will emit",
"fp8a16 GEMMs, the matrix work through v_dot2acc_f32_f16 rather than RDNA3's WMMA "
"fragment layout",
/* The architectures this build's code objects run on, spelled as `RadDeviceProps::arch`. The
* loader compares a device's arch against these words and warns once when the code object it
* picked names a card this list does not (`target_covers`), so the string has to be the build's
* real targets rather than an author's guess at them.
* RAD_GPU_TARGETS reaches this source as a compile definition from CMakeLists.txt; the fallback
* is the whole family, which is what a build that did not say is claiming. */
* loader warns once when the code object it picked names a card this list does not
* (`target_covers`), so the string must be the build's real targets. R3D_BUILD_TARGET comes
* from CMakeLists.txt as a compile definition; the fallback is the whole family. */
R3D_BUILD_TARGET,
};