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

+182 -262
View File
@@ -1,128 +1,101 @@
/* r3d_gemm_fp8a8_gated.hip -- gemm_nt_q_gated: the gated MLP's GEMM, its gate and its quantiser in
* one launch. 48 bands on one 2B model (N=12288 K=2048 group=128 dtype=fp8a8 act=silu, M=64 x47
* and M=16), and the reason the [M, N] bf16 intermediate never exists.
/* r3d_gemm_fp8a8_gated.hip -- gemm_nt_q_gated: the gated MLP's GEMM, gate and quantiser in one
* launch, so the [M, N] bf16 intermediate is never materialised. On the 2B model it serves
* (N=12288 K=2048 group=128 dtype=fp8a8 act=silu) 47 bands are M=64 and one is M=16.
*
* y[M,n] = gate(a[M,K] @ b[N,K]^T), quantised: n = N/2, gate half = b's rows [0, n),
* up half = [n, N). `q` is E4M3 codes over y, `scale` one f32 per (row, `group` of n), and
* `out_bf16`, when bound, is exactly the bf16 the codes were taken over.
* `out_bf16`, when bound, is the bf16 the codes were taken over.
*
* The law is ref_gemm_nt_q_gated and it is transcribed in its order:
* Transcribed from ref_gemm_nt_q_gated, in its order:
*
* row[j] = quant_dot(ma, mb, SA, SB, m, j, K) over the FULL N, j ascending
* gt = round_bf16(row[i]), up = round_bf16(row[n + i]) BOTH halves, before the gate
* sg = 1 / (1 + exp(-gt)) the gate is the FIRST half
* row[j] = quant_dot(ma, mb, SA, SB, m, j, K) over the full N, j ascending
* gt = round_bf16(row[i]), up = round_bf16(row[n + i]) both halves, before the gate
* sg = 1 / (1 + exp(-gt)) the gate is the first half
* h = f32_to_bf16((act == silu ? gt * sg : sg) * up) the activation is not narrowed
* fp8_row(h, n, group) amax -> scale[m, group], codes
*
* Both halves are narrowed before the gate because the unfused pair writes a bf16 [M, N] tensor and
* re-reads it: the fused form must be byte-identical to the pair it replaces, so the narrowing that
* the store performed is kept, and `out_bf16` is what the pair's tensor held. The activation itself
* is NOT narrowed -- `gt * sg` is formed in f32 from the narrowed gate, and the product with `up`
* Both halves are narrowed before the gate because the unfused pair writes and re-reads a bf16
* [M, N] tensor, and the fused form must be byte-identical to it; `out_bf16` is what that tensor
* held. The activation is not narrowed: `gt * sg` is formed in f32 and the product with `up`
* rounds once, at the store.
*
* ---- the lane map: one lane owns a PAIR of dots -----------------------------------------------
* ---- the lane map: one lane owns a pair of dots -----------------------------------------------
*
* The gate couples column i with column n + i, and a wave covers 32 consecutive columns, so the
* partner column is 192 waves away for the band's n = 6144: no lane-to-lane exchange reaches it, and
* staging a whole row through LDS to reach it costs a round trip of the [M, N] tensor this op exists
* to avoid. So the lane owns BOTH products of its column: it walks k ascending with two accumulators
* and reads two weight rows, `i` and `n + i`. The weight traffic is unchanged -- the pair of rows is
* exactly the traffic the unfused GEMM spent on the two columns -- and the coupling is free.
* The gate couples column i with column n + i, which for n = 6144 is 192 waves away: no lane
* exchange reaches it, and staging the row through LDS would cost the round trip this op avoids.
* So each lane computes both products of its column, walking k ascending with two accumulators over
* weight rows `i` and `n + i`. The weight traffic equals the unfused GEMM's for the two columns.
*
* A block covers ONE group of `group` output columns and RP = 256 / group rows, so a lane is
* A block covers one group of `group` output columns and RP = 256 / group rows:
*
* i = blockIdx.x * group + (tid % group) m = blockIdx.y * RP + tid / group
*
* and a wave's 32 lanes are 32 consecutive columns of one group of one row, for group >= 32. That
* alignment is what closes the epilogue inside the block: the group's amax is a wave max folded over
* the group's group/32 waves in LDS, the scale is one store, the codes are one byte a lane. The
* whole op -- product, gate, quantiser -- is one launch and no scratch, which is why the row is
* concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`) and why the bf16 row of the
* intermediate is not written, read, or allocated.
* so for group >= 32 a wave's 32 lanes are 32 consecutive columns of one group of one row. The
* epilogue therefore closes inside the block: the group's amax is a wave max folded over group/32
* waves in LDS, the scale is one store, the codes one byte per lane. The op is one launch with no
* scratch, so the row is concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`).
*
* ---- the two streams: fp8a8 at M <= 8 reads the codes, the rest stages them -------------------
* ---- the two arms: fp8a8 at M <= 8 reads the codes directly, the rest stage them --------------
*
* The band's served case is a decode: one row, the whole 12288 x 2048 operand, 42 calls a token.
* The shape above is built for the band's declared ceiling (M = 64, 47 of the 48 bands) and serves
* that height well; at M = 1 it spends 987 us on 24 MiB of codes, 25 GB/s, and the reason is not
* the loads. It is the path a code takes: global -> LDS stage -> decode -> dot, with two
* `group_barrier`s per k-block holding the block in step, and a decoder of ten VALU a code (RDNA3
* has no fp8 instruction: r3d_codecs.h, and the builtins that look like one are rejected at
* instruction selection on gfx1102).
* The staged shape below suits the bands' ceiling (M = 64) but not decode (M = 1, the whole
* 12288 x 2048 operand, 42 calls per token). Its cost there is the path a code takes: global ->
* LDS stage -> decode -> dot, with two `group_barrier`s per k-block, and an arithmetic decoder of
* ten VALU per code (RDNA3 has no fp8 instructions; see r3d_codecs.h). The launcher picks the arm
* by row count:
*
* So the arm is chosen by the row count, in the launcher, from the same band key:
* M <= 8 and fp8a8 read the activation and both weight rows directly, 16 bytes at a time,
* decode them from a 256-entry table the block builds once, and multiply. No
* shared memory between load and dot, no barrier in the k-loop, six loads in
* flight.
* M >= 9, and every fp8a16 case the staged shape, with the same table decoder. At these
* heights the grid is 48 x M/2 blocks and occupancy feeds the stream.
*
* M <= 8 and fp8a8 read the activation and both weight rows straight from memory, 16 bytes at
* a time, decode them out of a 256-entry table the block builds once, and
* multiply. No shared memory between a load and a dot, no barrier in the
* k-loop, six loads in flight.
* M >= 9, and every fp8a16 case the shape above, with the same table decoder in place of the
* arithmetic one. At these heights the grid is 48 x M/2 blocks and occupancy,
* not the window, is what feeds the stream; the stage pays for itself.
* On the band's stream (24 MiB of codes, kernel loop without the epilogue) the staged arithmetic
* path takes 497 us, the direct table path 187 us, and the bare loads 139 us. The table decoder
* also cuts M = 64 by about two thirds at no register cost (109 per lane, four waves per SIMD, no
* spills).
*
* Measured on the band, vram, GPU 2, nine launches timed on their own, best/median:
*
* M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the card's 163 GB/s
* M = 2 1120.6 / 1196.5 -> 166.2 / 177.1 us floor for 24 MiB is 154 us, and the same
* M = 4 1417.3 / 1581.2 -> 221.0 / 229.6 us sixteen loads with no decode and no dot
* M = 8 1874.0 / 2318.0 -> 403.4 / 412.3 us run in 139 us)
* M = 16 2949.3 / 3226.1 -> 1055.0 / 1160.6 us
* M = 32 5123.4 / 5405.1 -> 1660.6 / 1705.0 us
* M = 64 8395.3 / 9051.0 -> 2786.5 / 2877.3 us
*
* The two numbers behind the shape, both from the band's own stream (24 MiB of codes, vram, 11
* launches, this kernel's loop with the epilogue off): staged through LDS and decoded arithmetically
* 497 us; read straight and decoded from the table 187 us; the read alone 139 us. The table alone
* moves M = 64 from 8395 us to 2786 us -- two thirds of the tall arm's gain is the decoder, and it
* costs nothing in registers (109 a lane, four waves a SIMD, zero spills).
*
* Two things in this file are load-bearing. The table's argument is a PAIR, not an index (see
* build_e4m3_table). And the decoded pairs go from the table into the dot inline, never through an
* array (see the tall arm's step_body).
* Two invariants: the table builder's codec argument is a pair, not an index (build_e4m3_table),
* and decoded pairs go from the table into the dot inline, never through an array (step_body).
*
* ---- where the scale multiplies -------------------------------------------------------------
*
* quant_dot, unchanged from r3d_gemm_fp8a16_nt_m1.hip: per group of k a sub-sum from zero over
* ascending k of the CODES' products, then `acc = acc + (sub * sa) * sb` -- the parentheses are the
* reference's, the scale multiplies the finished block once, and `sa` is `a_scale[m][gi]` (1 when
* the activation carries no scale plane). Each lane's two chains are the two calls the unfused pair
* makes, so the bracketing is the pair's, element for element.
* quant_dot, as in r3d_gemm_fp8a16_nt_m1.hip: per group of k a sub-sum from zero over ascending k
* of the codes' products, then `acc = acc + (sub * sa) * sb` with the reference's parentheses, `sa`
* being `a_scale[m][gi]` (1 without a scale plane). Each lane's two chains are the unfused pair's
* two calls, so the bracketing matches element for element.
*
* b_scale is bf16: this op's shape hook writes `o.t(RAD_BF16, {nb, kb})` with no f32 spelling, so
* the plain entry reads the plane as bf16 and the `_ex` twin takes the dtype, as the fp8 GEMM's
* does. bf16 -> f32 widening is exact, so an f32 plane carrying the same values must produce
* bit-identical output; the driver tests exactly that.
* b_scale is bf16: this op's shape hook writes `o.t(RAD_BF16, {nb, kb})` with no f32 form, so the
* plain entry reads bf16 and the `_ex` entry takes the dtype, as for the fp8 GEMM. bf16 -> f32
* widening is exact, so an f32 plane with the same values gives bit-identical output (the test
* driver checks this).
*
* ---- the epilogue's one transcendental -------------------------------------------------------
*
* libref's sigmoid is `1.0f / (1.0f + (float)std::exp((double)(-x)))`. There is no f64 ALU on this
* card (1:64, emulated), and the band asks for M*n = 393216 exponentials a layer, which is
* attention's regime and not the sampler's. `expf` is the accurate device form, as in
* r3d_gated_quant_fp8's kernel (r3d_quant_fp8.hip), not `__expf`; what it feeds is a bf16
* narrowing, whose ulp is 2^-8 against the transcendental's ~1e-7, so the narrowing lands the same
* bf16 everywhere but on a tie. The count of those ties is in the row's prose, measured.
* libref's sigmoid is `1.0f / (1.0f + (float)std::exp((double)(-x)))`. f64 runs at 1:64 on this
* card, and the band needs M*n = 393216 exponentials per layer, so the kernel uses the accurate
* device `expf` (not `__expf`), as r3d_gated_quant_fp8 (r3d_quant_fp8.hip) does. Its ~1e-7 error is
* far under the bf16 ulp of 2^-8 the result is narrowed to, so the bf16 differs only on a tie; the
* row's text records the tie count.
*
* ---- what the launcher refuses ----------------------------------------------------------------
*
* M > 64 (the bands' ceiling, and past it the weight stream -- M reads of an [N, K] plane from L2 --
* is the wall, which is a tiled kernel's problem, not this one's); N odd (the reference's own
* `N & 1` test); a group that is not a power of two in [32, 256] (a wave must sit inside one group,
* and the block is one group wide); group > n, where the reference defaults the QUANTISER's group to
* n and leaves the weight's K block at the stated width: two widths this kernel reads as one, so it
* refuses rather than serve a geometry whose two grids disagree; K % group != 0, because a ragged K
* block reads past the scale plane; sk > 1, because no K slab closes an epilogue that needs the
* whole row. Refusals are codes: -1 null, -2 shape, -3 pitch, -4 HIP.
* M > 64 (the bands' ceiling; beyond it the M reads of an [N, K] plane from L2 are a tiled
* kernel's problem); N odd (the reference's `N & 1` test); a group that is not a power of two in
* [32, 256] (a wave must sit inside one group, and the block is one group wide); group > n, where
* the reference would use n for the quantiser's group but keep the stated K block, two widths this
* kernel reads as one; K % group != 0, because a ragged K block reads past the scale plane; sk > 1,
* because the epilogue needs the whole row. Codes: -1 null, -2 shape, -3 pitch, -4 HIP.
*
* ---- relayout: none, and it is a claim ---------------------------------------------------------
* ---- no relayout ------------------------------------------------------------------------------
*
* libref reads the gated weight [N, K] row-major; libr4d stores fp8a8 weights in WMMA fragment order
* (`r4d.fp8.w.frag64`). The two readings are ~1.35 apart, a relative error, not noise, so this row
* carries no relayout and says so: a row that inherits the fp8 GEMM's unrelayout scores 1.35 against
* the per-op oracle and reads as a broken kernel. The stored order is the reading order here, which
* is the library's rule for every row.
* This row reads the gated weight [N, K] row-major, as libref does. libr4d stores fp8a8 weights in
* WMMA fragment order (`r4d.fp8.w.frag64`); the two readings differ by a relative error of ~1.35,
* so a row that inherited the fp8 GEMM's relayout would fail the per-op oracle. The stored order
* is the reading order, as for every row in the library.
*/
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD uses
#include "r3d.h"
#include "r3d_common.h"
@@ -134,27 +107,23 @@ namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load
constexpr int kWin = 64; // codes a lane takes per WINDOW: four loads per stream
constexpr int kStep = 16; // codes per lane step: one 16-byte load
constexpr int kGroupMin = 32; // a wave's 32 columns must sit inside one group
constexpr int kGroupMax = 256; // a block is one group wide, at 256 threads
constexpr int kMMax = 64; // the bands' ceiling: 47 of the 48 are M = 64
constexpr int kMMax = 64; // the bands' ceiling
constexpr float kTopE4M3 = 448.0f; // q8_group's top for E4M3: the largest finite code
/* The E4M3 decoder as a table: 256 f16, one entry per code. The codec's arithmetic decode is ten
* VALU a code (r3d_codecs.h -- RDNA3 has no fp8 instruction, and the builtins that look like one
* are rejected at instruction selection), and this kernel decodes every weight code it multiplies,
* twice over at RP = 2, which at M = 1 is every code in the operand. The table costs two
* `ds_read_u16` and a pack a PAIR, and it is exact by construction: the entry for code c is the
* dword the arithmetic path returns for c, computed by that path at the block's first instruction.
* The unit test reads all 256 entries back and compares them with the codec. */
* VALU per code (r3d_codecs.h), and this kernel decodes every weight code it multiplies (twice at
* RP = 2). The table costs two `ds_read_u16` and a pack per pair, and is exact: entry c is what the
* arithmetic path returns for c, computed by that path at block start. The unit test reads all 256
* entries back and compares them with the codec. */
__device__ __forceinline__ void build_e4m3_table(uint16_t* tab, uint32_t tid)
{
for (uint32_t u = tid; u < 128; u += kBlockThreads)
/* The codec's argument is a PAIR, low code in the low byte; the entry is indexed by code.
* Feeding it the index alone fills the even entries and decodes code 0 into every odd one,
* so the kernel multiplies half the plane by zero -- the board's `codes256` case, whose
* weight is the code enumeration, shows it: rel_l2 9.6e-01, not a NaN. */
/* The codec's argument is a pair, low code in the low byte; the entry is indexed by code.
* Passing the index alone would decode code 0 into every odd entry and silently zero half
* the products (the `codes256` test case catches this). */
*(uint32_t*)&tab[2 * u] = e4m3x2_to_f16x2((u * 2) | ((u * 2 + 1) << 8));
}
@@ -165,10 +134,9 @@ __device__ __forceinline__ uint32_t tab_pair(const uint16_t* tab, uint32_t pair)
return lo | (hi << 16);
}
/* One step of the skinny arm: sixteen codes of activation and sixteen of weight, both coded, both
* out of the same table. This is the whole of the reference's inner step -- `sub += a[k] * b[k]`,
* k ascending -- with the pairs decoded as each dot consumes them. Four dot4, the pairs in order,
* one accumulator; nothing about it depends on where the bytes came from. */
/* One step of the skinny arm: sixteen activation codes and sixteen weight codes, both decoded from
* the same table as each dot consumes them. The reference's `sub += a[k] * b[k]`, k ascending: four
* dot4, pairs in order, one accumulator. */
__device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u32x4 a,
const r3d_u32x4 c, float sub)
{
@@ -183,14 +151,11 @@ __device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u
return sub;
}
/* One step's sixteen codes into the accumulator: four dot4, the pairs decoded out of the table as
* each dot consumes them. Materialising the eight pairs first and feeding the dots from the array
* is what the register file cannot afford here: the scheduler hoists the sixteen table reads, so
* all eight decoded pairs are live at once on top of the window's loads. Consuming a pair in the
* dot that wants it keeps two registers live where the array keeps eight -- which is the
* difference between this arm compiling at zero spills and spilling 374 bytes against the
* 128-register budget a 256-thread block gets at four waves a SIMD. The order is unchanged: the
* pairs ascend, four dot4 a step, into one accumulator. */
/* One step's sixteen weight codes into the accumulator: four dot4, pairs decoded from the table as
* each dot consumes them. Materialising the eight pairs in an array first lets the scheduler hoist
* all sixteen table reads, keeping eight decoded pairs live instead of two, which spills against
* the 128-register budget of a 256-thread block at four waves per SIMD. Pairs ascend into one
* accumulator. */
__device__ __forceinline__ float dot_step(const uint16_t* tab, const r3d_u32x4 c,
const r3d_u32x4 a0, const r3d_u32x4 a1, float sub)
{
@@ -211,8 +176,8 @@ __device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p) { return *(const r3d_u32x4*)p; }
/* q8_group's clamp, with q8_group's comparisons: fminf/fmaxf replace a NaN with the bound, and a NaN
* activation is a value the reference encodes as the format's NaN, not as +-top. */
/* q8_group's clamp, with q8_group's comparisons rather than fminf/fmaxf, which would replace a NaN
* with the bound; the reference encodes a NaN activation as the format's NaN, not +-top. */
__device__ __forceinline__ float clamp_top(float c)
{
if (c > kTopE4M3) c = kTopE4M3;
@@ -220,16 +185,15 @@ __device__ __forceinline__ float clamp_top(float c)
return c;
}
/* y[M,n] = gate(a @ b^T), with the quantiser. GROUP is the block's width in output columns AND the
* weight's K block AND the quantiser's group: one `group` parameter, three grids, which is what the
* op states: kb, nb and ng are derived from the one key. ACT is the gate, A8 the coded activation,
* NT the weight load's lowering.
/* y[M,n] = gate(a @ b^T), with the quantiser. GROUP is at once the block's width in output columns,
* the weight's K block and the quantiser's group: the op states one `group` key, and kb, nb and ng
* derive from it. ACT is the gate, A8 the coded activation, NT the weight load's lowering, WIN the
* skinny (direct-read) arm.
*
* The activation is staged in LDS per K block, widened to f16 pairs on the way in -- E4M3 -> f16 and
* bf16 -> f16 are both exact over f16's normal range. A block stages RP * GROUP values, 512 bytes at
* every supported GROUP, and a wave reads its row's 16 values per step as one broadcast ds_read: all
* 32 lanes of a wave own the same m, so all 32 read the same address. The weight is not staged: a
* lane streams two rows of it and no other lane reads them with it. */
* The tall arm stages the activation in LDS per K block, widened exactly to f16 pairs. A block
* stages RP * GROUP values (512 bytes at every supported GROUP). All 32 lanes of a wave share one
* m, so a wave reads its row's 16 values per step as one broadcast ds_read. The weight is not
* staged: each lane streams two rows no other lane reads. */
template <int GROUP, int ACT, bool A8, bool NT, bool WIN>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_kernel(
const uint8_t* __restrict__ A, const float* __restrict__ AScale,
@@ -237,8 +201,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
uint8_t* __restrict__ Q, float* __restrict__ S, uint16_t* __restrict__ Y,
int M, int N, int K, int a_ld, int q_ld, int y_ld, int nkb, int ng)
{
constexpr int RP = kBlockThreads / GROUP; // rows a block carries
constexpr int AP = GROUP / 2; // dwords a staged activation row (f16 pairs)
constexpr int RP = kBlockThreads / GROUP; // rows per block
constexpr int AP = GROUP / 2; // dwords per staged activation row (f16 pairs)
constexpr int WPG = GROUP / kWave; // waves covering one group of columns
static_assert(RP >= 1 && WPG >= 1 && RP * WPG == kWaves, "a block is one group wide");
@@ -250,10 +214,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
/* The block's decoder, filled before any lane reads it: 128 dwords, one per pair of codes, by
* the codec's own arithmetic. The cost is 128 decodes a block -- at the band's M = 64 that is
* 0.02% of the block's decodes, and at M = 1 it is paid once per block for 128 codes x 16 k
* blocks of table reads. */
/* The block's decoder table, filled before any lane reads it: 128 dwords, one per pair of
* codes, 128 arithmetic decodes per block. */
build_e4m3_table(s_tab, tid);
group_barrier();
@@ -263,15 +225,15 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
const uint32_t m = (uint32_t)blockIdx.y * RP + mloc;
const int n = N / 2;
/* A ragged last group runs past n: the pair's rows are clamped, so no lane reads past the weight
/* A ragged last group runs past n: the pair's rows are clamped so no lane reads past the weight
* plane, and its stores are guarded below. A row past M re-reads the last real row. */
const int i_real = (int)(i < (uint32_t)n ? i : (uint32_t)(n - 1));
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
const uint8_t* wg = B + (size_t)i_real * K; // the gate's row
const uint8_t* wu = B + (size_t)(n + i_real) * K; // the up's row, n rows further on
/* b_scale is [ceil(N/group)][ceil(K/group)]: make_scales gives rblk = group (fewer scale rows
* than operand rows is a block grid), so a row's scale row is its row index over the block. */
/* b_scale is [ceil(N/group)][ceil(K/group)] (make_scales uses rblk = group), so a row's scale
* row is its row index divided by the block. */
const size_t bsg = (size_t)((uint32_t)i_real / GROUP) * (size_t)nkb;
const size_t bsu = (size_t)((uint32_t)(n + i_real) / GROUP) * (size_t)nkb;
const float* bsF = bs16 ? nullptr : (const float*)BScale;
@@ -280,23 +242,19 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
float acc_g = 0.0f, acc_u = 0.0f;
/* One scale block per round, `nkb` of them: stage the block's activation, walk the block's k
* with two chains, fold the block's two scales in at the block's end. K is a multiple of GROUP,
* which the launcher requires, so every block is whole and the staging loop has no tail. */
/* The skinny arm's activation pointer: the row, in bytes. */
/* One scale block per iteration, `nkb` of them: stage the block's activation, walk its k with
* two chains, apply its two scales at the end. The launcher requires K % GROUP == 0, so every
* block is whole and staging has no tail. */
/* The skinny arm's activation row, in bytes. */
const uint8_t* ar = (A8 && WIN) ? (const uint8_t*)A + (size_t)m_real * a_ld : nullptr;
for (int kb = 0; kb < K; kb += GROUP) {
const int gi = kb / GROUP;
/* The staged round, and the barrier around it, belong to the tall arms. At the skinny height
* -- M <= 8, the threshold `R3D_GT_G` selects on, 16 KiB of activation at the band's K --
* the whole activation is M*K bytes and the 48 column groups of a row all
* read the same slice of it, so it lives in L1 from the first k-block on and staging it
* through shared memory buys nothing but a barrier a block a k-block. The numbers: the
* same stream read straight from memory 187 us, the same stream staged through LDS 497 us,
* at 48 blocks, 24 MiB of codes, on a part of this family. */
/* Staging and its barrier belong to the tall arm. At the skinny height (M <= 8, at most
* 16 KiB of activation at the band's K) all 48 column groups read the same activation
* slice, so it stays in L1 and staging would only add a barrier per k-block. */
if constexpr (!WIN) {
constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) a unit
constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) per unit
constexpr int nu = GROUP / kUnit;
#pragma unroll
for (int u = (int)tid; u < RP * nu; u += kBlockThreads) {
@@ -312,8 +270,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
dst[2] = e4m3x2_to_f16x2(b8.y & 0xffffu);
dst[3] = e4m3x2_to_f16x2(b8.y >> 16);
} else {
/* Cast to the element pointer FIRST: the row and k offsets are ELEMENT offsets,
* which for bf16 is twice the byte count (r3d_gemm_fp8a16_nt_m1.hip). */
/* Cast to the element pointer first: the row and k offsets are bf16 element
* offsets. */
const r3d_u32x4 b16 = *(const __attribute__((address_space(1))) r3d_u32x4*)(
(const uint16_t*)A + (size_t)rr * a_ld + kb + c);
dst[0] = bf16x2_to_f16x2(b16.x);
@@ -327,49 +285,29 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
}
const uint32_t* ap = s_a + (size_t)mloc * AP;
/* One chain at a time. The gate's product, k ascending into `sub_g`, then the up's into
* `sub_u` -- the two chains are the two calls the unfused pair makes, they share nothing,
* and each one's bracketing is that call's, element for element.
/* The two chains, gate into `sub_g` and up into `sub_u`, each k ascending: the unfused
* pair's two calls, each with that call's bracketing.
*
* Sequencing them, rather than interleaving them step by step, is what the register file
* asks for. The window is eight 16-byte loads a stream; holding both streams' windows
* live at once is 64 registers of loads on top of the decode's temporaries, the staged
* activation's reads, the two accumulators and the block's pointers, and at 256 threads
* (four waves a SIMD, 128 registers a lane) it spills 365 bytes. One chain's window is
* 32 registers, and the arm compiles clean.
*
* On the band's stream -- 24 MiB of codes, vram, 11 launches, GPU 2, this kernel's loop
* with the epilogue off: 16-byte step with the arithmetic decoder 584 us; table decoder,
* same step 453 us; table, window 64 283 us; table, window 128 187 us; the same sixteen
* loads with no decode and no dot 139 us. The op without the table decoder and the window
* spends 1474 us a call. */
* The skinny arm runs the chains one after the other rather than interleaved: holding
* both streams' windows live (64 registers of loads, on top of everything else) spills at
* 256 threads (four waves per SIMD, 128 registers per lane), while one chain's window is
* 32 registers and does not. */
float sub_g, sub_u;
if constexpr (WIN) {
/* The skinny arm, M <= 8 (the threshold `R3D_GT_G` selects on): read the codes, decode
* them out of the block's table, multiply
* them. No shared memory between the load and the dot, and no barrier in the k-loop --
* the two chains, gate then up, k ascending inside each, the scales folded at the block's
* end, the epilogue below untouched.
*
* Three loads a step, sixteen bytes each: the activation's sixteen codes, the gate's,
* the up's. Six of them are in flight at the depth below, against the 163 GB/s the card
* does; the tall arms feed the same stream with occupancy, at 32 waves a CU.
*
* On this band's stream (24 MiB of codes, vram, 11 launches, GPU 2, epilogue off):
* the staged shape 497 us; the same codes read straight 187 us; the same sixteen loads
* with no decode and no dot 139 us. The op without the table decoder and the window
* spends 1474 us a call. */
constexpr int kNS = GROUP / kStep; // steps a block
constexpr int kD = 2; // loads a chain in flight
/* The skinny arm, M <= 8 (selected by `R3D_GT_G`): load the codes, decode them from
* the block's table and multiply, with no shared memory between load and dot and no
* barrier in the k-loop. Each step loads 16 bytes of activation and 16 of weight;
* prefetching two steps ahead keeps loads in flight, where the tall arm relies on
* occupancy (32 waves per CU). */
constexpr int kNS = GROUP / kStep; // steps per block
constexpr int kD = 2; // loads in flight per chain
auto chain = [&](const uint8_t* w, float sub) {
auto ld = [&](int st) {
return ldc<NT>(w + kb + (st < kNS ? st : kNS - 1) * kStep);
};
/* Named registers, not an array: an array indexed across a round -- even with the
* round count constant and the loop marked for unrolling -- puts the codes in the
* private segment, 572 bytes a lane, and every code crosses scratch on its way from
* the load to the dot. Two named dwords-in-four, prefetched two steps ahead, keep
* the same six loads in flight and the frame at zero. */
/* Named registers, not an array: an array indexed across iterations, even with a
* constant trip count and unrolling, is placed in private (scratch) memory. Two
* named 16-byte registers, prefetched two steps ahead, keep the frame at zero. */
r3d_u32x4 c0 = ld(0), c1 = ld(1);
#pragma unroll
for (int st = 0; st < kNS; st += kD) {
@@ -387,25 +325,19 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
sub_g = chain(wg, 0.0f);
sub_u = chain(wu, 0.0f);
} else {
/* The tall arms: one 16-code step a round, both streams in the same round.
* At M >= 8 the block grid is 48 x M/2 blocks, the wave slots are full, and the stream
* is fed by occupancy -- 109 registers a lane, four waves a SIMD, 32 waves a CU. The
* window is a skinny-arm fix: it buys its loads per lane at 32 registers, which on
* this arm is a fifth wave a SIMD given up, and on the 47 bands at M = 64 that is the
* whole op. Measured: windowed at M = 64 costs more than it saves. */
/* The tall arm: one 16-code step per iteration, both streams in the same iteration.
* At M >= 9 the grid is 48 x M/2 blocks and occupancy feeds the stream (109 registers
* per lane, four waves per SIMD, 32 waves per CU). A load window would cost 32
* registers per lane here, and at M = 64 it costs more than it saves. */
sub_g = 0.0f;
sub_u = 0.0f;
/* The round's unroll depth is a register decision, and at group = 32 it is the whole
* decision: the block is two steps wide, so `unroll 2` is a full unroll, the scheduler
* takes all thirty-two table reads of the two chains and hoists them above the dots,
* and the arm lands at 128 registers with 12 spilled (the same arm at group >= 64, in
* the same file, is 106 to 112 with none). Left as a loop the body is one step. */
/* Inline, from the table into the dot, on purpose. Materialising the eight decoded
* pairs into an array on the way -- the shape the arithmetic decoder above feeds --
* puts the plane about a third away from the reference at every tall height (M = 7:
* rel_l2 6.6e-01; M = 64: -nan), with the table itself exact on the device, entry by
* entry and pair by pair. The array form is the one that miscomputes here; do not
* restore it as a tidy-up. */
/* Unroll depth is a register decision. At group = 32 the block is two steps wide, so
* `unroll 2` is a full unroll: the scheduler hoists all 32 table reads of both chains
* above the dots and the arm spills at 128 registers. group = 32 therefore stays a
* one-step loop; group >= 64 unrolls by 2 without spilling. */
/* Do not materialise the eight decoded pairs into an array on the way to the dot:
* that form miscomputes on this arm (rel_l2 6.6e-01 at M = 7, NaN at M = 64) although
* the table itself is exact. Keep the decode inline. */
auto step_body = [&](int k) {
const r3d_u32x4 a0 = lds_a(ap + k / 2);
const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4);
@@ -421,9 +353,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
}
}
if constexpr (!WIN)
group_barrier(); // the next block's stage must not race this one's reads
group_barrier(); // the next block's stage must not race these reads
/* The two finished sub-sums, each scaled once, in libref's parentheses. */
/* The two sub-sums, each scaled once, in libref's parentheses. */
const float sa = A8 ? as[gi] : 1.0f;
acc_g = acc_g + (sub_g * sa) * (bs16 ? bf16_to_f32(bsH[bsg + gi]) : bsF[bsg + gi]);
acc_u = acc_u + (sub_u * sa) * (bs16 ? bf16_to_f32(bsH[bsu + gi]) : bsF[bsu + gi]);
@@ -437,8 +369,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
const bool keep = (i < (uint32_t)n) && (m < (uint32_t)M);
if (keep && Y) Y[(size_t)m * y_ld + i] = h;
/* A column past n, and a row past M, contribute 0.0f: padding takes no part in the amax and
* takes no store, which is quant_act_fp8's rule for a ragged row. */
/* A column past n or a row past M contributes 0.0f to the amax and is not stored, as in
* quant_act_fp8 for a ragged row. */
const float am = keep ? fabsf(bf16_to_f32(h)) : 0.0f;
float mx = wave_max(am); // fmaxf skips a NaN, as `if (m > amax)` does
@@ -449,9 +381,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
for (int w = 1; w < WPG; ++w) mx = fmaxf(mx, s_mx[mloc * WPG + w]);
const float sc = mx > 0.0f ? mx * (1.0f / kTopE4M3) : 1.0f;
/* One store per (row, group): the group's WPG waves all hold the same max, so the first writes
* and the rest stand down. `scale` is dense -- the launcher takes no pitch for it -- so a row is
* `ng` scales and the group index is the block's. */
/* One store per (row, group): the group's WPG waves hold the same max and the first writes it.
* `scale` is dense (the launcher takes no pitch for it): `ng` scales per row, indexed by the
* block's group. */
if (keep && lane == 0 && (wave % WPG) == 0) S[(size_t)m * ng + gidx] = sc;
if (keep) {
@@ -469,19 +401,18 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
* b [N][K] E4M3 codes, row-major, k contiguous: gate rows [0,n), up rows
* [n,N)
* b_scale [ceil(N/group)][ceil(K/group)] bf16 (the op's stated dtype) or f32, block-major
* q [M][n] E4M3 codes, `q_ld` elements a row (0 = n)
* scale [M][ceil(n/group)] f32, DENSE (no pitch is taken)
* out_bf16 [M][n] bf16, `y_ld` elements a row (0 = n), optional: the pre-gate...
* the gated bf16 tensor the codes were taken over
* q [M][n] E4M3 codes, `q_ld` elements per row (0 = n)
* scale [M][ceil(n/group)] f32, dense (no pitch is taken)
* out_bf16 [M][n] bf16, `y_ld` elements per row (0 = n), optional: the gated
* bf16 tensor the codes were taken over
*
* `group` is the weight's K block, the weight's row block and the output quantiser's group at once,
* which is what the op's single key states; 0 takes the checkpoint's 128. `act` is R3D_ACT_SILU
* (down_proj's input) or R3D_ACT_SIGMOID (a gated attention o_proj's). `sk` is accepted as 0/1 and
* refused above it: the epilogue needs a whole row. `nt` selects the weight load's lowering.
* `scratch` is unused -- the op needs no arena, which is what keeps the row concurrent.
* `group` is at once the weight's K block, the weight's row block and the output quantiser's group,
* as the op's single key states; 0 takes the checkpoint's 128. `act` is R3D_ACT_SILU (down_proj's
* input) or R3D_ACT_SIGMOID (a gated attention o_proj's). `sk` is accepted as 0/1 and refused above
* it: the epilogue needs a whole row. `nt` selects the weight load's lowering. `scratch` is unused;
* needing no arena keeps the row concurrent.
*
* Returns 0, -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP
* failed. */
* Returns 0, -1 a null pointer, -2 an unsupported shape, -3 an unreadable pitch, -4 HIP failed. */
extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
@@ -510,14 +441,12 @@ extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale
const int rp = kBlockThreads / group;
const dim3 grid((unsigned)ng, (unsigned)((M + rp - 1) / rp)), blk(kBlockThreads);
/* The skinny arms -- the decode's height -- take the windowed stream; the tall arms keep
* the step. One number, two kernels, and the band key that names them is the same one.
/* fp8a8 at M <= 8 takes the skinny (direct-read) arm, everything else the staged arm.
*
* M <= 8 is the shipped threshold and it is a tunable, not a fact. With the table decoder in both
* arms, N=12288 K=2048 group=128 vram: at M=8 skinny 402 against staged 754, at M=16 skinny 955
* against staged 1030 -- so the crossover is above 16; M=9..15 is unmeasured. Decode lives at M=1
* and a draft's verify at M<=8, which is what the threshold is chosen for; a prefill at 9..16 rows
* would take the skinny arm on the M=16 numbers, for about 7%. */
* The threshold is a tunable chosen for decode (M = 1) and draft verify (M <= 8). With the table
* decoder in both arms, at N=12288 K=2048 group=128 the skinny arm takes 402 us against 754 at
* M = 8 and 955 against 1030 at M = 16, so the crossover lies above 16 (M = 9..15 unmeasured);
* raising the threshold to 16 would gain about 7% for a prefill of 9..16 rows. */
#define R3D_GT_G(G, A, A8, NTV) \
do { \
if (A8 && M <= 8) R3D_GT_W(G, A, A8, NTV, true); \
@@ -546,10 +475,9 @@ extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The declaration in r3d.h carries no scale dtype, and this op's shape hook states bf16 -- the hook
* has no f32 spelling at all -- so the plain entry reads bf16 and the `_ex` twin above carries the
* key. A caller with an f32 scale plane (the `fp8a8f32` reading of the unfused GEMM) lands on `_ex`
* with RAD_F32; the kernel widens bf16 -> f32 exactly, so the two agree to the bit. */
/* The entry without a scale dtype reads bf16, the only form this op's shape hook states. A caller
* with an f32 scale plane (the `fp8a8f32` reading of the unfused GEMM) uses `_ex` with RAD_F32;
* bf16 widens exactly, so the two agree bit for bit. */
extern "C" int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
@@ -562,9 +490,9 @@ extern "C" int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, l
/* ============================================================== the plugin ABI entry point
*
* gemm_nt_q_gated's operands are [a, a_scale, b, b_scale, q, scale, out_bf16?] and its parameters
* M, N, K, group, dtype, act (libref's pGemmQGated/oGemmQGated: `act` REQUIRED, `a_scale` REQUIRED,
* M, N, K, group, dtype, act (libref's pGemmQGated/oGemmQGated: `act` and `a_scale` required,
* `out_bf16` optional). The shape hook declines every scheme but fp8a8, so the row binds fp8a8 and
* the shim reads the coded activation off the operands. */
* the shim reads the coded activation from the operands. */
enum { G_A = 0, G_ASCALE, G_B, G_BSCALE, G_Q, G_SCALE, G_OB };
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
@@ -586,10 +514,9 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
R3D_NEED(dt_e4m3(Q));
R3D_NEED(dt_f32(SC));
if (OB) R3D_NEED(dt_bf16(OB));
/* The activation: E4M3 codes with a per-(row, group) f32 scale (fp8a8, the scheme this op's
* shape hook and every band states), or bf16 with no scale (fp8a16, which the hook declines, so
* no band arrives: the kernel carries the path because the launcher does, and the shim accepts
* it on the operands). E5M2 has no decoder here. */
/* The activation: E4M3 codes with a per-(row, group) f32 scale (fp8a8, the scheme every band
* states), or bf16 with no scale (fp8a16, which the shape hook declines, so no band reaches it;
* the launcher supports it and the shim accepts it). E5M2 has no decoder here. */
const bool a8 = AS != nullptr;
if (a8) {
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
@@ -597,16 +524,14 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
} else {
R3D_NEED(dt_bf16(A));
}
/* b_scale is bf16 -- `o.t(RAD_BF16, {nb, kb})` is this op's own line in the hook, and the
* container's `weight_scale_inv` for the whole quantised family. f32 is accepted because the
* widening is exact and the kernel reads both: the driver's bf16/f32 pair must agree element
* for element. */
/* b_scale is bf16 (the hook's `o.t(RAD_BF16, {nb, kb})`, the container's `weight_scale_inv`).
* f32 is also accepted; the widening is exact, so both give the same output. */
const bool bs16 = r3d_is_bf16(BS);
if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE);
/* `act` is required by the schema (P_STR, not P_STRO): an implementation may compile one gate,
* and an optional parameter would let the row resolve for the other. libref's default is -1 and
* it refuses it; so does this shim, with no `mode` integer spelling to fall back on. */
/* `act` is required by the schema (P_STR, not P_STRO), because an implementation may compile
* only one gate. libref defaults it to -1 and refuses that; so does this shim, with no integer
* `mode` fallback. */
const int act = r3d_act_code(a, "act", nullptr, -1);
if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return R3D_NO(RAD_E_INVAL);
@@ -615,20 +540,18 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
if (K < 1 || N < 2 || (N & 1)) return R3D_NO(RAD_E_SHAPE);
const long long n = N / 2;
/* Rows come from `q`, never from the `M` parameter, which is the band's upper bound. libref
* reads numel(q) / n; on a plane whose pitch exceeds n that counts the padding, so the shape's
* own row count clamps it. A dense plane -- every case the fixture draws -- reads the same
* number either way. */
/* Rows come from `q`, never from the `M` parameter (the band's upper bound). libref reads
* numel(q) / n, which on a plane with pitch > n counts the padding, so the shape's row count
* clamps it. Dense planes give the same number either way. */
const long long qnel = r3d_numel(Q);
if (qnel < n || qnel % n) return R3D_NO(RAD_E_SHAPE);
long long M = qnel / n;
if (Q->rank >= 2 && r3d_dim(Q, (int)Q->rank - 2) < M) M = r3d_dim(Q, (int)Q->rank - 2);
if (M < 1 || M > kMMax) return R3D_NO(RAD_E_SHAPE);
/* The group: the weight's K block, the weight's row block and the quantiser's group, from the
* one key the op states. The reference defaults 0 to `group`-as-stated for the grids and
* `g > n` to n for the quantiser alone; this kernel reads one width, so a group wider than the
* fused width is refused rather than served on a grid the two sides do not share. */
/* The group: the weight's K block, row block and the quantiser's group, from the op's one key.
* The reference would use n for the quantiser alone when group > n; this kernel reads one
* width, so such a group is refused. */
const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK);
if (group < kGroupMin || group > kGroupMax || (group & (group - 1))) return R3D_NO(RAD_E_SHAPE);
if (group > n) return R3D_NO(RAD_E_SHAPE);
@@ -645,14 +568,12 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
const long long q_ld = r3d_rows_pitch(Q, n, &qrows);
const long long y_ld = OB ? r3d_rows_pitch(OB, n, &yrows) : n;
if (a_ld < 0 || q_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
/* `yrows` is only a promise when the plane is there. `r3d_rows_pitch` leaves the count at zero
* for a null operand, and an absent optional output is a null operand by contract (r3d_args.h),
* so testing `yrows` unconditionally reads "the row is missing" from "the caller asked for no
* bf16 mirror". */
/* `yrows` is only meaningful when the plane exists: `r3d_rows_pitch` leaves it zero for a null
* operand, and an absent optional output is a null operand (r3d_args.h). */
if (arows < M || qrows < M || (OB && yrows < M)) return R3D_NO(RAD_E_SHAPE);
if (a_ld % 8) return R3D_NO(RAD_E_STRIDE); // 8-code / 8-element staging
/* The scale planes travel without a pitch argument, so they must be dense, and `scale`'s grid
* must be the one the kernel walks: `ng` scales a row. */
/* The scale planes take no pitch argument, so they must be dense, and `scale` must hold `ng`
* scales per row. */
if (!r3d_contig(B) || !r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE);
if (AS && !r3d_contig(AS)) return R3D_NO(RAD_E_STRIDE);
if (r3d_rows_pitch(SC, ng, &srows) != ng) return R3D_NO(RAD_E_STRIDE);
@@ -663,9 +584,8 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
/* Split-K is the axis this kernel cannot honour: a K slab produces a partial product, and the
* epilogue needs the finished row -- its bf16 narrowing, the gate's partner column, the group's
* amax. A caller that states sk > 1 is refused here, at the row, not answered slowly. */
/* No split-K: the epilogue needs the finished row (its bf16 narrowing, the gate's partner
* column, the group's amax), so sk > 1 is refused. */
if (c.sk > 1) return R3D_NO(RAD_E_SHAPE);
const int e = r3d_gemm_nt_q_gated_ex(