Merge Gemma 4 31B: PRs #74, #75, #81 and #86 (sfjes, keptn42), with fixes

The gemma4_bf16 architecture (sliding and global attention, the proportional RoPE ladder, the
assistant head as a drafter that reads the trunk's cache, the vision tower), its w4a8 decode
junctions, the h512/gqa8 and h256/gqa2 attention kernels, compressed-tensors int4 import, multi-EOS
from generation_config, the call/reasoning reply format, a window group that keeps the keys a
prefill chunk still reads, and window snapshots in checkpoint slots so a prefix hit on a
sliding-window trunk resumes.

Fixes on top: the investigation switches and diagnostic blocks out of the served paths; int4 import
through the checkpoint import framework; attention_k_eq_v from the config; the fused junctions only
where every reader takes their pair; a shared-KV head binds no group of its own; the compose file
without HSA_ENABLE_IPC_MODE_LEGACY (TP2 fails with it on ROCm 10.1); a checkpoint carries a window
only where a hit resumes from it; the README says the linked container is keptn42's calibrated GPTQ
build and what the in-tree recipe gives.
This commit is contained in:
Deadcode committed 2026-10-12 20:46:37 +02:00
84 files changed
+10292 -230

No files matched your search

+10
View File
@@ -57,6 +57,13 @@ set(RAD_W4_GROUP 128 CACHE STRING "libr4d quantised-weight group size (must matc
set(R4D_UNITS
"r4d_attn_paged_h256_gqa6|"
"r4d_attn_paged_h128_gqa4|"
# Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode only
# (prefill falls to the caller's libref path). The windowed twin of the drafter leg above.
"r4d_attn_paged_h256_gqa2|"
# Gemma 4 dense global layers: head_dim 512, 8 queries per KV head, full attention (window 0).
# The head_dim the library had not compiled before -- the prefill KV tile drops to 16 to fit 64
# KiB of LDS, and the decode combine takes the head-generic merge (DPL 16 breaks the vector form).
"r4d_attn_paged_h512_gqa8|"
# Eight queries per KV head, at both head widths: the routed 35B-A3B is 16 over 2 at 256
# and MiniCPM5-2B is 16 over 2 at 128. Same device code, different instantiations.
"r4d_attn_paged_gqa8|"
@@ -134,6 +141,9 @@ set(R4D_UNITS
"r4d_model_bf16|"
"r4d_sample_stages_f32|"
"r4d_quant_act_i8|"
"r4d_rmsnorm_quant_i8|"
"r4d_qkv_norm_rope|"
"r4d_gelu_mul_quant_i8|"
"r4d_had_quant_act_i8|"
"r4d_rmsnorm_had_quant_i8|"
"r4d_ar_ln_had_quant_i8|"
+44 -3
View File
@@ -108,6 +108,24 @@ int r4d_attn_h128_gqa4_have_prefill(void);
// Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache
// dtype: the partials are f16 either way.
long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a);
// The Gemma 4 dense sliding-window geometry: head_dim 256, 2 queries per KV head, sliding window.
// Both bands: the decode band (q_len*gqa <= 64, i.e. q_len <= 32) and the windowed prefill band
// (a prefill-length query, WIN on). The prefill leg is the same r4d_attn_prefill_kernel the
// h256/gqa6 and h512/gqa8 dispatches instantiate, with the window bit turned on.
int r4d_attn_prefill_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a);
// The Gemma 4 dense global geometry: head_dim 512, 8 queries per KV head, full attention (window 0).
// The one head_dim the library had not compiled -- a stand-alone instantiation, not the gqa8
// parameterised body (whose prefill tile of 48 does not fit 512-channel tiles in LDS). Both legs
// spill ~384 VGPRs at this head; a 3b tuning question, not a 3a one.
int r4d_attn_prefill_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h512_gqa8_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h512_gqa8_scratch_bytes(const R4DArgs* a);
// The geometry the attention kernels above are compiled for, so a caller can test a model against
// it instead of discovering the mismatch at the first launch.
void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows);
@@ -784,6 +802,15 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag
long loc_pack, long loc_scale_off);
int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void);
// The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of the
// reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8 GEMM's
// per-row int8 quantiser. Exact wire only; `x` is the message and takes no pitch.
int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long x, long res, long w, long wp,
long sc, int sc_f32, long y, long q, long s, int M, int n, float eps,
float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq);
// ---- sampling ----------------------------------------------------------------------------------
//
// One workgroup a position: temperature, softmax, top_k, top_p, min_p, renormalise and the draw, in
@@ -896,6 +923,11 @@ void r4d_dequant_w4_bf16(long wq, long ws, long out, int N, int K, int group, in
// whole table, an unsliced lookup.
int r4d_embed_lookup_bf16(long tok, long wte, long x, int M, int n_embd, int n_vocab,
int vocab_off, int x_ld, long stream);
// The same lookup with a RUNTIME gather scale on the rows that are found (x = table[id] *
// scale); 1.0 is the plain copy, and a missed row still writes zero rather than zero * scale.
// Gemma 4's embedding is scaled by sqrt(n_embd) at the lookup, not baked into the table.
int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd, int n_vocab,
int vocab_off, int x_ld, float scale, long stream);
int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows,
int x_ld, int y_ld, long stream);
// y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in f32 after
@@ -904,6 +936,9 @@ int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows,
// is -- or bf16. The activation either side is bf16 in both cases.
int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, int w_f32,
int x_ld, int y_ld, long stream);
// y = x * rsqrt(mean(x^2) + eps). The weightless RMS: the same two-pass sum of squares as rmsnorm
// with the gain multiply dropped, gemma's bare value normalisation.
int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, int x_ld, int y_ld, long stream);
// `op` 0 sums, 1 multiplies. A `b_ld` of 0 is the ONE broadcast form: every row reads the same n
// elements, which is what makes a bias add this op rather than a second one.
int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
@@ -913,6 +948,9 @@ int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream);
// y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF -- the order rad-convert
// fuses gate_proj and up_proj in.
int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
// y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF, the tanh
// approximation (gemma's gelu_pytorch_tanh), not the erf one.
int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
// In place over `n_rope_heads` consecutive heads of a row; anything after them (the V heads of a
// fused projection) is untouched. `gptj` 0 pairs i with i + rot/2 (NeoX, and mrope, which is the
// same arithmetic when every position component is equal); 1 pairs 2i with 2i+1. `rot` may be less
@@ -922,9 +960,12 @@ int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int
float theta, float rscale, int row_pitch, long stream);
// The multi-component rotary (docs/OPS.md, `rope`): `mode` 2 mrope, 3 imrope, 4 axial over
// `sec[0..n_sec)`, component c of token m at pos[c * plane + m]. plane 0 is the call above.
int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int gptj,
float theta, float rscale, int row_pitch, int mode, const int* sec, int n_sec,
int plane, long stream);
// `den` is the width the base ladder's exponent divides by: `rot` (the `rotary` ladder, the
// default) or `head_dim` (the `head` ladder, the proportional variant). The `rope` row resolves it
// from its `ladder` param; the plain form above passes `rot`.
int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
int gptj, float theta, float rscale, int row_pitch, int mode, const int* sec,
int n_sec, int plane, long stream);
// C[M,N] f32 = A[M,K] bf16 @ W[N,K]^T bf16, f32 accumulate. THE OUTPUT IS f32 and that is why this
// is not r4d_gemm_bf16_nt_m16 under another name: the engine declares its logits buffer f32,
// because a bf16 logit has eight bits of mantissa and a nucleus cut compares neighbouring
+56
View File
@@ -1246,6 +1246,62 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
/* THE ALL-REDUCE AND THE SANDWICH-NORM JUNCTION AFTER IT, int8 out: `all_reduce` (exact) of `x`, then
* `rmsnorm_quant_i8` -- post-norm of the reduced x, the residual add, the scalar, the norm and the
* per-row int8 quantiser the w4a8 skinny GEMM reads. Operands are rmsnorm_quant_i8's with `x`
* INOUT, because it is the message and the reduced sum lands back in it. The exact wire only: a
* deployment that allows the lossy one keeps the standalone all-reduce. Width and block count as
* ar_rmsnorm_quant_fp8 resolves them, for the same reasons: the norm's width from M, one block a
* row. */
enum { AQ8_X = 0, AQ8_RES, AQ8_W, AQ8_Q, AQ8_S, AQ8_Y, AQ8_WP, AQ8_SC };
extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
if (in->world != 2) return RAD_E_SHAPE;
const RadTensor* x = r4d_opt(a, AQ8_X);
const RadTensor* rs = r4d_opt(a, AQ8_RES);
const RadTensor* w = r4d_opt(a, AQ8_W);
const RadTensor* q = r4d_opt(a, AQ8_Q);
const RadTensor* sc = r4d_opt(a, AQ8_S);
const RadTensor* ob = r4d_opt(a, AQ8_Y);
const RadTensor* wp = r4d_opt(a, AQ8_WP);
const RadTensor* sl = r4d_opt(a, AQ8_SC);
if (!x || !w || !q || !sc) return RAD_E_INVAL;
if ((wp || sl) && !rs) return RAD_E_INVAL;
if (!r4d_contig(w) || (wp && !r4d_contig(wp))) return RAD_E_STRIDE;
if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32) return RAD_E_DTYPE;
long long M = 0, K = 0;
if (r4d_rows_of(x, &M, &K) != RAD_OK) return RAD_E_SHAPE;
if (M * K > in->max_numel) return RAD_E_SHAPE;
if (K % 16) return RAD_E_SHAPE;
if (r4d_numel(w) != K || (w->dtype != RAD_F32 && w->dtype != RAD_BF16)) return RAD_E_DTYPE;
if (wp && (r4d_numel(wp) != K || wp->dtype != w->dtype)) return RAD_E_SHAPE;
if (sl && (r4d_numel(sl) != 1 || (sl->dtype != RAD_F32 && sl->dtype != RAD_BF16))) return RAD_E_SHAPE;
if (r4d_numel(q) != M * K || !r4d_contig(q)) return RAD_E_SHAPE;
if (r4d_numel(sc) != M || !r4d_contig(sc)) return RAD_E_SHAPE;
if (ob && r4d_numel(ob) != M * K) return RAD_E_SHAPE;
if (rs && r4d_numel(rs) != M * K) return RAD_E_SHAPE;
const long long xp = r4d_row_pitch(x), yp = ob ? r4d_row_pitch(ob) : 0, rp = rs ? r4d_row_pitch(rs) : 0;
if (xp != K || yp < 0 || rp < 0) return RAD_E_STRIDE; /* x is the message: tight */
if (r4d_geti_or(a, "wire", 0) != 0) return RAD_E_INVAL;
R4dArCfg cfgv;
r4d_cfg_ar(a, &cfgv);
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : (int)M;
if (nblocks > (int)M) nblocks = (int)M;
if (nblocks > 256) nblocks = 256;
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
if (nblocks < 1) nblocks = 1;
const int e = r4d_ar_rmsnorm_quant_i8(
in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq,
in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(wp), r4d_addr(sl),
sl ? (sl->dtype == RAD_F32) : 0, r4d_addr(ob), r4d_addr(q), r4d_addr(sc), (int)M, (int)K,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), w->dtype == RAD_F32,
(int)rp, (int)yp, (long)(uintptr_t)s, nblocks, cfgv.drain, cfgv.acq);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
/* THE ALL-REDUCE WITH THE GATED RESIDUAL'S WRITE IN IT: `all_reduce` of `y` and then `hc_write`
* of the reduced `y` into `h`, one kernel. A block whose output feeds a hyper-connection write
* skips its own collective when this runs, and the write carries it.
+174
View File
@@ -0,0 +1,174 @@
// R4D attention dispatch for the Gemma 4 dense model's sliding-window geometry: head_dim 256,
// 2 queries per KV head, paged block 16, and a SLIDING WINDOW (window 1024 in the model, 50 of its
// 60 layers). It is the same device code as the 27B target's h256/gqa6 dispatch -- the kernels are
// templates on head_dim and gqa, so this file is another set of instantiations, not a second
// kernel -- with the window bit (template arg WIN) turned on, the way the DFlash2 drafter leg does
// it at head_dim 128.
//
// Both bands, now. The decode band (q_len * gqa <= 64, i.e. q_len <= 32 at gqa 2) is the
// windowed decode kernel above. The prefill band (a query long enough to want the query-tiled
// prefill kernel) is the windowed prefill kernel below -- the same r4d_attn_prefill_kernel the
// h256/gqa6 and h512/gqa8 dispatches instantiate, with the window bit (template arg WIN) turned on,
// the way the decode leg does. A trunk layer prefills, so it needs the prefill band on the device:
// libref is an opt-in fallback the engine refuses by default (spec §17). The drafter leg is
// decode-only because a drafter never prefills.
#include "r4d.h"
#include "r4d_attn_args.h"
#include "r4d_common.h"
#include <cmath>
#include <algorithm>
using std::max;
// The decode and prefill kernels share their query conversion and fragment helpers, so the prefill
// header comes first here for the same reason it does in the h256 dispatch. This translation unit
// instantiates BOTH r4d_attn_prefill_kernel (below, WIN=1) and the windowed decode kernel.
#include "r4d_attn_prefill_h256_gqa6.hip"
#include "r4d_attn_decode_h256_gqa6.hip"
#define CHK4() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
#define B_HEAD_DIM 256
#define B_GQA 2
#define B_BLOCK_SIZE 16
#define B_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold
#define B_TILE 16
// The same option set the h256 decode kernel ships, K prefetch of 2 included. At head_dim 256 it
// is the same register picture gqa6 has (256 VGPRs with a small spill), so this is a correctness
// instantiation here -- the register count is a 3b tuning question, not a 3a one. The window bit
// is already in the template; this file only turns it on.
#define B_OPT 3429947
#ifndef B_JPB
#define B_JPB 2
#endif
#ifndef B_VECMIN
#define B_VECMIN 256
#endif
// Split law, the drafter leg's with the same window-aware term. It aims at 192 workgroups, snaps
// DOWN to a power of two but never below 16, clamps to at least two tiles a segment, and then steps
// UP off the exact grid size `splits * units == 256`, a pothole in this geometry's timing.
//
// THE WINDOW-AWARE TERM is the one thing it does that the h256 full-attention law does not: under a
// sliding window the context the kernel actually walks is the window, not the sequence, so the tile
// count that feeds the machine-fill target and the thin-segment clamp comes from the window.
// Without that the law reads a 16K sequence and asks for segments two tiles deep off a 1024-token
// walk.
static int decode_splits_h256_gqa2(const R4DArgs* a) {
if (a->splits > 0) return a->splits;
const int span = (a->window > 0 && a->window + a->q_len < a->max_ctx)
? a->window + a->q_len : a->max_ctx;
const int tiles = (span + B_TILE - 1) / B_TILE;
const int units = std::max(1, a->kv_heads * a->num_seqs);
const int raw = 192 / units;
int s = 128;
while (s > 16 && s > raw) s >>= 1;
const int cap = tiles / 2;
while (s > 16 && s > cap) s >>= 1;
if (s > tiles) s = tiles;
if (s < 1) s = 1;
if (s * units == 256 && s * 2 <= tiles) s <<= 1; // step off the pothole, see above
return s;
}
extern "C" long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a) {
const int splits = decode_splits_h256_gqa2(a);
const long rows = (long)r4d_q_total(*a) * a->q_heads;
return (B_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8)
: rows * splits * (long)(a->head_dim + 2) * 4L;
}
template <int KVP>
static int decode_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != B_GQA) return -2;
const int rows = a->q_len * B_GQA;
if (rows > B_MAX_DECODE_ROWS) return -4;
const int nw = (rows + 15) / 16;
const int splits = decode_splits_h256_gqa2(a);
#define B_LAUNCH(NW) \
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, B_TILE, B_HEAD_DIM, B_GQA, B_BLOCK_SIZE, \
KVP, B_OPT, 1>), \
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
if (nw == 1) B_LAUNCH(1);
else if (nw == 2) B_LAUNCH(2);
else if (nw == 3) B_LAUNCH(3);
else B_LAUNCH(4);
#undef B_LAUNCH
CHK4();
// Same two merge forms, and the same rule for choosing between them, as the h256 dispatch:
// a wave a row while there are enough rows to fill the part and the segment count fits a
// wave, the general LDS-tree form otherwise. Both produce the same bytes, and both carry the
// window bit here (the final template argument) for the same reason the decode kernel does.
const int jobs3 = r4d_q_total(*a) * a->q_heads;
if (splits <= 64 && jobs3 >= B_VECMIN) {
const int blocks = (jobs3 + B_JPB - 1) / B_JPB;
if (B_OPT & 32)
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<B_HEAD_DIM, 4, 1, B_JPB, 1>),
dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE);
else
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<B_HEAD_DIM, 4, 0, B_JPB, 1>),
dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE);
} else if (B_OPT & 32)
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<B_HEAD_DIM, 4, 1, 1>), dim3(jobs3),
dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE);
else
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<B_HEAD_DIM, 4, 0, 1>), dim3(jobs3),
dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE);
CHK4();
return 0;
}
extern "C" int r4d_attn_decode_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) {
return decode_launch_h256_gqa2<0>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) {
return decode_launch_h256_gqa2<1>(a, s);
}
// ---- prefill ---------------------------------------------------------------------------------
// The h256/gqa6 prefill option set (P_OPT 3955211) is reused unchanged: at head_dim 256 the wide K
// fetch (O_KWIDE) is valid -- it is written for 16 channels = head_dim 256 exactly -- so unlike the
// h512 leg (which turns it off because 512 reads past the tile) this one keeps it. gqa 2 makes
// BLOCK_Q (NWARPS*16/2 = 192) larger than gqa 6's 64, so a workgroup covers more query positions:
// fewer grid.x blocks, the same KV tile. WIN is on (the last template arg); window <= 0 folds it
// away to the full-attention form, so a windowless launch is safe.
#define P_NWARPS 24
#define P_TILE 48
#define P_OPT 3955211
template <int KVP>
static int prefill_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != B_GQA) return -2;
constexpr int BQ = (P_NWARPS * 16) / B_GQA;
dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs);
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, B_HEAD_DIM, B_GQA,
B_BLOCK_SIZE, KVP, P_OPT, 1>),
grid, dim3(P_NWARPS * 32), 0, s, *a);
CHK4();
return 0;
}
extern "C" int r4d_attn_prefill_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h256_gqa2<0>(a, s);
}
extern "C" int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch_h256_gqa2<1>(a, s);
}
/* The prefill RadArgs wrappers, defined here (not in the h256 dispatch) for the same reason the
* h512 leg's live in theirs: an entry point appended to a textual inclusion compiles into nothing.
* Absent descales mean 1.0 (fill_paged leaves them null and the kernel reads 1.0). */
extern "C" int r4d_rad_attn_prefill_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = fill_paged(a, &r, B_HEAD_DIM);
if (rc != RAD_OK) return rc;
return r4d_attn_prefill_h256_gqa2_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_prefill_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = fill_paged(a, &r, B_HEAD_DIM);
if (rc != RAD_OK) return rc;
return r4d_attn_prefill_h256_gqa2_bf16kv(&r, (hipStream_t)s);
}
+35 -6
View File
@@ -254,6 +254,15 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) {
* step off its pothole doubles the splits at one count and not at the next. A step may carry any
* count up to the bound, so the region is the largest over all of them. The laws are closed forms
* and this runs at declare, so the sweep costs nothing a step. */
// One hook per geometry but one shared (seqs x heads x rows) partial layout, so the worst-over-
// the-batch sweep below asks each geometry its own bytes in one place instead of triplicating the
// sweep. which: 0 = h256/gqa6, 1 = h128/gqa4, 2 = h256/gqa2 (the Gemma 4 windowed leg).
static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) {
if (which == 1) return (int64_t)r4d_attn_decode_h128_gqa4_scratch_bytes(r);
if (which == 2) return (int64_t)r4d_attn_decode_h256_gqa2_scratch_bytes(r);
return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r);
}
static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
@@ -278,8 +287,7 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) {
int64_t worst = 0;
for (long long n = 1; n <= max_seqs; ++n) {
r.num_seqs = (int)n;
const int64_t need = which == 0 ? r4d_attn_decode_h256_gqa6_scratch_bytes(&r)
: r4d_attn_decode_h128_gqa4_scratch_bytes(&r);
const int64_t need = decode_scratch_bytes_of(&r, which);
if (need > worst) worst = need;
}
return worst;
@@ -288,8 +296,7 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) {
int rc = fill_paged(a, &r, head_dim);
if (rc != RAD_OK) return rc;
r.splits = sp;
return which == 0 ? r4d_attn_decode_h256_gqa6_scratch_bytes(&r)
: r4d_attn_decode_h128_gqa4_scratch_bytes(&r);
return decode_scratch_bytes_of(&r, which);
}
extern "C" int64_t r4d_rad_attn_decode_h256_scratch(const RadArgs* a) {
@@ -306,8 +313,7 @@ static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which)
int rc = fill_paged(a, r, head_dim);
if (rc != RAD_OK) return rc;
r->splits = sp;
const int64_t need = (which == 0) ? r4d_attn_decode_h256_gqa6_scratch_bytes(r)
: r4d_attn_decode_h128_gqa4_scratch_bytes(r);
const int64_t need = decode_scratch_bytes_of(r, which);
if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH);
return RAD_OK;
}
@@ -343,3 +349,26 @@ extern "C" int r4d_rad_attn_decode_h128_bf16(const RadArgs* a, RadStream s) {
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa4_bf16kv(&r, (hipStream_t)s);
}
/* Gemma 4 dense sliding window -- head_dim 256, 2 queries per KV head, window 1024. Decode only;
* a prefill step does not match the row's q_len band and takes the caller's (windowed) fallback.
* Same shape as the drafter leg above (h128): one `which` routing to the gqa2 scratch law and the
* gqa2 decode launch, no check_dims_once because this is not the geometry that reports dims. */
extern "C" int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 2);
}
extern "C" int r4d_rad_attn_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2);
if (rc != RAD_OK) return rc;
/* Absent descales mean 1.0; see the prefill twin above. */
return r4d_attn_decode_h256_gqa2_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_bf16kv(&r, (hipStream_t)s);
}
+212
View File
@@ -0,0 +1,212 @@
// R4D attention dispatch for the Gemma 4 dense model's GLOBAL layers: head_dim 512, 8 queries per
// KV head, full attention (window 0), paged block 16. This is the one head_dim the library has not
// compiled before -- no h512 kernel existed -- so this file is a real new instantiation, not a
// rename. It is the same device code as the h256/gqa6 and gqa8 dispatches (the kernels are
// templates on head_dim and gqa), with the two changes head_dim 512 forces:
//
// PREFILL -- TILE 16, not 48. The 16-bit K+V tiles are sK[TILE*(512+8)] + sV16[512*(TILE+8)];
// at TILE 48 that is 107264 B, past the 64 KiB of LDS the part has, and only TILE 16 clears it
// (41216 B). The prefill warps tile the QUERY dimension (BLOCK_Q = NWARPS*16/gqa) and loop the
// KV in TILE chunks, so shrinking the KV tile costs loop iterations, not a different tiling.
// `O_KWIDE` is off -- its thread-to-(key,channel) map is written for 16 channels, head_dim 256
// exactly, and at 512 it would read past the tile; the h128 prefill runs the same set minus it,
// so the non-wide path is already a shipped, correct one.
//
// DECODE -- the split-KV combine is the HEAD-GENERIC plain form (one thread per channel, a block
// of head_dim threads), not the vectorised form: that one pins a lane's width to eight or four
// dwords, and head_dim 512 would give it sixteen and refuse to compile. The plain form is slower
// but merges off the decode critical path; the trade is a 3b question.
//
// Register pressure at head_dim 512 is the one thing this file does not fix -- a thread carries
// head_dim/16 query fragments plus head_dim/8 accumulator floats, ~384 VGPRs, which the part tops
// out at, so both legs spill. That is correct and a tuning (3b) question, not a 3a one.
#include "r4d.h"
#include "r4d_attn_args.h"
#include "r4d_common.h"
#include <cmath>
#include <algorithm>
using std::max;
#include "r4d_attn_prefill_h256_gqa6.hip"
#include "r4d_attn_decode_h256_gqa6.hip"
#define CHK5() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0)
#define H5_HEAD_DIM 512
#define H5_GQA 8
#define H5_BLOCK_SIZE 16
#define H5_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold: q_len <= 8
// The h256 prefill option set (3955211) minus O_KWIDE -- the only head-512 option change; the h128
// prefill ships this exact number.
#define H5_P_NWARPS 24
#define H5_P_TILE 16 // the KV tile that fits 64 KiB LDS at head_dim 512 (see above)
#define H5_P_OPT 3430923
#define H5_D_TILE 16
#define H5_D_OPT 3429947 // the shared decode opt set; bit 32 (f16 partials) is set
#define H5_D_JPB 2
#define H5_D_VECMIN 256
// ---- prefill -----------------------------------------------------------------------------------
template <int KVP>
static int h5_prefill_launch(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != H5_HEAD_DIM || a->block_size != H5_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != H5_GQA) return -2;
constexpr int BQ = (H5_P_NWARPS * 16) / H5_GQA;
dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs);
hipLaunchKernelGGL((r4d_attn_prefill_kernel<H5_P_NWARPS, H5_P_TILE, H5_HEAD_DIM, H5_GQA,
H5_BLOCK_SIZE, KVP, H5_P_OPT>),
grid, dim3(H5_P_NWARPS * 32), 0, s, *a);
CHK5();
return 0;
}
extern "C" int r4d_attn_prefill_h512_gqa8_fp8kv(const R4DArgs* a, hipStream_t s) {
return h5_prefill_launch<0>(a, s);
}
extern "C" int r4d_attn_prefill_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t s) {
return h5_prefill_launch<1>(a, s);
}
// ---- decode ------------------------------------------------------------------------------------
// The h256 full-attention split law: as many workgroups as fit under 128, at least two tiles a
// segment. It reads kv_heads, num_seqs and max_ctx and nothing about gqa or head_dim, so there is
// nothing to re-derive for this geometry; a window does not exist at full attention.
static int h5_decode_splits(const R4DArgs* a) {
if (a->splits > 0) return a->splits;
const int tiles = (a->max_ctx + H5_D_TILE - 1) / H5_D_TILE;
const int units = max(1, a->kv_heads * a->num_seqs);
int s = 128 / units;
const int cap = tiles / 2;
if (s > cap) s = cap;
if (s > tiles) s = tiles;
if (s < 1) s = 1;
return s;
}
extern "C" long r4d_attn_decode_h512_gqa8_scratch_bytes(const R4DArgs* a) {
const int splits = h5_decode_splits(a);
const long rows = (long)r4d_q_total(*a) * a->q_heads;
return (H5_D_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8)
: rows * splits * (long)(a->head_dim + 2) * 4L;
}
template <int KVP>
static int h5_decode_launch(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != H5_HEAD_DIM || a->block_size != H5_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != H5_GQA) return -2;
const int rows = a->q_len * H5_GQA;
if (rows > H5_MAX_DECODE_ROWS) return -4;
const int nw = (rows + 15) / 16;
const int splits = h5_decode_splits(a);
#define H5_LAUNCH(NW) \
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, H5_D_TILE, H5_HEAD_DIM, H5_GQA, \
H5_BLOCK_SIZE, KVP, H5_D_OPT>), \
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
if (nw == 1) H5_LAUNCH(1);
else if (nw == 2) H5_LAUNCH(2);
else if (nw == 3) H5_LAUNCH(3);
else H5_LAUNCH(4);
#undef H5_LAUNCH
CHK5();
// The head-generic plain combine, always: a single thread per channel, one block of head_dim
// threads, no DPL to trip on at 512. H5_D_OPT carries bit 32 (f16 partials), so it reads them
// as such; the f32 half is spelled for the same guard the other dispatches use, not expected.
const int jobs3 = r4d_q_total(*a) * a->q_heads;
if (H5_D_OPT & 32)
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<H5_HEAD_DIM, 4, 1>), dim3(jobs3),
dim3(H5_HEAD_DIM), splits * sizeof(float), s, *a, splits, H5_D_TILE);
else
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<H5_HEAD_DIM, 4, 0>), dim3(jobs3),
dim3(H5_HEAD_DIM), splits * sizeof(float), s, *a, splits, H5_D_TILE);
CHK5();
return 0;
}
extern "C" int r4d_attn_decode_h512_gqa8_fp8kv(const R4DArgs* a, hipStream_t s) {
return h5_decode_launch<0>(a, s);
}
extern "C" int r4d_attn_decode_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t s) {
return h5_decode_launch<1>(a, s);
}
// ============================================================== the plugin ABI entry points
// Defined here, in this translation unit, for the same reason the h128 drafter's live in theirs:
// the prefill and decode headers are textual inclusions, and an entry point appended to either
// compiles into nothing, leaving the .so with an undefined symbol only r4d_selftest would catch.
extern "C" int r4d_rad_attn_prefill_h512_gqa8_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = fill_paged(a, &r, 512);
if (rc != RAD_OK) return rc;
/* Absent descales mean 1.0; see the prefill twins in the h256 dispatch. */
return r4d_attn_prefill_h512_gqa8_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_prefill_h512_gqa8_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = fill_paged(a, &r, 512);
if (rc != RAD_OK) return rc;
return r4d_attn_prefill_h512_gqa8_bf16kv(&r, (hipStream_t)s);
}
/* The split-KV partial buffer, sized at declare from the batch's worst step, the way the other
* decode geometries do it. The h256 split law makes splits * num_seqs flat, but its clamp to
* `>= 2 tiles a segment` breaks that at large batches, so the sweep over every count to the bound
* is still the right size even at full attention. */
extern "C" int64_t r4d_rad_attn_decode_h512_gqa8_scratch(const RadArgs* a) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
R4DArgs r;
const long long n_head = r4d_geti_or(a, "n_head", 0);
const long long max_seqs = r4d_geti_or(a, "max_seqs", 0);
if (n_head > 0 && max_seqs > 0) {
std::memset(&r, 0, sizeof(r));
r.head_dim = H5_HEAD_DIM;
r.q_heads = (int)n_head;
r.kv_heads = (int)(n_head / H5_GQA);
r.num_seqs = (int)max_seqs;
r.q_len = (int)r4d_geti_or(a, "q_len", 1);
r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0);
r.block_size = (int)r4d_geti_or(a, "block_size", 16);
r.splits = sp;
if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL);
int64_t worst = 0;
for (long long n = 1; n <= max_seqs; ++n) {
r.num_seqs = (int)n;
const int64_t need = r4d_attn_decode_h512_gqa8_scratch_bytes(&r);
if (need > worst) worst = need;
}
return worst;
}
int rc = fill_paged(a, &r, H5_HEAD_DIM);
if (rc != RAD_OK) return rc;
r.splits = sp;
return r4d_attn_decode_h512_gqa8_scratch_bytes(&r);
}
static int h5_decode_common(const RadArgs* a, R4DArgs* r, int which) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
int rc = fill_paged(a, r, H5_HEAD_DIM);
if (rc != RAD_OK) return rc;
r->splits = sp;
const int64_t need = r4d_attn_decode_h512_gqa8_scratch_bytes(r);
if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH);
return RAD_OK;
}
extern "C" int r4d_rad_attn_decode_h512_gqa8_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = h5_decode_common(a, &r, 0);
if (rc != RAD_OK) return rc;
/* Absent descales mean 1.0; see the prefill twin above. */
return r4d_attn_decode_h512_gqa8_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_decode_h512_gqa8_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = h5_decode_common(a, &r, 1);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h512_gqa8_bf16kv(&r, (hipStream_t)s);
}
+26 -6
View File
@@ -76,7 +76,12 @@ __device__ __forceinline__ uint32_t r4d_qcvt(uint32_t w, float s) {
__builtin_bit_cast(float, w & 0xffff0000u) * s);
}
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT>
// WIN turns on a sliding window (a.window positions, ending at each row's causal limit), the way
// the decode kernel's WIN does. The window's lower bound masks the keys before it, and the KV walk
// starts at the tile holding the window's first token (taken at query row 0, whose window reaches
// furthest back) so the tiles no row can reach are never walked. window <= 0 (or WIN off) is the
// full-attention form, unchanged.
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT, int WIN = 0>
__global__ __launch_bounds__(NWARPS * 32)
void r4d_attn_prefill_kernel(const R4DArgs a)
{
@@ -159,6 +164,11 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
}
const int klimit = ctx - qlen + qpos;
// The window's first key this row may attend to: the causal limit back by the window, floored
// at zero. The decode kernel's r4d_attn_wlo is the same formula, inlined here because the
// prefill header is compiled before the decode one that defines it.
int wlo = (WIN && a.window > 0) ? (ctx - qlen + qpos - a.window + 1) : 0;
if (WIN && a.window > 0 && wlo < 0) wlo = 0;
float m_ref = -3.0e38f;
float off = PSHIFT + 3.0e38f;
@@ -170,6 +180,13 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
const int qmax_cta = min(qb * BLOCK_Q + BLOCK_Q - 1, qlen - 1);
const int klimit_cta = ctx - qlen + qmax_cta;
const int ntiles = (min(klimit_cta + 1, ctx) + TILE - 1) / TILE;
// The window's first tile, taken at THIS CTA's first query row (whose window reaches furthest
// back among the rows it holds); the walk starts there, so no tile below every row's window is
// fetched. Taken at the CHUNK's row 0 instead, the last CTA of an 8192-token chunk walked eight
// thousand keys none of its rows can see -- fully masked tiles, so skipping them changes no
// value. WIN off (or window <= 0) starts at 0.
const int wlo0 = (WIN && a.window > 0) ? (ctx - qlen + qb * BLOCK_Q - a.window + 1) : 0;
const int tstart = (WIN && a.window > 0 && wlo0 > 0) ? (wlo0 / TILE) : 0;
// ---- staging, split into a global FETCH (registers) and an LDS STORE ------------------------
// Splitting them is what lets GPREV move the fetch out from between the barriers; without
@@ -302,10 +319,10 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
}
};
int blk[NB];
if (BTS) load_bt(0, blk);
if (GPREV) fetchV(0, blk);
if (BTS) load_bt(tstart * NB, blk);
if (GPREV) fetchV(tstart * TILE, blk);
for (int ti = 0; ti < ntiles; ++ti) {
for (int ti = tstart; ti < ntiles; ++ti) {
const int k0 = ti * TILE;
int blkn[NB];
if (BTS && ti + 1 < ntiles) {
@@ -352,9 +369,12 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul;
const int kbase = k0 + mt * 16 + 8 * h;
if (!MSKIP || wave_any(kbase + 7 > klimit)) {
// The causal bound masks the keys past klimit; the window bound (WIN) also masks the
// keys before wlo. MSKIP skips both when an m-tile straddles neither limit.
if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo))) {
#pragma unroll
for (int e = 0; e < 8; ++e) sc[e] = (kbase + e <= klimit) ? sc[e] : -INFINITY;
for (int e = 0; e < 8; ++e) sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo))
? sc[e] : -INFINITY;
}
float smax = sc[0];
+72 -4
View File
@@ -217,6 +217,61 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel(
}
}
// The `blocks` mode at any head_dim and section size (Gemma 4's vision tower: 72-wide heads, two
// sections of 18 pairs) -- what the register layout above cannot hold. A wave a head and a lane a
// rotated pair: the norm's sum of squares first, then each lane re-reads its pair, norms, gains,
// rounds (the norm rounded before the rotation, as above) and rotates it. Channels past `rot`
// are normed only; a v head (v_norm) is normed at unit gain.
__global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel(
uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw,
const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv,
uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld,
QkBlocks blk, uint32_t pplane) {
__shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf];
__shared__ int pa_s[kQkMaxHalf], pb_s[kQkMaxHalf];
const uint32_t m = blockIdx.x;
const uint32_t n_rope = n_head + n_head_kv;
const uint32_t n_norm = n_rope + (v_norm ? n_head_kv : 0);
const uint32_t half = rot / 2;
uint16_t* row = qkv + (size_t)m * ld;
const float div = rscale != 0.0f ? rscale : 1.0f;
for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) {
int c = 0, s0 = 0;
while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; }
const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div;
const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]);
sincosf(p * inv, &sn_s[i], &cs_s[i]);
pa_s[i] = 2 * s0 + ((int)i - s0);
pb_s[i] = pa_s[i] + blk.sec[c];
}
__syncthreads();
const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
for (uint32_t hh = wave; hh < n_norm; hh += kQkThreads / 32) {
uint16_t* h = row + hh * head_dim;
float ss = 0.0f;
for (uint32_t e = lane; e < head_dim; e += 32) { const float v = bf2f(h[e]); ss += v * v; }
ss = r4d_wave_sum(ss);
const float sc = 1.0f / sqrtf(ss / (float)head_dim + eps);
const bool is_v = hh >= n_rope;
const uint16_t* w = hh < n_head ? qw : kw;
auto nrm = [&](uint32_t e) {
const float g = is_v ? 1.0f : bf2f(w[e]) + wadd;
return bf2f(f32_to_bf16(bf2f(h[e]) * sc * g));
};
if (is_v) {
for (uint32_t e = lane; e < head_dim; e += 32) h[e] = f32_to_bf16(nrm(e));
continue;
}
for (uint32_t i = lane; i < half; i += 32) {
const uint32_t a = (uint32_t)pa_s[i], b = (uint32_t)pb_s[i];
const float x0 = nrm(a), x1 = nrm(b);
h[a] = f32_to_bf16(x0 * cs_s[i] - x1 * sn_s[i]);
h[b] = f32_to_bf16(x0 * sn_s[i] + x1 * cs_s[i]);
}
for (uint32_t e = rot + lane; e < head_dim; e += 32) h[e] = f32_to_bf16(nrm(e));
}
}
// ---------------------------------------------------------------------------- pool_rows
// ref_pool_rows: row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to
// bf16, then times `mult` and rounded again. A workgroup an output row, a thread a column.
@@ -541,21 +596,32 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M
const QkBlocks* blk, int pplane, long stream) {
if (!qkv || !pos || !qw || !kw) return -1;
if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot <= 0 || rot > head_dim ||
(rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || head_dim % 32 ||
mode < 0 || mode > 2)
(rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 2)
return -2;
if (mode != 2 && head_dim % 32) return -2;
if (mode == 1 && head_dim % 64) return -2;
if (mode == 0 && (rot / 2) % 32) return -2;
QkBlocks b{};
bool any = false; /* the blocks mode outside the register layout: qk_norm_rope_any_kernel */
if (mode == 2) {
if (!blk || blk->n <= 0 || blk->n > 8) return -2;
b = *blk;
int total = 0;
for (int c = 0; c < b.n; ++c) {
if ((2 * total) % 32 || (b.sec[c] != 16 && b.sec[c] % 32)) return -2;
if (b.sec[c] <= 0) return -2;
if ((2 * total) % 32 || (b.sec[c] != 16 && b.sec[c] % 32)) any = true;
total += b.sec[c];
}
if (2 * total != rot) return -2;
if (head_dim % 32) any = true;
}
if (any) {
hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0,
(hipStream_t)stream, (uint16_t*)qkv, (const int*)pos,
(const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim,
(uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta,
eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
#define R4D_QN(MD) \
hipLaunchKernelGGL(qk_norm_rope_kernel<MD>, dim3((uint32_t)M), dim3(kQkThreads), 0, \
@@ -766,12 +832,14 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) {
return R4D_NO(RAD_E_SHAPE);
/* A head lives in a wave's registers with both halves of a rotary pair in one lane (or, for a
* 16-pair block, in the two half-waves): head_dim a multiple of 32 up to 1024. */
if (hd % 32 || hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
if (hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
const char* mode = r4d_gets(a, "mode");
int md = 0;
if (mode && !std::strcmp(mode, "gptj")) md = 1;
else if (mode && !std::strcmp(mode, "blocks")) md = 2;
else if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED);
/* Any head_dim in the blocks mode (qk_norm_rope_any_kernel); the others need multiples of 32. */
if (md != 2 && hd % 32) return R4D_NO(RAD_E_SHAPE);
QkBlocks blk{};
long long M = 0, pplane = 0;
if (md == 2) {
+96
View File
@@ -0,0 +1,96 @@
// r4d_gelu_mul_quant_i8.hip - r4d_gelu_mul_quant_i8: gelu(gate) * up and the per-row int8 quantiser
// r4d_gemm_w4a8_nt_m64 reads, in one pass over the row.
//
// The down projection's input of a GELU-gated feed-forward (Gemma) on a w4a8 grid: unfused it is
// gelu_mul and quant_act_i8, two single-row dispatches at a decode batch. This is the pair as one,
// BYTE-IDENTICAL to it: the product is formed exactly as gelu_mul_kernel forms it (the tanh form,
// the same constants, rounded to bf16), and the absmax, scale and codes are quant_act_i8's over
// those bf16 values -- the absmax is a max and so takes no partition, and every code is a function
// of its own value and the row scale.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include <cstdint>
namespace {
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
template <uint32_t THR>
__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
extern __shared__ uint16_t ybuf[];
__shared__ float lm[THR / 32];
const uint32_t row = blockIdx.x;
const uint16_t* __restrict__ gr = gu + (size_t)row * gu_ld;
signed char* __restrict__ qr = q + (size_t)row * n;
float m = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const float g = bf2f(gr[i]);
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g)));
const uint16_t y = f32_to_bf16(gelu * bf2f(gr[n + i]));
ybuf[i] = y;
if (yo) yo[(size_t)row * y_ld + i] = y;
m = fmaxf(m, fabsf(bf2f(y)));
}
m = r4d_wave_max(m);
if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m;
__syncthreads(); // also publishes ybuf to every thread
m = lm[0];
#pragma unroll
for (uint32_t i = 1; i < THR / 32; i++) m = fmaxf(m, lm[i]);
const float scale = fmaxf(m, 1e-8f) / 127.f;
const float inv = 1.f / scale;
if (threadIdx.x == 0) S[row] = scale;
// quant_act_i8's fragment order, see r4d_quant_act_i8.hip
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint32_t s = i >> 4, j = i & 15;
const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
const int t = __float2int_rn(bf2f(ybuf[src]) * inv);
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
}
} // namespace
// Operands (r4d_rows.cpp, oGeluMulQuantI8): gate_up [M][2n] bf16 (gate first), q [M][n] int8 in the
// fragment order, scale [M][1] f32, out_bf16 [M][n] bf16 optional.
enum { GM_GU = 0, GM_Q, GM_S, GM_Y };
static int rad_gelu_mul_quant_i8_body(const RadArgs* a, const R4dSink& sk) {
int emit_rc = RAD_OK;
const RadTensor* gu = r4d_opt(a, GM_GU);
const RadTensor* q = r4d_opt(a, GM_Q);
const RadTensor* s = r4d_opt(a, GM_S);
const RadTensor* y = r4d_opt(a, GM_Y);
if (!gu || !q || !s) return R4D_NO(RAD_E_INVAL);
if (gu->dtype != RAD_BF16 || q->dtype != RAD_I8 || s->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
long long M = 0, n = 0;
if (r4d_rows_of(q, &M, &n) != RAD_OK) return R4D_NO(RAD_E_SHAPE);
if (n % 16 || !r4d_contig(q)) return R4D_NO(RAD_E_SHAPE);
long long Mg = 0;
const long long gp = r4d_rows_pitch(gu, 2 * n, &Mg);
if (gp < 0) return R4D_NO(RAD_E_STRIDE);
if (Mg < M) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(s) != M || !r4d_contig(s)) return R4D_NO(RAD_E_SHAPE);
if (y && r4d_numel(y) != M * n) return R4D_NO(RAD_E_SHAPE);
const long long yp = y ? r4d_row_pitch(y) : n;
if (yp < 0) return R4D_NO(RAD_E_STRIDE);
const size_t lds = (size_t)n * sizeof(uint16_t);
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
const int thr = r4d_act_threads((int)M, (int)n);
#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(sk, (gelu_mul_quant_i8_kernel<T>), dim3((uint32_t)M), dim3(T), lds, \
(const uint16_t*)r4d_p(gu), (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), \
(uint32_t)n, (uint32_t)gp, (uint32_t)yp)
if (thr == 1024) R4D_GMQ_T(1024);
else if (thr == 512) R4D_GMQ_T(512);
else if (thr == 256) R4D_GMQ_T(256);
else return R4D_NO(RAD_E_INVAL);
#undef R4D_GMQ_T
return emit_rc;
}
R4D_ENTRY(r4d_rad_gelu_mul_quant_i8, rad_gelu_mul_quant_i8_body)
+332 -16
View File
@@ -49,6 +49,7 @@
#include "r4d_fp8_wmma.h"
#include <cstdlib>
#include <cstring>
namespace {
@@ -273,6 +274,29 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
}
}
// ---------------------------------------------------------------------------- rmsnorm_p
// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain.
// It is the weightless value normalisation Gemma's attention uses on V (llama.cpp's
// ggml_rms_norm(V, eps), no tensor); there is no checkpoint plane to feed a gain through, so an
// rmsnorm call would need a phantom all-zero weight. Two passes over the row, the sum of squares
// in f32; the second pass drops the gain multiply rmsnorm has. The mean accumulates in f32 in
// ascending index order, exactly as rmsnorm does, so the two agree bit-for-bit where rmsnorm's
// gain happens to be one.
__global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) {
__shared__ float lds[kThreads / kWave];
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) { const float v = bf2f(xr[i]); ss += v * v; }
ss = block_sum<kThreads / kWave>(ss, lds);
const float s = rsqrtf(ss / (float)n + eps);
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = f32_to_bf16(bf2f(xr[i]) * s);
}
// ---------------------------------------------------------------------------- add / mul
// ref_add / ref_mul, including THE ONE BROADCAST RULE: an operand carrying exactly n elements
// against an output of rows*n broadcasts along rows, and nothing else broadcasts at all. That is
@@ -310,6 +334,53 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel(
yr[i] = f32_to_bf16(1.0f / (1.0f + expf(-bf2f(xr[i]))));
}
// ---------------------------------------------------------------------------- logit_softcap
// ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. THE ROW-WISE-WITH-A-PITCH
// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the logits_gemm's output,
// and the pitch form costs nothing on a contiguous buffer -- it is x_ld == n.
__global__ __launch_bounds__(kThreads) void logit_softcap_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = f32_to_bf16(cap * tanhf(bf2f(xr[i]) / cap));
}
/* The f32 leg: the 1.3.0 sampling chain carries the logits in f32 from the gemm, so the softcap
* is issued against f32 rows. The same row-with-pitch shape as the bf16 leg, and the math is the
* op's definition verbatim -- no rounding pass, the buffer already holds the arithmetic dtype. */
__global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32(
const float* __restrict__ x, float* __restrict__ y,
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const float* __restrict__ xr = x + (size_t)m * x_ld;
float* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = cap * tanhf(xr[i] / cap);
}
// ---------------------------------------------------------------------------- scale
// ref_scale: y = x * s, s a [1] weight broadcast over every element. THE ROW-WISE-WITH-A-PITCH
// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the residual stream at
// the end of every layer (the per-layer scalar), and the pitch form costs nothing on a contiguous
// buffer -- it is x_ld == n. The scalar is read once per block (a single load, cached), not per
// element: a per-element reload of a [1] tensor is the same value every time and costs a load per
// element. `s` is f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint); the branch is
// on its dtype, so the op is dtype-generic in the scalar and the bf16 kernel is the residual
// stream's, which is what a served Gemma 4 issues it against.
__global__ __launch_bounds__(kThreads) void scale_kernel(
const uint16_t* __restrict__ x, const void* __restrict__ s, uint32_t s_dt,
uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const float sv = (s_dt == RAD_F32) ? ((const float*)s)[0] : bf2f(((const uint16_t*)s)[0]);
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = f32_to_bf16(bf2f(xr[i]) * sv);
}
// ---------------------------------------------------------------------------- silu_mul
// ref_silu_mul: y[.., i] = silu(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, which is
// the order rad-convert fuses gate_proj and up_proj into one weight in; the two conventions cannot
@@ -343,6 +414,26 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel(
}
}
// ---------------------------------------------------------------------------- gelu_mul
// ref_gelu_mul: y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, the
// same order-lock as silu_mul. The tanh-approx GELU (gemma's gelu_pytorch_tanh), NOT the erf one:
// gated feed-forwards are trained with the tanh form, and the constants are the standard fit the
// gemm_nt_bias "gelu_tanh" epilogue uses (the identical function, so a GELU-gated FFN and a
// tanh-gelu epilogue agree to the last bit).
__global__ __launch_bounds__(kThreads) void gelu_mul_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y,
uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const float g = bf2f(gr[i]);
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g)));
yr[i] = f32_to_bf16(gelu * bf2f(gr[n + i]));
}
}
// ---------------------------------------------------------------------------- rope
// ref_rope, in place over a fused [n_head + 2*n_head_kv] head row -- the V heads at the end are
// left alone, which is the whole reason the op takes the fused projection rather than two tensors.
@@ -354,8 +445,10 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel(
// (rad_block_attn_gated.h says so and says what would have to change first), so the shim maps it.
//
// PARTIAL ROTARY. `rot` may be less than head_dim -- 64 of 256 on this target -- and the tail of
// the head is untouched. The frequency exponent divides by `rot`, not by head_dim: the rotated
// prefix is a complete rotary of its own width.
// the head is untouched. The base ladder's exponent divides by `den`, which `ladder` resolves:
// `rot` for `rotary` (the rotated prefix, a complete rotary of its own width) and `head_dim` for
// `head` (the proportional variant, a prefix of the full-width table). `den` = `rot` on the
// default path, so existing models are bit-for-bit unchanged.
//
// One thread a PAIR. The pair's two loads and two stores are the whole body, so there is no
// reduction and no LDS; the grid is (M, heads).
@@ -379,7 +472,7 @@ __device__ __forceinline__ int rope_comp(int mode, uint32_t i, const int* sec, i
__global__ __launch_bounds__(kThreads) void rope_kernel(
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos,
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int gptj,
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, uint32_t nfreq, int den, int gptj,
float theta, float rscale, uint32_t row_pitch,
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) {
const uint32_t m = blockIdx.x;
@@ -392,7 +485,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
t += kThreads * gridDim.y) {
const uint32_t h = t / half, i = t % half;
uint16_t* __restrict__ hd = qkv + (size_t)m * row_pitch + (size_t)h * head_dim;
float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den);
float p = p0;
if (plane) {
uint32_t j = i;
@@ -402,6 +495,10 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c]));
}
inv = yarn.frequency(inv, (int)i);
/* THE PROPORTIONAL LADDER rotates the whole head with every frequency past nfreq zero
* (HF's _compute_proportional_rope_parameters), so pair i is (i, i + head_dim/2) and the
* pairs past nfreq turn by 0: cos 1, sin 0, the value back exactly. */
if (i >= nfreq) inv = 0.0f;
const float ang = p * inv;
float c, s;
sincosf(ang, &s, &c);
@@ -638,6 +735,13 @@ static int embed_lookup_q_emit(const int32_t* tok, const void* wte, bool q, cons
return rc == RAD_OK ? 0 : -4;
}
extern "C" int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd,
int n_vocab, int vocab_off, int x_ld, float scale,
long stream) {
R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream;
return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, scale, sk);
}
static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src_rows,
int x_ld, int y_ld, const R4dSink& sk) {
if (!x || !idx || !y) return -1;
@@ -734,6 +838,22 @@ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps,
return r4d_rmsnorm_mult_bf16(x, w, y, M, n, eps, wadd, 1.0f, w_f32, x_ld, y_ld, stream);
}
// The weightless norm: rmsnorm without the gain multiply. It is not templated on a thread count
// the way rmsnorm is, because rmsnorm's width is pinned to the fused rmsnorm_quant_fp8 by their
// shared byte-identical requirement, and rmsnorm_p has no fused quantiser counterpart to match --
// kThreads is the same choice the other non-templated row kernels (binary, sigmoid, silu_mul) make.
extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps,
int x_ld, int y_ld, long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(rmsnorm_p_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, eps,
(uint32_t)x_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// `op` is 0 for a sum and 1 for a product. `b_ld` of 0 with the same n is the broadcast form: the
// caller passes a b_ld of zero and every row reads the same n elements.
// b_ld -1 is a ONE-ELEMENT b, the scalar broadcast; 0 is one row broadcast down the rows.
@@ -788,6 +908,48 @@ extern "C" int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long s
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!(cap > 0.0f)) return -3;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream,
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap,
(uint32_t)x_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!(cap > 0.0f)) return -3;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream,
(const float*)x, (float*)y, (uint32_t)n, cap,
(uint32_t)x_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_scale_bf16(long x, long s, uint32_t s_dt, long y, int M, int n,
int x_ld, int y_ld, long stream) {
if (!x || !s || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (s_dt != RAD_F32 && s_dt != RAD_BF16) return -3;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(scale_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream,
(const uint16_t*)x, (const void*)s, s_dt, (uint16_t*)y, (uint32_t)n,
(uint32_t)x_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
if (!gu || !y) return -1;
if (M <= 0 || n <= 0) return -2;
@@ -800,21 +962,38 @@ extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// GELU-gated product, the gemma FFN activation. Same shape and order-lock as silu_mul (the gate
// is the first half of the fused [M, 2n] row); the only difference is the nonlinearity, which is
// the tanh approximation, not the erf one, to match ref_gelu_mul's act_gelu_tanh.
extern "C" int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
if (!gu || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!gu_ld) gu_ld = 2 * n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(gelu_mul_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)gu, (uint16_t*)y, (uint32_t)n,
(uint32_t)gu_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// `n_rope_heads` is n_head + n_head_kv: the Q heads and the K heads of a fused projection, or just
// the one buffer's heads when q and k are separate tensors (which is what the gated block does).
extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
int rot, int gptj, float theta, float rscale, int row_pitch,
long stream) {
return r4d_rope_mc_bf16(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale,
return r4d_rope_mc_bf16(qkv, pos, M, head_dim, n_rope_heads, rot, rot, gptj, theta, rscale,
row_pitch, 0, nullptr, 0, 0, stream);
}
// THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN
// blend returns the frequency it was given and the magnitude is not applied, so the C entry points
// below and the op without YaRN run the same arithmetic with the same arguments.
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot,
// below and the op without YaRN run the same arithmetic with the same arguments. `den` is the
// ladder's width (`rot` for `rotary`, `head_dim` for `head`) -- the multi-component form passes
// the caller's, and the plain entry passes `rot`, as it always has.
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
int gptj, float theta, float rscale, int row_pitch, int mode,
const int* sec, int n_sec, int plane, RadYarn yarn, long stream) {
const int* sec, int n_sec, int plane, RadYarn yarn, long stream,
int nfreq = -1) {
if (!qkv || !pos) return -1;
if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2;
if (rot <= 0 || rot > head_dim || (rot & 1)) return -3;
@@ -823,9 +1002,11 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
const uint32_t pairs = (uint32_t)n_rope_heads * (uint32_t)(rot / 2);
const uint32_t gy = (pairs + kThreads - 1) / kThreads;
const int s0 = n_sec > 0 ? sec[0] : 0, s1 = n_sec > 1 ? sec[1] : 0, s2 = n_sec > 2 ? sec[2] : 0;
if (nfreq < 0) nfreq = rot / 2;
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
(uint32_t)n_rope_heads, (uint32_t)rot, gptj, theta, rscale,
(uint32_t)n_rope_heads, (uint32_t)rot, (uint32_t)nfreq, (int)den, gptj, theta,
rscale,
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -833,10 +1014,11 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
int rot, int gptj, float theta, float rscale, int row_pitch,
int mode, const int* sec, int n_sec, int plane, long stream) {
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, row_pitch,
mode, sec, n_sec, plane, RadYarn{}, stream);
int rot, int den, int gptj, float theta, float rscale,
int row_pitch, int mode, const int* sec, int n_sec, int plane,
long stream) {
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, den, gptj, theta, rscale,
row_pitch, mode, sec, n_sec, plane, RadYarn{}, stream);
}
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
@@ -1281,6 +1463,29 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ rmsnorm_p */
extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(y));
const long long n = r4d_geti_or(a, "n", r4d_dim(x, (int)x->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n, &M);
const long long y_ld = r4d_rows_pitch(y, n, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const int rc = r4d_rmsnorm_p_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, eps,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s);
return rc == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ add / mul */
enum { BI_A = 0, BI_B, BI_Y };
@@ -1393,6 +1598,76 @@ extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ logit_softcap */
extern "C" int r4d_rad_logit_softcap(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
/* Two legs, one op: bf16 (the logits buffer as the gemm writes it on the bf16 chain) and f32
* (the 1.3.0 sampling chain, where the gemm hands the sampler f32 rows). The dtype check
* moved from the entry to the call below because the legs differ, not the geometry. */
const bool leg_bf16 = (x->dtype == RAD_BF16) && (y->dtype == RAD_BF16);
const bool leg_f32 = (x->dtype == RAD_F32) && (y->dtype == RAD_F32);
if (!leg_bf16 && !leg_f32) return R4D_NO(RAD_E_DTYPE);
/* `cap` is where the model lives: Gemma 4 issues it at 30.0. The default exists for the same
* reason every other one here does (a direct call with no declare in front), and the `> 0`
* test is load-bearing: a zero cap is a division by zero in every lane, not a bad answer. */
const float cap = (float)r4d_getf(a, "cap", 30.0);
if (!(cap > 0.0f)) return R4D_NO(RAD_E_INVAL);
/* ROW-WISE WITH A PITCH, same as sigmoid: issued against a column slice there is no contiguous
* extent to walk, and the contiguous case costs nothing. */
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n, &M);
const long long y_ld = r4d_rows_pitch(y, n, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
const int rc = leg_bf16
? r4d_logit_softcap_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s)
: r4d_logit_softcap_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s);
return rc == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ scale */
extern "C" int r4d_rad_scale(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* sc = r4d_opt(a, 1);
const RadTensor* y = r4d_opt(a, 2);
if (!x || !sc || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(y));
/* `s` is a [1] weight, f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint). A
* scalar with no element is a shape error, not a broadcast of zero -- a zero scalar would be
* a plausible number, which is the thing the oracle rules out. Read on the device (the kernel
* reads s[0] once per block) rather than a host copy: a device-to-host copy of one element is
* a synchronisation on the step path, and the per-block read is cached. */
if (sc->dtype != RAD_F32 && sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (r4d_numel(sc) < 1) return R4D_NO(RAD_E_SHAPE);
/* ROW-WISE WITH A PITCH, same as sigmoid: issued against the residual stream at the end of a
* layer there is no contiguous extent to walk, and the contiguous case costs nothing. */
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n, &M);
const long long y_ld = r4d_rows_pitch(y, n, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
return r4d_scale_bf16(r4d_addr(x), r4d_addr(sc), sc->dtype, r4d_addr(y), (int)M, (int)n,
(int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ silu_mul */
extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) {
@@ -1414,6 +1689,28 @@ extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) {
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ gelu_mul */
extern "C" int r4d_rad_gelu_mul(const RadArgs* a, RadStream s) {
const RadTensor* gu = r4d_opt(a, 0);
const RadTensor* y = r4d_opt(a, 1);
if (!gu || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(gu));
R4D_NEED(dt_bf16(y));
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0, Mg = 0;
const long long y_ld = r4d_rows_pitch(y, n, &M);
const long long gu_ld = r4d_rows_pitch(gu, 2 * n, &Mg);
if (y_ld < 0 || gu_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Mg < M) return R4D_NO(RAD_E_SHAPE);
const int rc = r4d_gelu_mul_bf16(r4d_addr(gu), r4d_addr(y), (int)M, (int)n, (int)gu_ld, (int)y_ld,
(long)(uintptr_t)s);
return rc == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ rope */
enum { RP_QKV = 0, RP_POS };
@@ -1433,6 +1730,21 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
if (head_dim <= 0 || n_head <= 0) return R4D_NO(RAD_E_SHAPE);
if (rot <= 0 || rot > head_dim || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
/* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim`, the
* proportional variant. head_dim is already validated above, so `den = head_dim` is safe. */
const char* lad = r4d_gets(a, "ladder");
long long den = rot;
if (lad) {
if (!std::strcmp(lad, "head")) den = head_dim;
else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head"))
return R4D_NO(RAD_E_UNSUPPORTED);
}
/* `head` is HF's proportional RoPE: the rotation spans the WHOLE head (rotate_half over
* head_dim, so pair i is (i, i + head_dim/2)) and only the first rotary_dim/2 frequencies are
* non-zero. Rotating the first rotary_dim dims as a rotary of their own pairs (i, i + rot/2)
* instead -- Gemma 4's global layers, 128 of 512 -- turns the wrong channels, and long-range
* attention degrades with distance. */
/* THE MODE, and with it how many components a position has. With [M] positions -- one
* component a token -- mrope and imrope ARE neox: every frequency reads the same position and
* the ladder is the same. With [C, M] positions and `sections`, each frequency reads the
@@ -1482,10 +1794,14 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED);
/* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole
* reason this op takes the fused projection rather than two tensors. */
long long rot_l = rot, nfreq = rot / 2;
if (den == head_dim && rot < head_dim && !multi && !gptj && mc == 0) rot_l = head_dim;
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0 ? RAD_OK
: RAD_E_DEVICE;
(int)(n_head + n_head_kv), (int)rot_l, (int)den, gptj, theta, rscale,
(int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s,
(int)nfreq) == 0
? RAD_OK
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ kv_store */
+29
View File
@@ -89,6 +89,14 @@ int r4d_rad_attn_decode_h128_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs*);
/* Gemma 4 dense sliding window (r4d_attn_paged_h256_gqa2.hip): head_dim 256, 2 queries per KV head,
* windowed. Both bands: the decode band (q_len*gqa <= 64, verify width 32 against the gqa6 leg's
* 10) and the windowed prefill band (the same r4d_attn_prefill_kernel the gqa6 leg uses, WIN on). */
int r4d_rad_attn_prefill_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_gqa2_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*);
int r4d_rad_attn_vit (const RadArgs*, RadStream);
int r4d_rad_attn_dense (const RadArgs*, RadStream);
/* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256
@@ -114,6 +122,15 @@ int64_t r4d_rad_attn_decode_h256_gqa4_scratch(const RadArgs*);
/* ...and its head_dim 64 prefill leg, LFM2's geometry, which serves every query length. */
int r4d_rad_attn_prefill_h64_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h64_gqa4_bf16(const RadArgs*, RadStream);
/* Eight queries per KV head at head_dim 512, full attention -- the Gemma 4 dense GLOBAL layers.
* Its own instantiation, not the gqa8 body above: that one's prefill tile is 48, which 512-channel
* tiles do not fit in LDS, so head_dim 512 is a stand-alone dispatch
* (r4d_attn_paged_h512_gqa8.hip). The verify width is the gqa bound, 64/8 = 8. */
int r4d_rad_attn_prefill_h512_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h512_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h512_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h512_gqa8_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h512_gqa8_scratch(const RadArgs*);
/* Twelve queries a KV head, head_dim 256 only -- Qwen3.8-Flash-Next's QSA layers. Same body,
* different instantiation; r4d_attn_paged_h256_gqa12.hip is four lines. */
int r4d_rad_attn_prefill_h256_gqa12_fp8 (const RadArgs*, RadStream);
@@ -287,6 +304,13 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*);
/* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */
int r4d_rad_quant_act_i8 (const RadArgs*, RadStream);
int r4d_rad_quant_act_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream);
int r4d_rad_qkv_norm_rope_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_gelu_mul_quant_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_quant_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_gated_had_quant_i8 (const RadArgs*, RadStream);
@@ -421,6 +445,7 @@ int r4d_rad_scatter_rows_bf16(const RadArgs*, RadStream);
int r4d_rad_scatter_rows_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_gather_rows_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_rmsnorm (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_p (const RadArgs*, RadStream);
int r4d_rad_add (const RadArgs*, RadStream);
int r4d_rad_mul (const RadArgs*, RadStream);
int r4d_rad_mul_weight (const RadArgs*, RadStream);
@@ -438,7 +463,10 @@ int r4d_rad_rel_sinusoid (const RadArgs*, RadStream);
int r4d_rad_attn_local_rel (const RadArgs*, RadStream);
int r4d_rad_sigmoid (const RadArgs*, RadStream);
int r4d_rad_fill (const RadArgs*, RadStream);
int r4d_rad_logit_softcap (const RadArgs*, RadStream);
int r4d_rad_scale (const RadArgs*, RadStream);
int r4d_rad_silu_mul (const RadArgs*, RadStream);
int r4d_rad_gelu_mul (const RadArgs*, RadStream);
int r4d_rad_rope (const RadArgs*, RadStream);
/* -- the vision tower's ops (r4d_vit_bf16.hip) -- */
int r4d_rad_layernorm (const RadArgs*, RadStream);
@@ -546,6 +574,7 @@ int r4d_shape_moe_gemm_q (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_moe_gemm_q_mod4(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_moe_gather (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_scale_rows (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_scale (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_row_topk_merge (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_quant_act_i8 (const RadParam*, int, int operand, RadOpdDesc*);
+21 -7
View File
@@ -211,11 +211,12 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
// addresses are never read.
//
// THE ARITHMETIC IS r4d_model_bf16.hip's rope_kernel, LINE FOR LINE, and that is what makes the
// fusion bit-for-bit rather than merely close: `1.0f / powf(theta, 2i/rot)`, the position divided
// by `rscale` in f32, `sincosf`, and the products consumed in f32 by the caller. Changing any of
// those here silently changes the model's output -- a different rope is a different model.
// fusion bit-for-bit rather than merely close: `1.0f / powf(theta, 2i/den)`, where `den` is the
// ladder's width (`rot` for `rotary`, `head_dim` for `head`), the position divided by `rscale`
// in f32, `sincosf`, and the products consumed in f32 by the caller. Changing any of those here
// silently changes the model's output -- a different rope is a different model.
__global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, float theta,
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, int den, float theta,
float rscale, int cs_f32, int pos_i64, RadYarn yarn) {
const int m = blockIdx.x;
const long pp = pos_i64 ? ((const long*)POS)[m] : (long)((const int*)POS)[m];
@@ -227,7 +228,7 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
const size_t o = (size_t)pp * rot;
for (int i = threadIdx.x; i < half; i += (int)blockDim.x) {
const float inv = yarn.frequency(1.0f / powf(theta, (float)(2 * i) / (float)rot), i);
const float inv = yarn.frequency(1.0f / powf(theta, (float)(2 * i) / (float)den), i);
float c, s;
sincosf(p * inv, &s, &c);
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
@@ -396,12 +397,25 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) {
if (M < 1 || rot < 2 || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(cs) % rot) return R4D_NO(RAD_E_SHAPE);
/* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim`, the
* proportional variant. `rope_table` has no head_dim by default, so `head` needs the parameter. */
const long long head_dim = r4d_geti_or(args, "head_dim", 0);
const char* lad = r4d_gets(args, "ladder");
long long den = rot;
if (lad) {
if (!std::strcmp(lad, "head")) {
if (head_dim <= 0) return R4D_NO(RAD_E_SHAPE);
den = head_dim;
} else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head"))
return R4D_NO(RAD_E_UNSUPPORTED);
}
const float theta = (float)r4d_getf(args, "theta", 10000.0);
const float rscale = (float)r4d_getf(args, "scale", 1.0);
const RadYarn yarn = rad_yarn_args(args);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return R4D_NO(RAD_E_INVAL);
return R4D_EMIT(sk, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0,
r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, theta, rscale,
cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn);
r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, (int)den, theta,
rscale, cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn);
}
R4D_ENTRY(r4d_rad_rope_table, rad_rope_table_body)
+190
View File
@@ -0,0 +1,190 @@
// r4d_qkv_norm_rope.hip - r4d_qkv_norm_rope: the per-head norms and the rotary of separate q, k and
// v projections in one dispatch -- Gemma 4's attention prologue.
//
// WHY. Between its projections and the cache store a Gemma 4 attention block runs five single-pass
// kernels over a few dozen heads: the weightless value norm (rmsnorm_p), the q and the k norms
// (rmsnorm, one row a head) and the two rotaries (rope). At a decode batch each is a handful of
// workgroups, so the block pays five dispatches for work the card does in a fraction of one. This is
// the five as one, one workgroup a (token, head).
//
// BYTE-IDENTICAL TO THE FIVE, for the reason r4d_rmsnorm_quant_i8.hip gives. What makes that hold:
//
// * each norm's sum of squares is taken by THE PARTITION ITS STANDALONE KERNEL USES. rmsnorm runs
// one workgroup a row at r4d_act_threads(rows, head_dim) threads and rmsnorm_p at 256; thread t
// folds columns t, t+THR, ... in order, the waves are summed in order through LDS. Here a
// workgroup is head_dim threads, and thread t < min(THR, head_dim) folds the same columns in the
// same order while the rest hold zero -- which is what the standalone kernel's surplus waves hold
// too, and adding +0.0 to a sum of squares changes no bit;
// * the norm output is rounded to bf16 as the standalone norm stores it, and the rotary reads that;
// * the rotary's per-pair arithmetic is rope_kernel's, written the same way (powf ladder,
// sincosf, `x0*c - x1*s`, `x0*s + x1*c`), under the library's -ffp-contract=off.
//
// `v_from_k` IS GEMMA'S GLOBAL CLASS: k == v, so v is the value norm of the RAW k, taken before the
// k norm rewrites it -- the order the unfused block issues them in.
//
// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include <cstdint>
#include <algorithm>
#include <cstring>
namespace {
constexpr uint32_t kWave = 32;
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
// THR threads' partition of one head's sum of squares, reproduced inside a head_dim-wide workgroup:
// thread t < P = min(THR, HD) folds t, t+P, ...; the waves are then summed in order.
template <uint32_t HD>
__device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_t P, float* lds) {
float ss = 0.0f;
if (threadIdx.x < P)
for (uint32_t i = threadIdx.x; i < HD; i += P) { const float v = bf2f(x[i]); ss += v * v; }
ss = r4d_wave_sum(ss);
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
if (lane == 0) lds[wave] = ss;
__syncthreads();
float s = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < HD / kWave; ++w) s += lds[w];
return s;
}
// The rotary over a normed head staged in `nb`, written to `out`: rope_kernel's body for pair i.
template <uint32_t HD>
__device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t* __restrict__ out,
float p0, uint32_t rot, uint32_t nfreq, int den, float theta) {
const uint32_t half = rot / 2, t = threadIdx.x;
if (t < half) {
float inv = 1.0f / powf(theta, (float)(2 * t) / (float)den);
if (t >= nfreq) inv = 0.0f;
const float ang = p0 * inv;
float c, s;
sincosf(ang, &s, &c);
const float x0 = bf2f(nb[t]), x1 = bf2f(nb[t + half]);
out[t] = f32_to_bf16(x0 * c - x1 * s);
out[t + half] = f32_to_bf16(x0 * s + x1 * c);
}
for (uint32_t i = rot + t; i < HD; i += HD) out[i] = nb[i]; // the unrotated tail
}
// blockIdx.y: [0, nq) a query head, [nq, nq+nkv) a key head (and with VK its value, from the raw
// key), [nq+nkv, nq+2nkv) a value head normalised in place (without VK).
template <uint32_t HD, bool WF32, bool VK>
__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(
uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v,
const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw,
uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv,
uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, float mult,
uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos) {
__shared__ float l1[HD / kWave], l2[HD / kWave];
__shared__ uint16_t nb[HD];
const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x;
const float div = rscale != 0.0f ? rscale : 1.0f;
// rope rotates the rows its positions cover; a row past them is normed and left unrotated
const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f;
if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p
uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)(hh - nq - nkv) * HD;
const float s = rsqrtf(head_ss<HD>(x, pv, l1) / (float)HD + eps);
__syncthreads(); // every thread has read x before any writes it
for (uint32_t i = t; i < HD; i += HD) x[i] = f32_to_bf16(bf2f(x[i]) * s);
return;
}
const bool isq = hh < nq;
const uint32_t h = isq ? hh : hh - nq;
uint16_t* __restrict__ x = isq ? q + (size_t)m * q_ld + (size_t)h * HD
: k + (size_t)m * k_ld + (size_t)h * HD;
const void* __restrict__ w = isq ? qw : kw;
if (VK && !isq) { // v = rmsnorm_p(raw k), before the k norm rewrites k
uint16_t* __restrict__ vo = v + (size_t)m * v_ld + (size_t)h * HD;
const float sv = rsqrtf(head_ss<HD>(x, pv, l2) / (float)HD + eps);
for (uint32_t i = t; i < HD; i += HD) vo[i] = f32_to_bf16(bf2f(x[i]) * sv);
}
const float s = rsqrtf(head_ss<HD>(x, isq ? pq : pk, l1) / (float)HD + eps);
for (uint32_t i = t; i < HD; i += HD) {
const float g = WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]);
nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd) * mult);
}
__syncthreads(); // the normed head is complete before any pair reads across it
if (m < n_pos) rotate<HD>(nb, x, p0, rot, nfreq, den, theta);
else for (uint32_t i = t; i < HD; i += HD) x[i] = nb[i];
}
} // namespace
// ============================================================== the plugin ABI entry point
enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW };
static int rad_qkv_norm_rope_body(const RadArgs* a, const R4dSink& sk) {
int emit_rc = RAD_OK;
const RadTensor* q = r4d_opt(a, QN_Q);
const RadTensor* k = r4d_opt(a, QN_K);
const RadTensor* v = r4d_opt(a, QN_V);
const RadTensor* ps = r4d_opt(a, QN_POS);
const RadTensor* qw = r4d_opt(a, QN_QW);
const RadTensor* kw = r4d_opt(a, QN_KW);
if (!q || !k || !v || !ps || !qw || !kw) return R4D_NO(RAD_E_INVAL);
if (q->dtype != RAD_BF16 || k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (ps->dtype != RAD_I32 || ps->rank != 1 || !r4d_contig(ps)) return R4D_NO(RAD_E_SHAPE);
if (qw->dtype != kw->dtype || (qw->dtype != RAD_BF16 && qw->dtype != RAD_F32)) return R4D_NO(RAD_E_DTYPE);
const long long hd = r4d_geti_or(a, "head_dim", 0);
const long long nq = r4d_geti_or(a, "n_head", 0);
const long long nkv = r4d_geti_or(a, "n_head_kv", 0);
const long long rot = r4d_geti_or(a, "rotary_dim", hd);
const long long vk = r4d_geti_or(a, "v_from_k", 0);
if (hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE);
if (nq <= 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(qw) != hd || r4d_numel(kw) != hd) return R4D_NO(RAD_E_SHAPE);
const char* mode = r4d_gets(a, "mode");
if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED);
if (r4d_getf(a, "yarn_factor", 0.0) != 0.0) return R4D_NO(RAD_E_UNSUPPORTED);
// rope's ladder, resolved exactly as r4d_rad_rope resolves it
const char* lad = r4d_gets(a, "ladder");
long long den = rot;
if (lad) {
if (!std::strcmp(lad, "head")) den = hd;
else if (std::strcmp(lad, "rotary")) return R4D_NO(RAD_E_UNSUPPORTED);
}
const long long nfreq = rot / 2;
const long long rot_l = (den == hd && rot < hd) ? hd : rot;
long long M = 0, Mk = 0, Mv = 0;
const long long q_ld = r4d_rows_pitch(q, nq * hd, &M);
const long long k_ld = r4d_rows_pitch(k, nkv * hd, &Mk);
const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv);
if (q_ld < 0 || k_ld < 0 || v_ld < 0) return R4D_NO(RAD_E_STRIDE);
const long long Mp = r4d_numel(ps);
if (Mp <= 0 || M < Mp || Mk != M || Mv != M) return R4D_NO(RAD_E_SHAPE);
// the standalone kernels' widths, from the same function: rmsnorm one row a head at
// r4d_act_threads(rows, head_dim), rmsnorm_p at 256
const uint32_t pq = (uint32_t)std::min<long long>(r4d_act_threads((int)(M * nq), (int)hd), hd);
const uint32_t pk = (uint32_t)std::min<long long>(r4d_act_threads((int)(M * nkv), (int)hd), hd);
const uint32_t pv = (uint32_t)std::min<long long>(256, hd);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
const float theta = (float)r4d_getf(a, "theta", 10000.0);
const float rsc = (float)r4d_getf(a, "scale", 1.0);
const float mult = 1.0f;
const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + (vk ? 0 : nkv)));
#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(sk, (qkv_norm_rope_kernel<HD, WF, VK>), grid, dim3(HD), 0, \
(uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \
r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \
(uint32_t)v_ld, eps, wadd, mult, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp)
#define R4D_QNR(HD) \
do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \
else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0)
if (hd == 256) R4D_QNR(256);
else R4D_QNR(512);
#undef R4D_QNR
#undef R4D_QNR_T
return emit_rc;
}
R4D_ENTRY(r4d_rad_qkv_norm_rope, rad_qkv_norm_rope_body)
+355
View File
@@ -0,0 +1,355 @@
// r4d_rmsnorm_quant_i8.hip - r4d_rmsnorm_quant_i8: the RMS norm and the per-row int8 quantiser
// r4d_gemm_w4a8_nt_m64 reads, in one pass over the row -- optionally with the residual junction
// in front of it: a post-norm on the branch output, the residual add and a scalar on the sum.
//
// WHY. A w4a8 linear needs its activation as int8 codes in the GEMM's fragment order with one f32
// scale per row (r4d_quant_act_i8), and the producer of that activation is a norm. Unfused, a
// model whose linears take that grid issues the norm and the quantiser as two dispatches, and a
// sandwich-norm model (Gemma 2/3/4) issues four or five at every residual junction:
//
// rmsnorm(branch; w_post) -> add(residual) -> [scale] -> rmsnorm(residual; w) -> quant_act_i8
//
// each one a single workgroup over one row at a decode batch, so the step pays the dispatch, not
// the bytes. This is that chain as one dispatch.
//
// BYTE-IDENTICAL TO THE CHAIN IT REPLACES, not merely close, because the engine's greedy output is
// compared byte for byte across builds. What makes that hold:
//
// * every intermediate the chain stores in bf16 is rounded to bf16 here too, and the next stage
// reads the rounded value: the post-norm output, the residual sum, the scaled residual and the
// norm output the quantiser takes its absmax and codes over;
// * both sums of squares are taken by the same partition the standalone norm uses -- the width
// r4d_act_threads(M, n) picks, thread t folding columns t, t+THR, ... in ascending order, then
// r4d_wave_sum and the waves in order through LDS (r4d_model_bf16.hip's rmsnorm_kernel and
// block_sum, which this copies rather than shares only because that one lives in another unit);
// * the arithmetic of every element is written the way the standalone kernels write it --
// `x * s * (g + wadd)`, `a + b`, `x * scalar`, `fmaxf(m, 1e-8f) / 127.f` -- and the library is
// built with -ffp-contract=off, so no stage picks up an fma the chain does not have.
//
// THE RESIDUAL IS READ AND WRITTEN, and nothing else reads it before this kernel is done: each
// thread rewrites only the columns it read, so the second pass reads its own writes back.
//
// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_ar_seq.h"
#include <cstdint>
namespace {
constexpr uint32_t kWave = 32;
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
// The standalone norm's reduction, verbatim (r4d_model_bf16.hip): the wave butterfly, then the
// waves summed IN ORDER by every thread out of LDS. `lds` must not be reused by a second
// reduction without a barrier between them -- the kernel below gives each its own array.
template <uint32_t NW>
__device__ __forceinline__ float block_sum(float v, float* lds) {
v = r4d_wave_sum(v);
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
if (lane == 0) lds[wave] = v;
__syncthreads();
float s = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < NW; ++w) s += lds[w];
return s;
}
__device__ __forceinline__ float gain(const void* w, uint32_t i, bool f32) {
return f32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]);
}
// RES: a residual is present; the norm is taken of `res + d` (stored back into `res`), where d is
// the branch `x` itself or, with POST, rmsnorm(x; w_post). Without RES the norm is of `x`.
// SCL: the sum is multiplied by the [1] scalar before it is stored and normalised.
// `ybuf` holds the row's norm output for the fragment-order store, which reads across threads.
//
// THE ROW BODY, from the junction on: `s1` is the post-norm's factor, already reduced over `xr` by
// the caller (the plain kernel below takes it off the row; the all-reduce form takes it off the
// reduced sum it has just stored). l2 and lm are this function's own reduction planes.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR>
__device__ __forceinline__ void junction_row(
const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w,
const void* __restrict__ wp, float sv, signed char* __restrict__ qr, float* __restrict__ Sr,
uint16_t* __restrict__ yr, uint32_t n, float eps, float wadd, float s1,
uint16_t* ybuf, float* l2, float* lm) {
// ---- the junction (post-norm, add, scalar), stored, and the norm's sum of squares over it
float ss2 = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) {
uint16_t v = xr[i];
if (RES) {
if (POST) v = f32_to_bf16(bf2f(v) * s1 * (gain(wp, i, WF32) + wadd));
v = f32_to_bf16(bf2f(rr[i]) + bf2f(v));
if (SCL) v = f32_to_bf16(bf2f(v) * sv);
rr[i] = v;
}
const float f = bf2f(v);
ss2 += f * f;
}
ss2 = block_sum<THR / kWave>(ss2, l2);
const float s2 = rsqrtf(ss2 / (float)n + eps);
// ---- the norm output, rounded to bf16 as the standalone norm stores it, and its absmax
const uint16_t* __restrict__ nr = RES ? rr : xr;
float m = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint16_t y = f32_to_bf16(bf2f(nr[i]) * s2 * (gain(w, i, WF32) + wadd));
ybuf[i] = y;
if (yr) yr[i] = y;
m = fmaxf(m, fabsf(bf2f(y)));
}
m = r4d_wave_max(m);
if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m;
__syncthreads(); // also publishes ybuf to every thread
m = lm[0];
#pragma unroll
for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]);
const float scale = fmaxf(m, 1e-8f) / 127.f;
const float inv = 1.f / scale;
if (threadIdx.x == 0) *Sr = scale;
// ---- the codes, in r4d_quant_act_i8's fragment order: byte j of a k step comes from
// lane-half j>>3 and element j&7, i.e. source 8*((j&7)>>2) + 4*(j>>3) + (j&3) inside the step.
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint32_t s = i >> 4, j = i & 15;
const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
const int t = __float2int_rn(bf2f(ybuf[src]) * inv);
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
}
__device__ __forceinline__ float scalar_of(const void* sc, uint32_t f32) {
return f32 ? ((const float*)sc)[0] : bf2f(((const uint16_t*)sc)[0]);
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR>
__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) {
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
const uint32_t row = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
// ---- the post-norm's sum of squares, over the branch output
float s1 = 0.0f;
if (POST) {
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; }
ss = block_sum<THR / kWave>(ss, l1);
s1 = rsqrtf(ss / (float)n + eps);
}
junction_row<WF32, RES, POST, SCL, THR>(
xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, SCL ? scalar_of(sc, sc_f32) : 1.0f,
q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1,
ybuf, l2, lm);
}
// ---------------------------------------------------------------------------------------------
// THE SAME JUNCTION WITH THE TWO-RANK ALL-REDUCE THAT ALWAYS PRECEDES IT: the branch output is a
// rank's partial sum of a column-sharded linear (o_proj, down_proj), and the post-norm is of the
// WHOLE sum. ar_rmsnorm_quant_fp8's handshake, exact wire only: each block pushes the rows it owns
// into the peer's scratch slot as 16B words, publishes its flag, waits for the peer's, and reduces
// `f2bf(mine + peer)` back into `x` -- the bytes the standalone exact all-reduce stores, fp32 add
// commuting exactly so both ranks agree -- on the post-norm's own sum-of-squares pass. A block owns
// whole rows, one a block at a decode batch.
#define R4D_ARQ8_SPIN_MAX 4000000000ULL
__device__ __forceinline__ void arq8_store_rel(unsigned int* p, unsigned int v) {
__hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
}
__device__ __forceinline__ unsigned int arq8_load_acq(const unsigned int* p) {
return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM);
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags,
unsigned int* seq_ctrs, int M, uint32_t n, float eps, float wadd, uint32_t r_ld, uint32_t y_ld,
int slot_stride16, int drain, int acq, unsigned int nbw) {
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
const int b = (int)blockIdx.x, nb = (int)gridDim.x;
const uint32_t tid = threadIdx.x;
const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb);
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); /* device-resident, replay-safe */
const unsigned int sq = s_seq;
int4* const ps = peer_base + (size_t)s_slot * slot_stride16;
const int4* const ms = my_base + (size_t)s_slot * slot_stride16;
/* push my rows into the peer's slot; `x` is a tight [M][n] of bf16 */
const int wpr = (int)(n >> 3);
const int4* const in4 = (const int4*)x;
for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) ps[k] = in4[k];
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
__syncthreads();
if (tid == 0) {
if (drain == 2) __threadfence_system();
arq8_store_rel(&peer_flags[b], sq);
unsigned long long z = 0;
while (r4d_ar_seq_behind(arq8_load_acq(&my_flags[b]), sq)) {
if (++z > R4D_ARQ8_SPIN_MAX) __builtin_trap();
}
}
__syncthreads();
if (acq) __threadfence_system();
const uint16_t* __restrict__ P = (const uint16_t*)ms; /* the peer's rows, in my scratch */
const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f;
for (int row = r0; row < r1; ++row) {
uint16_t* __restrict__ xr = x + (size_t)row * n;
const uint16_t* __restrict__ pr = P + (size_t)row * n;
float ss = 0.0f;
for (uint32_t i = tid; i < n; i += THR) {
const uint16_t a = f32_to_bf16(bf2f(xr[i]) + bf2f(pr[i]));
xr[i] = a;
if (POST) { const float v = bf2f(a); ss += v * v; }
}
float s1 = 0.0f;
if (POST) s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
junction_row<WF32, RES, POST, SCL, THR>(
xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sv, q + (size_t)row * n, S + row,
yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, ybuf, l2, lm);
__syncthreads(); /* the planes and ybuf are re-used by the next row this block owns */
}
}
} // namespace
// ============================================================== the plugin ABI entry point
//
// Operands, in the schema's order (r4d_rows.cpp, oRmsNormQuantI8):
// 0 x [M][n] bf16 the norm's input, or the branch output with a residual
// 1 residual [M][n] bf16, optional READ AND WRITTEN
// 2 w [n] bf16 or f32 the norm's gain
// 3 q [M][n] int8 fragment order, unpitched
// 4 scale [M][1] f32 one per row
// 5 out_bf16 [M][n] bf16, optional the norm output the unfused norm would have stored
// 6 w_post [n] optional a post-norm on x before the add; needs the residual
// 7 scalar [1] optional multiplies the sum; needs the residual
enum { RQ_X = 0, RQ_RES, RQ_W, RQ_Q, RQ_S, RQ_Y, RQ_WP, RQ_SC };
static int rad_rmsnorm_quant_i8_body(const RadArgs* a, const R4dSink& sk) {
int emit_rc = RAD_OK;
const RadTensor* x = r4d_opt(a, RQ_X);
const RadTensor* rs = r4d_opt(a, RQ_RES);
const RadTensor* w = r4d_opt(a, RQ_W);
const RadTensor* q = r4d_opt(a, RQ_Q);
const RadTensor* s = r4d_opt(a, RQ_S);
const RadTensor* y = r4d_opt(a, RQ_Y);
const RadTensor* wp = r4d_opt(a, RQ_WP);
const RadTensor* sc = r4d_opt(a, RQ_SC);
if (!x || !w || !q || !s) return R4D_NO(RAD_E_INVAL);
if ((wp || sc) && !rs) return R4D_NO(RAD_E_INVAL); // a junction without a stream to add into
if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || s->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
long long M = 0, n = 0;
if (r4d_rows_of(x, &M, &n) != RAD_OK) return R4D_NO(RAD_E_SHAPE);
if (n % 16) return R4D_NO(RAD_E_SHAPE); // a k step is sixteen bytes of one row
if (r4d_numel(w) != n) return R4D_NO(RAD_E_SHAPE);
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (wp && (r4d_numel(wp) != n || wp->dtype != w->dtype)) return R4D_NO(RAD_E_SHAPE);
if (sc && (r4d_numel(sc) != 1 || (sc->dtype != RAD_F32 && sc->dtype != RAD_BF16)))
return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(q) != M * n || !r4d_contig(q)) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(s) != M || !r4d_contig(s)) return R4D_NO(RAD_E_SHAPE);
if (y && r4d_numel(y) != M * n) return R4D_NO(RAD_E_SHAPE);
if (rs && r4d_numel(rs) != M * n) return R4D_NO(RAD_E_SHAPE);
const long long xp = r4d_row_pitch(x), rp = rs ? r4d_row_pitch(rs) : n, yp = y ? r4d_row_pitch(y) : n;
if (xp < 0 || rp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
// The row's norm output is staged in LDS for the cross-thread fragment-order store.
const size_t lds = (size_t)n * sizeof(uint16_t);
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
// THE SAME WIDTH AS rmsnorm_bf16 AND quant_act_i8 PICK, from the same function: it decides
// which columns a thread folds into each sum of squares, which is the byte-identity.
const int thr = r4d_act_threads((int)M, (int)n);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
const uint32_t scf = sc ? (sc->dtype == RAD_F32) : 0u;
#define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(sk, \
(rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T>), dim3((uint32_t)M), dim3(T), lds, \
(const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \
(signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \
(uint32_t)xp, (uint32_t)rp, (uint32_t)yp)
#define R4D_RQI8(WF, RS, PO, SC) \
do { if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024); \
else if (thr == 512) R4D_RQI8_T(WF, RS, PO, SC, 512); \
else if (thr == 256) R4D_RQI8_T(WF, RS, PO, SC, 256); \
else return R4D_NO(RAD_E_INVAL); } while (0)
#define R4D_RQI8_W(WF) \
do { if (!rs) R4D_RQI8(WF, false, false, false); \
else if (!wp && !sc) R4D_RQI8(WF, true, false, false); \
else if (wp && !sc) R4D_RQI8(WF, true, true, false); \
else if (wp && sc) R4D_RQI8(WF, true, true, true); \
else R4D_RQI8(WF, true, false, true); } while (0)
if (w->dtype == RAD_F32) R4D_RQI8_W(true);
else R4D_RQI8_W(false);
#undef R4D_RQI8_W
#undef R4D_RQI8
#undef R4D_RQI8_T
return emit_rc;
}
R4D_ENTRY(r4d_rad_rmsnorm_quant_i8, rad_rmsnorm_quant_i8_body)
// The fused all-reduce form's launch. The IPC arguments are r4d_ar_oneshot_2rank_exact's -- the
// double-buffered scratch, the per-block flags and the device-resident sequence counters -- and the
// rest is the junction's. `x` is the message and takes no pitch; `nblocks` is clamped to M (a block
// owns whole rows). Returns 0, or a negative code for a shape it does not serve.
extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long wp, long sc, int sc_f32,
long y, long q, long s, int M, int n, float eps, float wadd,
int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq) {
if (!x || !w || !q || !s) return -1;
if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 16) return -3;
if ((wp || sc) && !res) return -5;
if ((size_t)n * sizeof(uint16_t) > 60 * 1024) return -6;
if (!r_ld) r_ld = n;
if (!y_ld) y_ld = n;
int nb = nblocks < 1 ? 1 : nblocks;
if (nb > M) nb = M;
const int nbw = r4d_ar_max_blocks();
if (nb > nbw) nb = nbw;
const int thr = r4d_act_threads(M, n);
const size_t lds = (size_t)n * sizeof(uint16_t);
#define R4D_ARQ8_T(WF, RS, PO, SC, T) \
hipLaunchKernelGGL((ar_rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T>), dim3((uint32_t)nb), \
dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \
(const void*)w, (const void*)wp, (const void*)sc, (uint32_t)sc_f32, \
(signed char*)q, (float*)s, (uint16_t*)y, (int4*)peer_scratch, \
(const int4*)my_scratch, (unsigned int*)peer_flags, \
(unsigned int*)my_flags, (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, \
wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, drain, acq, \
(unsigned)nbw)
#define R4D_ARQ8(WF, RS, PO, SC) \
do { if (thr == 1024) R4D_ARQ8_T(WF, RS, PO, SC, 1024); \
else if (thr == 512) R4D_ARQ8_T(WF, RS, PO, SC, 512); \
else R4D_ARQ8_T(WF, RS, PO, SC, 256); } while (0)
#define R4D_ARQ8_W(WF) \
do { if (!res) R4D_ARQ8(WF, false, false, false); \
else if (!wp && !sc) R4D_ARQ8(WF, true, false, false); \
else if (wp && !sc) R4D_ARQ8(WF, true, true, false); \
else if (wp && sc) R4D_ARQ8(WF, true, true, true); \
else R4D_ARQ8(WF, true, false, true); } while (0)
if (w_f32) R4D_ARQ8_W(true);
else R4D_ARQ8_W(false);
#undef R4D_ARQ8_W
#undef R4D_ARQ8
#undef R4D_ARQ8_T
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+381 -10
View File
@@ -277,11 +277,13 @@ static const RadParamSpec pRopeTable[] = {
{ "rot", RAD_P_INT, RAD_REQUIRED },
P_F64("theta"),
P_F64("scale"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
{ "head_dim", RAD_P_INT, RAD_OPTIONAL }, /* needed only by the `head` ladder */
{ "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */
};
static const RadOperandSpec oRopeTable[] = {
{ "positions", RAD_OPD_IN, 0 },
@@ -1312,6 +1314,97 @@ static const RadOperandSpec oArRmsNormQuantFp8[] = {
{ "out_bf16", RAD_OPD_OUT, 1 },
};
/* `rmsnorm_quant_i8` is the norm with r4d_gemm_w4a8_nt_m64's own activation producer on its pass:
* int8 codes in the GEMM's fragment order and ONE f32 scale per row -- quant_act_i8's grid, not
* quant_act_i8g's per-group one and not the rotated rmsnorm_had_quant_i8's. Its first six operands
* are rmsnorm_quant_fp8's, so the residual is the fused_add_rms_norm form; two optional weights
* after them make it a sandwich-norm model's whole residual junction: `w_post` normalises the
* branch output BEFORE the add and `scalar` multiplies the sum after it (Gemma's per-layer
* scalar). Every stage rounds to bf16 where the chain it replaces stores bf16, so the op is
* byte-identical to that chain. */
static const RadParamSpec pRmsNormQuantI8[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
P_F64("eps"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
P_F64O("wadd"),
};
static const RadOperandSpec oRmsNormQuantI8[] = {
{ "x", RAD_OPD_IN, 0 },
{ "residual", RAD_OPD_INOUT, 1 }, /* present = the norm is of residual + (post-normed) x */
{ "w", RAD_OPD_WEIGHT, 0 },
{ "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 },
{ "out_bf16", RAD_OPD_OUT, 1 },
{ "w_post", RAD_OPD_WEIGHT, 1 }, /* rmsnorm(x; w_post) before the add; needs the residual */
{ "scalar", RAD_OPD_WEIGHT, 1 }, /* [1], multiplies the sum; needs the residual */
};
/* `qkv_norm_rope` is `qk_norm_rope` over SEPARATE q, k and v projections rather than one fused row:
* the per-head q and k norms, the weightless value norm and the rotary of q and k, in one
* dispatch -- Gemma 4's attention prologue, whose projections are three GEMMs. `v_from_k` 1 is its
* global class (k == v): v is the value norm of the RAW k, written before the k norm rewrites it.
* The rotary parameters are `rope`'s (`ladder` included), the norm parameters `rmsnorm`'s, and the
* op is byte-identical to rmsnorm_p + rmsnorm + rmsnorm + rope + rope. */
static const RadParamSpec pQkvNormRope[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "head_dim", RAD_P_INT, RAD_REQUIRED },
{ "n_head", RAD_P_INT, RAD_REQUIRED },
{ "n_head_kv", RAD_P_INT, RAD_REQUIRED },
P_F64("theta"),
P_F64("eps"),
P_F64O("scale"),
{ "mode", RAD_P_STR, RAD_OPTIONAL },
{ "rotary_dim", RAD_P_INT, RAD_OPTIONAL },
{ "ladder", RAD_P_STR, RAD_OPTIONAL },
P_F64O("wadd"),
{ "v_from_k", RAD_P_INT, RAD_OPTIONAL },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
static const RadOperandSpec oQkvNormRope[] = {
{ "q", RAD_OPD_INOUT, 0 },
{ "k", RAD_OPD_INOUT, 0 },
{ "v", RAD_OPD_INOUT, 0 }, /* written from the raw k under v_from_k */
{ "positions", RAD_OPD_IN, 0 },
{ "q_w", RAD_OPD_WEIGHT, 0 },
{ "k_w", RAD_OPD_WEIGHT, 0 },
};
/* `gelu_mul_quant_i8` is `gelu_mul` with quant_act_i8's quantiser on its pass: the down projection
* input of a GELU-gated feed-forward on the w4a8 grid, byte-identical to the pair. */
static const RadParamSpec pGeluMulQuantI8[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
static const RadOperandSpec oGeluMulQuantI8[] = {
{ "gate_up", RAD_OPD_IN, 0 },
{ "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 },
{ "out_bf16", RAD_OPD_OUT, 1 },
};
/* `ar_rmsnorm_quant_i8` is rmsnorm_quant_i8 with the two-rank exact all-reduce of `x` in front:
* same operands, `x` INOUT because the reduced sum lands back in it, plus `world_size`. */
static const RadParamSpec pArRmsNormQuantI8[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
P_F64("eps"),
{ "world_size", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
P_F64O("wadd"),
};
static const RadOperandSpec oArRmsNormQuantI8[] = {
{ "x", RAD_OPD_INOUT, 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 },
{ "w_post", RAD_OPD_WEIGHT, 1 },
{ "scalar", RAD_OPD_WEIGHT, 1 },
};
static const RadParamSpec pGatedQuantFp8[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
@@ -1536,6 +1629,16 @@ static const RadParamSpec pMnDtype[] = {
{ "n", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
/* `logit_softcap`'s, matched field for field to ref's `pMnCap` so the two plugins agree (spec
* §2.3). `cap` is required and must be > 0; a non-positive cap is a division by zero in every
* lane, so the op refuses it rather than answering with NaNs. */
static const RadParamSpec pMnCap[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
P_F64("cap"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
static const RadOperandSpec oBinary[] = {
{ "a", RAD_OPD_IN, 0 },
{ "b", RAD_OPD_IN, 0 },
@@ -1640,6 +1743,11 @@ static const RadParamSpec pFill[] = {
static const RadOperandSpec oFill[] = {
{ "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oScale[] = {
{ "x", RAD_OPD_IN, 0 },
{ "s", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
/* `cast`'s two dtype keys are STRINGS and not one `dtype`, because the whole point of the op is
* that the two ends differ. ref's spelling, matched field for field so the two plugins agree. */
static const RadParamSpec pCast[] = {
@@ -1674,6 +1782,7 @@ static const RadParamSpec pRope[] = {
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
{ "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */
};
/* ---------------------------------------------------------------------- the vision tower */
@@ -1738,7 +1847,7 @@ static const RadParamSpec pEmbed[] = {
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "vocab_offset", RAD_P_INT, RAD_OPTIONAL }, /* first GLOBAL row; vocab-parallel embedding */
/* The scale embed_lookup_q's layout quantises with. That op shares this parameter list and
* libref fixes it for both, so it is spelled here to match; embed_lookup reads no scale. */
* libref fixes it for both, so it is spelled here to match. */
{ "wscale", RAD_P_F64, RAD_OPTIONAL },
};
/* embed_lookup's own: pEmbed and `mult`, the factor every gathered row is multiplied by (Gemma's
@@ -1961,6 +2070,11 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("rmsnorm", pRmsNorm, oRmsNorm,
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in "
"f32 after the load because forming it in bf16 first costs 0.3% per channel."),
SCHEMA("rmsnorm_p", pLayernorm, oUnary,
"y = x * rsqrt(mean(x^2) + eps); an rmsnorm with NO gain tensor at all. Gemma's "
"attention normalises the value with a bare RMS (a weightless ggml_rms_norm) and the "
"key with the k_norm gain in the same layer, which one op with a required gain cannot "
"express."),
SCHEMA("add", pMnDtype, oBinary,
"y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts "
"along rows, and nothing else broadcasts at all."),
@@ -1970,7 +2084,12 @@ static const RadOpSchema kSchemas[] = {
"(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."),
SCHEMA("silu_mul", pMnDtype, oGateUp,
"y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The GATE IS THE FIRST HALF, "
"which is the order rad-convert fuses gate_proj and up_proj in."),
"which is the order rad-convert fuses gate_proj and up_proj in."),
SCHEMA("gelu_mul", pMnDtype, oGateUp,
"y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i], the tanh approximation "
"(gemma's gelu_pytorch_tanh), and the GATE IS THE FIRST HALF as in silu_mul. Its own "
"op, not gelu, because gated feed-forwards are trained with the tanh form and the "
"unary gelu is the exact erf one."),
SCHEMA("act_mul", pActMul, oBinary,
"y = act(a) * b, the activation (silu, gelu, gelu_tanh) rounded to y's dtype before "
"the product: silu_mul with its two halves in two operands."),
@@ -2008,6 +2127,12 @@ static const RadOpSchema kSchemas[] = {
"y = value, every element of an [M, n] extent (default 0). The op a rank issues where "
"it computes nothing and a reader downstream -- an all-reduce, a residual -- still "
"expects a defined buffer: a wire shared across layers cannot be zeroed once a step."),
SCHEMA("logit_softcap", pMnCap, oUnary,
"y = cap * tanh(x / cap); the final-logit softcap. `cap` is required and > 0."),
SCHEMA("scale", pMnDtype, oScale,
"y = x * s, s a [1] weight broadcast over every element; the per-tensor scalar "
"(per-layer scalar). `mul` broadcasts a row, `scale_rows` a column-per-row."),
SCHEMA("cast", pCast, oUnary,
"y = x, converted. `from` and `to` are for the selector; the bytes are described by the "
"tensors' own dtypes and those are what the kernel reads."),
@@ -2297,6 +2422,17 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("rmsnorm_quant_fp8", pRmsNormQuantFp8, oRmsNormQuantFp8,
"RMS norm and the fp8 activation quantiser in one pass over the row. The bf16 norm "
"output the unfused pair wrote is still written, and the codes are taken over it."),
SCHEMA("rmsnorm_quant_i8", pRmsNormQuantI8, oRmsNormQuantI8,
"RMS norm and the per-row int8 quantiser the w4a8 skinny GEMM reads, in one pass; with "
"a residual the norm is of residual + x (+ a post-norm of x, x a scalar), stored back."),
SCHEMA("qkv_norm_rope", pQkvNormRope, oQkvNormRope,
"per-head q and k RMS norms, the weightless v norm and the rotary of q and k over separate "
"q, k and v projections, in one dispatch; v from the raw k under v_from_k."),
SCHEMA("gelu_mul_quant_i8", pGeluMulQuantI8, oGeluMulQuantI8,
"gelu(gate) * up (tanh form) and the per-row int8 quantiser the w4a8 skinny GEMM reads, in "
"one pass."),
SCHEMA("ar_rmsnorm_quant_i8", pArRmsNormQuantI8, oArRmsNormQuantI8,
"the two-rank exact all-reduce of x and rmsnorm_quant_i8 after it, in one kernel."),
SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
"silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."),
SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
@@ -2455,6 +2591,32 @@ static const RadConstraint cAttnDecodeH128Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* Gemma 4 dense sliding window: head_dim 256, 2 queries per kv head, windowed decode
* (r4d_attn_paged_h256_gqa2.hip). window is a launch argument -- 1024 in the model, 0 = full
* attention -- so it is constrained on both sides like the drafter leg, not fixed. q_len <= 32 is
* the q_len*gqa <= 64 of the prose at gqa 2, and the bucket boundary that keeps prefill out. */
static const RadConstraint cAttnDecodeH256Gqa2Fp8[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* Gemma 4 dense sliding-window PREFILL (r4d_attn_paged_h256_gqa2.hip): the same geometry as the
* decode leg above, but no q_len bound -- it serves the prefill band (q_len > 32, the bucket the
* decode leg's C_LE leaves). window is a launch argument (1024 in the model) exactly as on the
* decode leg, so C_GE on both sides; the kernel's WIN bit masks the window and skips the below-
* window tiles. This was the band the decode-only leg left as a hole: a base-model prefill with no
* device kernel is fatal (spec §17 -- libref is an opt-in fallback the engine refuses by default). */
static const RadConstraint cAttnPrefillH256Gqa2Fp8[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnPrefillH256Gqa2Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* EIGHT QUERIES PER KV HEAD, at both head widths (r4d_attn_paged_gqa8.hip). q_len <= 8 is the
* `q_len * gqa <= 64` of the prose at gqa 8, and the difference from the gqa6 leg's 10 is the whole
* of what the ratio changes: a decode workgroup holds 64 rows and the verify width is how many of
@@ -2507,6 +2669,25 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* Gemma 4 dense GLOBAL layers: head_dim 512, 8 queries per KV head, full attention
* (r4d_attn_paged_h512_gqa8.hip). The `q_len <= 8` bound is the gqa verify width again; window
* stays 0, which is what separates this from the sliding leg and why it needs no windowed form. */
static const RadConstraint cAttnPrefillH512G8Fp8[] = {
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnPrefillH512G8Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
static const RadConstraint cAttnDecodeH512G8Fp8[] = {
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnDecodeH512G8Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's
* QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two
* ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is
@@ -2658,7 +2839,7 @@ static const RadConstraint cAttnDenseH512G4[] = {
/* A head in a wave's registers with a rotary pair in one lane: head_dim a multiple of 32 up to
* 1024. The shim refuses a rotary_dim whose half is not a multiple of 32 (neox) by name. */
static const RadConstraint cQkNormRope[] = {
C_LE("head_dim", 1024), C_DIV("head_dim", 32),
C_LE("head_dim", 1024), C_DIV("head_dim", 2),
};
/* ---- gated delta net ----------------------------------------------------------------------- */
@@ -3117,6 +3298,24 @@ static const RadConstraint cSampleChain[] = {
static const RadConstraint cQuantActI8[] = {
C_DIV("n", 16), C_IN("dtype", "bf16"),
};
/* `n DIV 16`: a k step of the fragment order is sixteen bytes of one row. The row is staged in LDS
* as bf16 for the cross-thread fragment store: `n <= 30720` is the 60 KiB the shims bound it to,
* stated here so a wider row is refused at selection, where the caller can keep the unfused chain,
* and not at its first launch. */
static const RadConstraint cRmsNormQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"),
};
/* head_dim 256 or 512: a workgroup is one head, a thread one channel. */
static const RadConstraint cQkvNormRope[] = {
C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"),
};
static const RadConstraint cGeluMulQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"),
};
/* x is the message, pushed as 16B words, and the row is staged in LDS for the fragment store. */
static const RadConstraint cArRmsNormQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 2), C_P2P,
};
static const RadConstraint cHadQuantActI8[] = {
C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"),
};
@@ -3419,6 +3618,7 @@ static const RadTunable tMv[] = {
* cannot match a query that forgot to say what it wanted -- the same reasoning cSampleChain gives.
* n_cand is bounded because the top-k's bitonic sort runs in LDS over a power-of-two padding. */
static const RadConstraint cBf16Row[] = { C_IN("dtype", "bf16") };
static const RadConstraint cF32Row[] = { C_IN("dtype", "f32") };
/* bf16 rows over the byte copy, which moves four bytes a thread: an even width. */
static const RadConstraint cBf16Row2[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) };
/* Opaque byte rows, four at a time. The width constraint is the vectorised copy's
@@ -3630,9 +3830,10 @@ static const RadKernelInfo kKernels[] = {
{ "qk_norm_rope_bf16", "qk_norm_rope", "attn",
"per-head RMS norm of q and k (and optionally v, unit gain) with rotary on q and k, in place",
"head_dim a multiple of 32 up to 1024, neox (rotary_dim / 2 a multiple of 32), gptj, or "
"blocks (sections of 16 or a multiple of 32 pairs, each starting on a 32-channel slice); one "
"workgroup a token and a wave a head, sin/cos computed once for all its heads",
"head_dim up to 1024, a multiple of 32 for neox (rotary_dim / 2 a multiple of 32) and gptj; "
"blocks at any even head_dim and section size (sections of 16 or a multiple of 32 pairs, each "
"on a 32-channel slice, in registers; others a lane a pair); one workgroup a token and a wave "
"a head, sin/cos computed once for all its heads",
"bf16 qkv and gains, i32 positions, f32 arithmetic, the norm rounded before the rotation",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cQkNormRope), NOTUNE,
@@ -3716,6 +3917,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_rmsnorm, nullptr, nullptr, nullptr,
r4d_shape_rmsnorm },
{ "rmsnorm_p_bf16", "rmsnorm_p", "norm",
"weightless root-mean-square norm (no gain), two passes over the row",
"any n; the sum of squares accumulates in f32 and only the store narrows",
"bf16 x / y, fp32 reduction",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_rmsnorm_p, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "layernorm_bf16", "layernorm", "norm",
"layer norm with a gain and an optional bias, two passes over the row",
"any n; mean and variance accumulate in f32 and only the store narrows",
@@ -3798,6 +4008,33 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_sigmoid, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "logit_softcap_bf16", "logit_softcap", "elem",
"cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent",
"any extent; contiguous in and out",
"bf16 in and out, fp32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_logit_softcap, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "logit_softcap_f32", "logit_softcap", "elem",
"cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent",
"any extent; contiguous in and out",
"f32 in and out — the 1.3.0 sampling chain carries the logits as f32 from the gemm",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cF32Row), NOTUNE,
nullptr, nullptr, r4d_rad_logit_softcap, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "scale_bf16", "scale", "elem",
"x * s, s a [1] weight broadcast over the whole extent, grid-strided",
"any extent; contiguous in and out",
"bf16 in and out, fp32 arithmetic, s f32 or bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr,
r4d_shape_scale },
{ "silu_mul_bf16", "silu_mul", "elem",
"silu-gated product over a fused [M, 2n] gate_up",
"any n; the gate is the first half",
@@ -3807,6 +4044,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_silu_mul, nullptr, nullptr, nullptr,
r4d_shape_silu_mul },
{ "gelu_mul_bf16", "gelu_mul", "elem",
"gelu-gated product over a fused [M, 2n] gate_up",
"any n; the gate is the first half",
"bf16 in and out, fp32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_mul, nullptr, nullptr, nullptr,
r4d_shape_silu_mul },
{ "rope_bf16", "rope", "attn",
"rotary embedding in place, one thread a rotated pair",
"any head_dim; rotary_dim even and no wider than head_dim -- the frequency exponent divides by "
@@ -4080,6 +4326,48 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa2_fp8kv", "attn_paged", "attn",
"paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)",
"head_dim 256, 2 queries per kv head, paged block 16, varlen, "
"window taken from the launch argument (0 = full attention)",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH256Gqa2Fp8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa2_fp8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa2_bf16kv", "attn_paged", "attn",
"paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)",
"head_dim 256, 2 queries per kv head, paged block 16, varlen, "
"window taken from the launch argument (0 = full attention)",
"bf16 query, bf16 kv cache, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH256Gqa2Bf16), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa2_bf16, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h256_gqa2_fp8kv", "attn_paged", "attn",
"paged causal attention with a sliding window, split-KV (decode / verify)",
"head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, "
"window taken from the launch argument (0 = full attention)",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH256Gqa2Fp8), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa2_fp8, r4d_rad_attn_decode_h256_gqa2_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h256_gqa2_bf16kv", "attn_paged", "attn",
"paged causal attention with a sliding window, split-KV (decode / verify)",
"head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, "
"window taken from the launch argument (0 = full attention)",
"bf16 query, bf16 kv cache, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa2_bf16, r4d_rad_attn_decode_h256_gqa2_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 8 queries per kv head, paged block 16, varlen",
@@ -4174,6 +4462,44 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_attn_prefill_h64_gqa4_bf16, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h512_gqa8_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 512, 8 queries per kv head, paged block 16, varlen",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH512G8Fp8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_fp8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h512_gqa8_bf16kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 512, 8 queries per kv head, paged block 16, varlen",
"bf16 query, bf16 kv cache, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH512G8Bf16), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_bf16, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h512_gqa8_fp8kv", "attn_paged", "attn",
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
"head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH512G8Fp8), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_fp8, r4d_rad_attn_decode_h512_gqa8_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h512_gqa8_bf16kv", "attn_paged", "attn",
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
"head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window",
"bf16 query, bf16 kv cache, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH512G8Bf16), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_bf16, r4d_rad_attn_decode_h512_gqa8_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
@@ -5414,6 +5740,51 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_quant_act_i8, nullptr, nullptr, nullptr,
r4d_shape_quant_act_i8 , nullptr, nullptr, r4d_rad_quant_act_i8_describe },
{ "rmsnorm_quant_i8", "rmsnorm_quant_i8", "quant",
"RMS norm and quant_act_i8's quantiser in one pass over the row; optionally the residual "
"junction in front of it -- a post-norm on x, the add into the residual and a scalar on the sum",
"n a multiple of 16 and n*2 bytes within LDS; one workgroup per row at rmsnorm_bf16's width; "
"the gains f32 or bf16, read off the operand; w_post and scalar need the residual",
"bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale, optional bf16 "
"out; every stored intermediate rounded to bf16 as the unfused chain stores it",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cRmsNormQuantI8), NOTUNE,
nullptr, nullptr, r4d_rad_rmsnorm_quant_i8, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, r4d_rad_rmsnorm_quant_i8_describe },
{ "qkv_norm_rope_bf16", "qkv_norm_rope", "attn",
"per-head RMS norms of separate q and k projections, the weightless norm of v (or of the raw k), "
"and the rotary of q and k, in place, in one dispatch",
"head_dim 256 or 512; neox, `rotary` or `head` ladder, one position component, no YaRN; one "
"workgroup a (token, head), a thread a channel",
"bf16 q/k/v and gains (or f32 gains), i32 positions; byte-identical to rmsnorm_p + rmsnorm x2 + "
"rope x2, each norm taken by its standalone kernel's partition",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cQkvNormRope), NOTUNE,
nullptr, nullptr, r4d_rad_qkv_norm_rope, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, r4d_rad_qkv_norm_rope_describe },
{ "gelu_mul_quant_i8", "gelu_mul_quant_i8", "quant",
"gelu(gate) * up, the tanh form, and quant_act_i8's quantiser in one pass over the row",
"n a multiple of 16 and n*2 bytes within LDS; one workgroup per row",
"bf16 gate_up in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale, optional "
"bf16 out; the codes taken over the bf16-rounded product",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGeluMulQuantI8), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_mul_quant_i8, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, r4d_rad_gelu_mul_quant_i8_describe },
{ "ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8", "quant",
"the two-rank exact all-reduce and the junction after it -- post-norm of the reduced sum, residual "
"add, scalar, RMS norm and quant_act_i8's quantiser -- in one kernel",
"exactly 2 ranks; n a multiple of 16, x unpitched (it is the message); one block a row; exact wire",
"bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale; the reduced sum "
"rounded to bf16 as the standalone exact all-reduce stores it",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cArRmsNormQuantI8), ROW(tAr), nullptr,
r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8, nullptr, nullptr, nullptr,
nullptr },
{ "had_quant_act_i8", "had_quant_act_i8", "quant",
"block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes "
"int8 activations usable at all: unrotated, the per-row absmax is set by a few outlier channels "
+873 -2
View File
@@ -771,7 +771,7 @@ static const RadKernelInfo* find(const Plugin& pl, const char* name) {
/* ------------------------------------------------------------------ per-family smoke tests */
static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa,
int64_t q_len, const char* kv_dtype, int prefill) {
int64_t q_len, const char* kv_dtype, int prefill, int window = 0) {
if (!sel(name)) return;
const RadKernelInfo* r = find(pl, name);
if (!r) { ok(name, false, "row absent"); return; }
@@ -803,7 +803,7 @@ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int6
absent(ts[6]);
std::vector<RadParam> ps = {
PI("q_len", q_len), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs),
PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
};
(void)prefill;
run_case(r, ts, ps);
@@ -884,6 +884,186 @@ static float h_e4m3(uint8_t b) {
return sign * (1.0f + (float)mn / 8.0f) * std::ldexp(1.0f, (int)ex - 7);
}
/* Two avalanche-random values for the numeric attention check: a bounded bf16 in [-1, 1] and an
* e4m3 code, each a function of its index so a wrong pitch or lane map reads unrelated numbers. */
static uint16_t st_rand_bf16(uint32_t i) {
const uint32_t x = st_mix32(i);
const float f = ((x & 0x00ffffffu) / 16777215.0f) * 2.0f - 1.0f;
return h_to_bf16(f);
}
static uint8_t st_rand_e4m3(uint32_t i) {
const uint32_t x = st_mix32(i + 0x9e3779b9u);
/* Bounded to [-1, 1] (the positive magnitudes below), mirroring st_rand_bf16. The full e4m3
* range (up to 448) makes the attention scores reach ~448*head_dim/sqrt(head_dim), so the
* softmax dominates by e^score and a 1-ulp difference between the device's v_cvt_f32_fp8 and
* this software h_e4m3 flips the max into a large output error; bounded, the scores stay ~22
* (the passing bf16 path) and the comparison is stable. */
static const uint8_t mag[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* subnormal, 0 .. 7/64 */
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, /* exp 4, 0.125 .. 0.234375 */
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, /* exp 5, 0.25 .. 0.46875 */
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, /* exp 6, 0.5 .. 0.9375 */
0x38, /* exp 7, 1.0 */
};
const uint8_t m = mag[(x >> 1) % (sizeof mag / sizeof mag[0])];
return (uint8_t)(m | (((x >> 8) & 1u) << 7));
}
/* The inline paged-attention oracle: a port of ref_attn_paged (libref/ref_attn.cpp) for the
* uniform batch, bf16 q, fp8-e4m3 or bf16 k/v, f32 descales. The selftest does not link libref,
* so the reference the kbench byte-equality uses is carried here; the mask, the two-pass softmax
* and the k/v dequant are the same, so a wrong kernel fails the comparison. One (row, head) at a
* time: `i` is the query's position within its sequence's query, and `pos = ctx - qlen + i`. */
static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8,
int64_t head_dim, int64_t kv_heads, int64_t block_size, int64_t kh,
const int* block_table, int64_t max_blocks, int ctx,
float kds, float vds, int causal, int window, float scale,
int64_t qlen, int64_t i, float* out) {
const int ew = kv_is_fp8 ? 1 : 2;
const int64_t pos = ctx - qlen + i;
const int64_t sb = kv_heads * block_size * 2 * head_dim;
const int64_t sh = block_size * 2 * head_dim;
const int64_t so = 2 * head_dim;
const auto kslot = [&](int64_t blk, int64_t slot, int64_t d) {
const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + d) * ew;
return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p);
};
const auto vslot = [&](int64_t blk, int64_t slot, int64_t d) {
const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + head_dim + d) * ew;
return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p);
};
const auto visible = [&](int64_t j) {
if (causal ? (j > pos) : (j >= ctx)) return false;
if (window > 0) { const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) return false; }
return true;
};
float mx = -INFINITY;
for (int64_t j = 0; j < ctx; ++j) {
if (!visible(j)) continue;
if (j / block_size >= max_blocks) break;
int blk = block_table[j / block_size];
if (blk < 0) continue;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) dot += h_bf16(qh[d]) * (kslot(blk, j % block_size, d) * kds);
dot *= scale;
if (dot > mx) mx = dot;
}
if (mx == -INFINITY) { for (int64_t d = 0; d < head_dim; ++d) out[d] = 0.0f; return; }
float sum = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) out[d] = 0.0f;
for (int64_t j = 0; j < ctx; ++j) {
if (!visible(j)) continue;
if (j / block_size >= max_blocks) break;
int blk = block_table[j / block_size];
if (blk < 0) continue;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) dot += h_bf16(qh[d]) * (kslot(blk, j % block_size, d) * kds);
const float w = std::exp(dot * scale - mx);
sum += w;
for (int64_t d = 0; d < head_dim; ++d) out[d] += w * (vslot(blk, j % block_size, d) * vds);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) out[d] *= inv;
}
/* The numeric attention check: fill q and the paged k/v with avalanche-random data, run the row,
* and compare the bf16 output against the inline oracle above. The launch smoke (attn_case) proves
* the kernel starts; this proves it computes. A negative control corrupts a share of the reference
* and requires the comparison to FAIL -- the proof the check has teeth. */
static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa,
int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64) {
if (!sel(name)) return;
const RadKernelInfo* r = find(pl, name);
if (!r) { ok(name, false, "row absent"); return; }
const int64_t seqs = 1, kv_heads = 2, bs = 16;
const int64_t q_heads = kv_heads * gqa;
const int64_t max_blocks = ctx / bs;
const int64_t total_q = seqs * q_len;
const int kv_is_fp8 = std::strcmp(kv_dtype, "bf16") != 0;
const uint32_t kvdt = kv_is_fp8 ? RAD_F8E4M3 : RAD_BF16;
const int ew = kv_is_fp8 ? 1 : 2;
const float scale = 1.0f / std::sqrt((float)head_dim);
std::vector<uint16_t> qh((size_t)total_q * q_heads * head_dim);
for (size_t i = 0; i < qh.size(); ++i) qh[i] = st_rand_bf16(i);
const int64_t nelem = max_blocks * kv_heads * bs * 2 * head_dim;
std::vector<uint8_t> kv((size_t)nelem * ew);
for (int64_t e = 0; e < nelem; ++e) {
const size_t bo = (size_t)e * ew;
if (kv_is_fp8) kv[bo] = st_rand_e4m3(e);
else { const uint16_t h = st_rand_bf16(e); kv[bo] = (uint8_t)h; kv[bo + 1] = (uint8_t)(h >> 8); }
}
const std::vector<int32_t> bt = iota_i32(max_blocks);
void* d_q = dalloc((size_t)total_q * q_heads * head_dim * 2);
st_memcpy(d_q, qh.data(), qh.size() * 2, hipMemcpyHostToDevice);
void* d_kv = dalloc(kv.size());
st_memcpy(d_kv, kv.data(), kv.size(), hipMemcpyHostToDevice);
void* d_out = dalloc((size_t)total_q * q_heads * head_dim * 2);
std::vector<RadTensor> ts = {
T(d_q, RAD_BF16, { total_q, q_heads, head_dim }),
T(d_kv, kvdt, { max_blocks, kv_heads, bs, 2 * head_dim }),
TI32({ seqs, max_blocks }, bt),
TI32({ seqs }, rep_i32(seqs, (int32_t)ctx)),
TF32({ seqs, kv_heads }, 1.0f),
TF32({ seqs, kv_heads }, 1.0f),
T(nullptr, RAD_I32, { seqs + 1 }),
T(d_out, RAD_BF16, { total_q, q_heads, head_dim }),
};
if (kvdt == RAD_BF16) { absent(ts[4]); absent(ts[5]); }
absent(ts[6]);
std::vector<RadParam> ps = {
PI("q_len", q_len), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs),
PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
};
run_case(r, ts, ps);
std::vector<uint16_t> oh((size_t)total_q * q_heads * head_dim);
st_memcpy(oh.data(), d_out, oh.size() * 2, hipMemcpyDeviceToHost);
const float abs_tol = 1e-3f, rel_tol = 2e-2f;
std::vector<float> oref((size_t)total_q * q_heads * head_dim);
float max_err = 0.0f; int nbad = 0;
for (int64_t tok = 0; tok < total_q; ++tok)
for (int64_t h = 0; h < q_heads; ++h) {
const int64_t kh = h / gqa;
float o[512];
attn_oracle_one(&qh[(tok * q_heads + h) * head_dim], kv.data(), kv_is_fp8,
head_dim, kv_heads, bs, kh, bt.data(), max_blocks, ctx,
1.0f, 1.0f, 1, window, scale, q_len, tok, o);
for (int64_t d = 0; d < head_dim; ++d) {
const size_t idx = (size_t)(tok * q_heads + h) * head_dim + d;
oref[idx] = o[d];
const float got = h_bf16(oh[idx]);
const float diff = std::fabs(got - o[d]);
if (diff > abs_tol + rel_tol * std::fabs(o[d])) ++nbad;
if (diff > max_err) max_err = diff;
}
}
char nm[160];
std::snprintf(nm, sizeof nm, "%s numeric", name);
ok(nm, nbad == 0,
fmt("max_err=%.5g bad=%d/%d", max_err, nbad, (int)oref.size()));
/* Negative control: corrupt a share of the reference and require the comparison to FAIL -- the
* proof the check has teeth, since a broken (always-passing) comparison would flag nothing. */
for (size_t idx = 0; idx < oref.size(); ++idx)
if ((idx & 7) == 0) oref[idx] += 0.5f;
float nmax = 0.0f; int nbadc = 0;
for (size_t idx = 0; idx < oref.size(); ++idx) {
const float got = h_bf16(oh[idx]);
const float diff = std::fabs(got - oref[idx]);
if (diff > abs_tol + rel_tol * std::fabs(oref[idx])) ++nbadc;
if (diff > nmax) nmax = diff;
}
std::snprintf(nm, sizeof nm, "%s numeric-negctl", name);
ok(nm, nbadc > 0,
fmt("corrupted ref must fail: max_err=%.5g bad=%d", nmax, nbadc));
}
/* ================================================================== a weight's canonical planes
*
* A container holds a weight as the planes of its encoding, row-major (spec §4.1), and a kernel's
@@ -4167,6 +4347,376 @@ static void bf16_tiled_identity(const Plugin& pl, int64_t M, int64_t N, int64_t
ok(nm, all, d);
}
/* logit_softcap, against an f64 evaluation of the same formula.
*
* THE CAP IS THE PARAMETER THE MODEL LIVES IN (Gemma 4's graph issues it at 30.0), so the case
* runs at two values: the model's, and a smaller one that moves every answer -- a kernel that
* hard-wires 30.0, or one that swaps `cap` with its inverse, passes one cap and fails the other.
*
* The inputs are 0, half, one, two and five TIMES THE CAP, signed: x/cap is then an exact small
* half-integer, the f64 oracle cap * tanh(x/cap) is five constants deep, and the only room for an
* error in the comparison is the kernel's own f32 arithmetic and its bf16 store. The tolerance is
* this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
static void logit_softcap_case(const Plugin& pl) {
const char* what = "logit_softcap vs an f64 evaluation of the same formula";
/* Both device legs run the case: bf16 (the gemm's own dtype) and f32 (the 1.3.0 sampling
* chain, where the logits reach the softcap as f32 rows). The f32 leg answers in the
* arithmetic dtype itself, so its oracle compare reads f32, not a bf16 round trip. */
for (const uint32_t dt : { (uint32_t)RAD_BF16, (uint32_t)RAD_F32 }) {
const char* row = dt == RAD_BF16 ? "logit_softcap_bf16" : "logit_softcap_f32";
const size_t es = dt == RAD_BF16 ? 2 : 4;
const RadKernelInfo* r = find(pl, row);
if (!r) { ok(what, false, std::string("row absent: ") + row); return; }
const int64_t M = 7, n = 128;
for (const double capd : { 30.0, 10.0 }) {
std::vector<uint16_t> xh((size_t)M * n);
std::vector<float> xf((size_t)M * n);
std::vector<double> want((size_t)M * n);
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
for (int64_t i = 0; i < M * n; ++i) {
const double mag = mags[(int)((i * 31) % 5)];
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
const double xv = sgn * mag * capd;
xh[(size_t)i] = h_to_bf16((float)xv);
xf[(size_t)i] = (float)xv;
want[(size_t)i] = capd * std::tanh(xv / capd);
}
void* d_x = dalloc((size_t)(M * n) * es);
void* d_o = dalloc((size_t)(M * n) * es);
if (!d_x || !d_o) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_x, dt == RAD_BF16 ? (const void*)xh.data() : (const void*)xf.data(),
(size_t)(M * n) * es, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_x, dt, { M, n }),
T(d_o, dt, { M, n }),
};
std::vector<RadParam> ps = { PI("n", n), PF("cap", capd) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) {
ok(what, false, "launch rc=" + std::to_string(rc) + " cap=" + std::to_string(capd));
return;
}
std::vector<uint16_t> got((size_t)(M * n));
std::vector<float> gotf((size_t)(M * n));
st_memcpy(dt == RAD_BF16 ? (void*)got.data() : (void*)gotf.data(), d_o,
(size_t)(M * n) * es, hipMemcpyDeviceToHost);
double worst = 0.0;
int64_t bad = 0;
for (int64_t i = 0; i < M * n; ++i) {
const double v = dt == RAD_BF16 ? (double)h_bf16(got[(size_t)i])
: (double)gotf[(size_t)i];
const double e = v - want[(size_t)i];
if (std::fabs(e) > worst) worst = std::fabs(e);
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
}
ok(what, bad == 0, std::string(row) + " cap=" + std::to_string(capd) +
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
}
}
}
/* rmsnorm_p, against an f64 evaluation of the weightless normalisation.
*
* THE EPS IS THE PARAMETER THE MODEL LIVES IN (Gemma 4 issues it at 1e-6), so the case runs at
* two values: the model's, and a larger one (1e-2) that moves every answer -- a kernel that hard-
* wires 1e-6, or one that drops the +eps and answers a bare 1/rms, passes the small one and fails
* the large.
*
* The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * rsqrt(mean(x^2) + eps)
* is exact and the only room for an error in the comparison is the kernel's own f32 accumulation
* and its bf16 store. The oracle is computed from the bf16 values the kernel actually reads. The
* tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
static void rmsnorm_p_case(const Plugin& pl) {
const char* what = "rmsnorm_p vs an f64 evaluation of the weightless normalisation";
const RadKernelInfo* r = find(pl, "rmsnorm_p_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = 7, n = 640;
for (const double epsd : { 1e-6, 1e-2 }) {
std::vector<uint16_t> xh((size_t)M * n);
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
for (int64_t i = 0; i < M * n; ++i) {
const double mag = mags[(int)((i * 31) % 5)];
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
xh[(size_t)i] = h_to_bf16((float)(sgn * mag));
}
// f64 oracle from the bf16 values the kernel reads: y = x * rsqrt(mean(x^2) + eps).
std::vector<double> want((size_t)M * n);
for (int64_t m = 0; m < M; ++m) {
double ss = 0.0;
for (int64_t i = 0; i < n; ++i) {
const double v = (double)h_bf16(xh[(size_t)m * n + i]);
ss += v * v;
}
const double s = 1.0 / std::sqrt(ss / (double)n + epsd);
for (int64_t i = 0; i < n; ++i)
want[(size_t)m * n + i] = (double)h_bf16(xh[(size_t)m * n + i]) * s;
}
void* d_x = dalloc(xh.size() * 2);
void* d_o = dalloc((size_t)(M * n) * 2);
if (!d_x || !d_o) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_x, RAD_BF16, { M, n }),
T(d_o, RAD_BF16, { M, n }),
};
std::vector<RadParam> ps = { PI("n", n), PF("eps", epsd) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) {
ok(what, false, "launch rc=" + std::to_string(rc) + " eps=" + std::to_string(epsd));
return;
}
std::vector<uint16_t> got((size_t)(M * n));
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
double worst = 0.0;
int64_t bad = 0;
for (int64_t i = 0; i < M * n; ++i) {
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
if (std::fabs(e) > worst) worst = std::fabs(e);
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
}
ok(what, bad == 0, "eps=" + std::to_string(epsd) +
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
}
}
/* gelu_mul, against an f64 evaluation of the tanh-approximation GELU.
*
* The inputs are a fixed set of magnitudes, signed, for both the gate and the up half, so the f64
* oracle 0.5*g*(1 + tanh(0.7978845608028654*(g + 0.044715*g^3))) * u is exact and the only room for
* an error in the comparison is the kernel's own f32 tanhf and its bf16 store. The oracle is computed
* from the bf16 values the kernel reads; the gate is the first half of the [M, 2n] row. The
* tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
static void gelu_mul_case(const Plugin& pl) {
const char* what = "gelu_mul vs an f64 evaluation of the tanh GELU";
const RadKernelInfo* r = find(pl, "gelu_mul_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = 7, n = 640;
std::vector<uint16_t> gh((size_t)M * 2 * n);
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
for (int64_t i = 0; i < M * 2 * n; ++i) {
const double mag = mags[(int)((i * 31) % 5)];
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
gh[(size_t)i] = h_to_bf16((float)(sgn * mag));
}
// f64 oracle from the bf16 values the kernel reads: y = gelu_tanh(gate) * up, gate the first half.
std::vector<double> want((size_t)M * n);
const double k0 = 0.7978845608028654, k1 = 0.044715;
for (int64_t m = 0; m < M; ++m) {
for (int64_t i = 0; i < n; ++i) {
const double g = (double)h_bf16(gh[(size_t)m * 2 * n + i]);
const double u = (double)h_bf16(gh[(size_t)m * 2 * n + n + i]);
const double gelu = 0.5 * g * (1.0 + std::tanh(k0 * (g + k1 * g * g * g)));
want[(size_t)m * n + i] = gelu * u;
}
}
void* d_g = dalloc(gh.size() * 2);
void* d_o = dalloc((size_t)(M * n) * 2);
if (!d_g || !d_o) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_g, gh.data(), gh.size() * 2, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_g, RAD_BF16, { M, 2 * n }),
T(d_o, RAD_BF16, { M, n }),
};
std::vector<RadParam> ps = { PI("n", n) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) {
ok(what, false, "launch rc=" + std::to_string(rc));
return;
}
std::vector<uint16_t> got((size_t)(M * n));
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
double worst = 0.0;
int64_t bad = 0;
for (int64_t i = 0; i < M * n; ++i) {
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
if (std::fabs(e) > worst) worst = std::fabs(e);
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
}
ok(what, bad == 0, "worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
}
/* scale, against an f64 evaluation of the same multiply.
*
* THE SCALAR IS THE [1] WEIGHT THE MODEL LIVES IN (Gemma 4's per-layer scalar, 0.03-0.99), so the
* case runs at three values: two positive of different magnitude (a kernel that hard-wires one of
* them, or one that squares the scalar, passes one and fails the other) and a negative (a kernel
* that drops the sign passes the positives and fails this).
*
* The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * s is five constants deep
* and the only room for an error in the comparison is the kernel's own f32 arithmetic and its bf16
* store. The tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). The scalar
* is stored as f32 (the kernel's branch reads it as such); a bf16 `s` takes the other branch and is
* not exercised here, which is fine -- the multiply is the same either way. */
static void scale_case(const Plugin& pl) {
const char* what = "scale vs an f64 evaluation of the same multiply";
const RadKernelInfo* r = find(pl, "scale_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = 7, n = 128;
for (const double sv : { 2.0, 0.5, -1.5 }) {
std::vector<uint16_t> xh((size_t)M * n);
std::vector<double> want((size_t)M * n);
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 3.0 };
for (int64_t i = 0; i < M * n; ++i) {
const double mag = mags[(int)((i * 31) % 5)];
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
const double xv = sgn * mag;
xh[(size_t)i] = h_to_bf16((float)xv);
want[(size_t)i] = xv * sv;
}
void* d_x = dalloc(xh.size() * 2);
void* d_s = dalloc(4);
void* d_o = dalloc((size_t)(M * n) * 2);
if (!d_x || !d_s || !d_o) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice);
const float sf = (float)sv;
st_memcpy(d_s, &sf, 4, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_x, RAD_BF16, { M, n }),
T(d_s, RAD_F32, { 1 }),
T(d_o, RAD_BF16, { M, n }),
};
std::vector<RadParam> ps = { PI("n", n) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) {
ok(what, false, "launch rc=" + std::to_string(rc) + " s=" + std::to_string(sv));
return;
}
std::vector<uint16_t> got((size_t)(M * n));
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
double worst = 0.0;
int64_t bad = 0;
for (int64_t i = 0; i < M * n; ++i) {
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
if (std::fabs(e) > worst) worst = std::fabs(e);
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
}
ok(what, bad == 0, "s=" + std::to_string(sv) +
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
}
}
/* rope_bf16, against an f32 mirror of rope_kernel at each ladder width. `den` is the ladder's
* width -- `rot` for `rotary`/absent and `head_dim` for `head` -- so the same kernel body is
* checked under both. The V head is untouched in every case; the absences there would be invisible
* in magnitude (the rotation preserves length) and rel_l2 is what sees the angle itself. */
static void rope_ladder_case(const Plugin& pl) {
const char* what = "rope ladder vs an f32 mirror of rope_kernel at each width";
const RadKernelInfo* r = find(pl, "rope_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = 5, hd = 64, rot = 32, half = rot / 2;
const int64_t n_head = 2, nkv = 1, n_rope = n_head + nkv; /* 3 rotate, one V does not */
const int64_t row = (n_head + 2 * nkv) * hd;
const float theta = 10000.0f;
const int32_t pos[5] = { 0, 1, 7, 128, 4096 };
for (const char* lad : std::initializer_list<const char*>{ nullptr, "rotary", "head" }) {
const int64_t den = (lad && !std::strcmp(lad, "head")) ? hd : rot;
const char* tag = lad ? lad : "absent";
std::vector<uint16_t> saved((size_t)M * row);
for (int64_t i = 0; i < M * row; ++i) {
float v = (float)(((i * 5) % 17) - 8) / 9.0f;
if (i % 13 == 0) v *= 4.0f; /* a few big channels */
saved[(size_t)i] = h_to_bf16(v);
}
void* d_qkv = dalloc(saved.size() * 2);
void* d_pos = dalloc(M * 4);
if (!d_qkv || !d_pos) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_qkv, saved.data(), saved.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_pos, pos, M * 4, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = { T(d_qkv, RAD_BF16, { M, row }), T(d_pos, RAD_I32, { M }) };
std::vector<RadParam> ps = { PI("M", M), PI("head_dim", hd), PI("n_head", n_head),
PI("n_head_kv", nkv), PF("theta", (double)theta),
PF("scale", 1.0), PS("mode", "neox"),
PI("rotary_dim", rot) };
if (lad) ps.push_back(PS("ladder", lad));
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) { ok(what, false, std::string("ladder=") + tag + " rc=" + std::to_string(rc)); return; }
std::vector<uint16_t> got((size_t)M * row);
st_memcpy(got.data(), d_qkv, got.size() * 2, hipMemcpyDeviceToHost);
double num = 0.0, dnorm = 0.0;
int64_t untouched_bad = 0;
for (int64_t m = 0; m < M; ++m) {
const size_t base = (size_t)m * row;
for (int64_t h = 0; h < n_rope; ++h) {
for (int64_t i = 0; i < half; ++i) {
const size_t i0 = base + (size_t)h * hd + i;
/* `head` is HF's proportional RoPE: pair i is (i, i + head_dim/2). */
const size_t i1 = i0 + ((lad && !std::strcmp(lad, "head")) ? hd / 2 : half);
const float x0 = h_bf16(saved[(size_t)i0]), x1 = h_bf16(saved[(size_t)i1]);
const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den);
float s, c;
sincosf((float)pos[(size_t)m] * inv, &s, &c);
const float w0 = x0 * c - x1 * s, w1 = x0 * s + x1 * c;
const float g0 = h_bf16(got[(size_t)i0]), g1 = h_bf16(got[(size_t)i1]);
num += (double)(g0 - w0) * (double)(g0 - w0) +
(double)(g1 - w1) * (double)(g1 - w1);
dnorm += (double)w0 * w0 + (double)w1 * w1;
}
}
for (int64_t e = 0; e < hd; ++e) /* the V head is untouched, so exact */
if (got[base + (size_t)n_rope * hd + e] != saved[base + (size_t)n_rope * hd + e])
++untouched_bad;
}
const double rel = dnorm > 0.0 ? std::sqrt(num / dnorm) : 0.0;
ok(what, rel < 2e-3 && untouched_bad == 0, std::string("ladder=") + tag + " rel_l2=" +
std::to_string(rel) + " vhead-moved=" + std::to_string(untouched_bad));
}
}
/* ---- the two fp8 fusions, against the pair each one replaces -------------------------------- */
//
// THE INVARIANT IS NOT "CLOSE", IT IS BYTE-IDENTICAL, which is why this compares against the
@@ -4432,6 +4982,254 @@ static void fused_quant_fp8_numeric(const Plugin& pl) {
}
}
/* ---- gelu_mul_quant_i8, against gelu_mul + quant_act_i8 -------------------------------------
* Gemma 4 31B's per-rank feed-forward width (10752 of 21504 at two ranks), both batch widths. */
static void gelu_mul_quant_i8_numeric(const Plugin& pl) {
const RadKernelInfo* gm = find(pl, "gelu_mul_bf16");
const RadKernelInfo* qz = find(pl, "quant_act_i8");
const RadKernelInfo* fz = find(pl, "gelu_mul_quant_i8");
if (!gm || !qz || !fz) { ok("gelu_mul_quant_i8 vs its pair", false, "rows absent"); return; }
for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40 }) {
const int64_t n = 10752;
std::vector<uint16_t> hgu((size_t)M * 2 * n);
for (size_t i = 0; i < hgu.size(); ++i)
hgu[i] = h_to_bf16(std::ldexp(1.0f, (int)((i / 512) % 5) - 2) * (0.029f * (float)((i * 41) % 103) - 1.5f));
void* dgu = dalloc(hgu.size() * 2);
void* dy[2] = { dalloc((size_t)M * n * 2), dalloc((size_t)M * n * 2) };
void* dq[2] = { dalloc((size_t)M * n), dalloc((size_t)M * n) };
void* ds[2] = { dalloc((size_t)M * 4), dalloc((size_t)M * 4) };
if (!dgu || !dy[1] || !dq[1] || !ds[1]) { ok("gelu_mul_quant_i8 alloc", false, "hipMalloc failed"); return; }
st_memcpy(dgu, hgu.data(), hgu.size() * 2, hipMemcpyHostToDevice);
int rc = launch_row(gm, { T(dgu, RAD_BF16, { M, 2 * n }), T(dy[0], RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PS("dtype", "bf16") });
if (rc == RAD_OK)
rc = launch_row(qz, { T(dy[0], RAD_BF16, { M, n }), T(dq[0], RAD_I8, { M, n }), T(ds[0], RAD_F32, { M }),
T(nullptr, RAD_F32, {}) },
{ PI("M", M), PI("n", n), PI("group", n), PS("dtype", "bf16") });
if (rc == RAD_OK)
rc = launch_row(fz, { T(dgu, RAD_BF16, { M, 2 * n }), T(dq[1], RAD_I8, { M, n }), T(ds[1], RAD_F32, { M }),
T(dy[1], RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PS("dtype", "bf16") });
const std::string what = "gelu_mul_quant_i8 M=" + std::to_string(M);
if (rc != RAD_OK) { ok((what + " vs gelu_mul + quant_act_i8").c_str(), false, "rc=" + std::to_string(rc)); continue; }
std::vector<uint16_t> y0((size_t)M * n), y1((size_t)M * n);
std::vector<uint8_t> q0((size_t)M * n), q1((size_t)M * n);
std::vector<float> s0((size_t)M), s1((size_t)M);
st_memcpy(y0.data(), dy[0], y0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(y1.data(), dy[1], y1.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(q0.data(), dq[0], q0.size(), hipMemcpyDeviceToHost);
st_memcpy(q1.data(), dq[1], q1.size(), hipMemcpyDeviceToHost);
st_memcpy(s0.data(), ds[0], s0.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(s1.data(), ds[1], s1.size() * 4, hipMemcpyDeviceToHost);
int ny = 0, nq = 0, ns = 0, nz = 0;
for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i];
for (size_t i = 0; i < q0.size(); ++i) { nq += q0[i] != q1[i]; nz += q1[i] != 0; }
for (size_t i = 0; i < s0.size(); ++i) ns += std::memcmp(&s0[i], &s1[i], 4) != 0;
ok((what + " is byte-identical to gelu_mul + quant_act_i8").c_str(), ny == 0 && nq == 0 && ns == 0 && nz > (int)q1.size() / 2,
"bf16 differs " + std::to_string(ny) + ", codes " + std::to_string(nq) + ", scales " + std::to_string(ns) +
", nonzero codes " + std::to_string(nz));
}
}
/* ---- qkv_norm_rope, against the five ops it replaces ------------------------------------------
*
* rmsnorm_p (v, or the raw k under v_from_k), rmsnorm over the q heads and over the k heads, then
* rope over q and over k -- kernel by kernel, against the one dispatch. Both of Gemma 4 31B's
* classes at one rank of two: sliding (head_dim 256, 16 q over 8 kv heads, full rotary, separate v)
* and global (512, 16 over 2, the proportional `head` ladder over 128, k == v), at batch heights
* that put the q/k norms at every width r4d_act_threads answers -- including 256 at head_dim 512,
* where a thread of the standalone norm folds two channels. */
static void qkv_norm_rope_numeric(const Plugin& pl) {
const RadKernelInfo* np = find(pl, "rmsnorm_p_bf16");
const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16");
const RadKernelInfo* rp = find(pl, "rope_bf16");
const RadKernelInfo* fz = find(pl, "qkv_norm_rope_bf16");
if (!np || !nrm || !rp || !fz) { ok("qkv_norm_rope vs its five", false, "rows absent"); return; }
struct Cls { int64_t hd, nq, nkv, rot; const char* ladder; double theta; bool vk; };
for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false },
Cls{ 512, 16, 2, 128, "head", 1000000.0, true } }) {
for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40 }) {
const int64_t QD = cl.nq * cl.hd, KD = cl.nkv * cl.hd;
std::vector<uint16_t> hq((size_t)M * QD), hk((size_t)M * KD), hv((size_t)M * KD);
std::vector<uint16_t> hqw((size_t)cl.hd), hkw((size_t)cl.hd);
std::vector<int32_t> hp((size_t)M);
for (size_t i = 0; i < hq.size(); ++i) hq[i] = h_to_bf16(0.031f * (float)((i * 37) % 97) - 1.4f);
for (size_t i = 0; i < hk.size(); ++i) hk[i] = h_to_bf16(0.027f * (float)((i * 53) % 89) - 1.1f);
for (size_t i = 0; i < hv.size(); ++i) hv[i] = h_to_bf16(0.023f * (float)((i * 29) % 83) - 0.9f);
for (int64_t c = 0; c < cl.hd; ++c) {
hqw[(size_t)c] = h_to_bf16(0.6f + 0.004f * (float)((c * 19) % 51));
hkw[(size_t)c] = h_to_bf16(0.5f + 0.005f * (float)((c * 11) % 47));
}
for (int64_t m = 0; m < M; ++m) hp[(size_t)m] = (int32_t)(1000 + 7 * m);
void* dq[2] = { dalloc(hq.size() * 2), dalloc(hq.size() * 2) };
void* dk[2] = { dalloc(hk.size() * 2), dalloc(hk.size() * 2) };
void* dv[2] = { dalloc(hv.size() * 2), dalloc(hv.size() * 2) };
void* dqw = dalloc(hqw.size() * 2);
void* dkw = dalloc(hkw.size() * 2);
void* dp = dalloc(hp.size() * 4);
if (!dq[1] || !dk[1] || !dv[1] || !dqw || !dkw || !dp) { ok("qkv_norm_rope alloc", false, "hipMalloc failed"); return; }
for (int j = 0; j < 2; ++j) {
st_memcpy(dq[j], hq.data(), hq.size() * 2, hipMemcpyHostToDevice);
st_memcpy(dk[j], hk.data(), hk.size() * 2, hipMemcpyHostToDevice);
st_memcpy(dv[j], hv.data(), hv.size() * 2, hipMemcpyHostToDevice);
}
st_memcpy(dqw, hqw.data(), hqw.size() * 2, hipMemcpyHostToDevice);
st_memcpy(dkw, hkw.data(), hkw.size() * 2, hipMemcpyHostToDevice);
st_memcpy(dp, hp.data(), hp.size() * 4, hipMemcpyHostToDevice);
const double eps = 1e-6, wadd = 0.0;
/* --- the five, in the order the unfused block issues them --- */
int rc = launch_row(np, { T(cl.vk ? dk[0] : dv[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dv[0], RAD_BF16, { M * cl.nkv, cl.hd }) },
{ PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16") });
if (rc == RAD_OK)
rc = launch_row(nrm, { T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }), T(dqw, RAD_BF16, { cl.hd }), T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }) },
{ PI("M", M * cl.nq), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) });
if (rc == RAD_OK)
rc = launch_row(nrm, { T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dkw, RAD_BF16, { cl.hd }), T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }) },
{ PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) });
for (int j = 0; j < 2 && rc == RAD_OK; ++j)
rc = launch_row(rp, { T(j ? dk[0] : dq[0], RAD_BF16, { M, (j ? cl.nkv : cl.nq) * cl.hd }), T(dp, RAD_I32, { M }) },
{ PI("M", M), PI("head_dim", cl.hd), PI("n_head", j ? cl.nkv : cl.nq), PI("n_head_kv", 0),
PF("theta", cl.theta), PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot),
PS("ladder", cl.ladder) });
/* --- the one --- */
if (rc == RAD_OK)
rc = launch_row(fz, { T(dq[1], RAD_BF16, { M, QD }), T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }),
T(dp, RAD_I32, { M }), T(dqw, RAD_BF16, { cl.hd }), T(dkw, RAD_BF16, { cl.hd }) },
{ PI("M", M), PI("head_dim", cl.hd), PI("n_head", cl.nq), PI("n_head_kv", cl.nkv),
PF("theta", cl.theta), PF("eps", eps), PF("scale", 1.0), PS("mode", "neox"),
PI("rotary_dim", cl.rot), PS("ladder", cl.ladder), PF("wadd", wadd),
PI("v_from_k", cl.vk ? 1 : 0), PS("dtype", "bf16") });
const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + " M=" + std::to_string(M);
if (rc != RAD_OK) { ok((what + " vs its five").c_str(), false, "rc=" + std::to_string(rc)); continue; }
int nd = 0, moved = 0;
for (int t = 0; t < 3; ++t) {
void* const* d = t == 0 ? dq : (t == 1 ? dk : dv);
const size_t n = t == 0 ? hq.size() : hk.size();
std::vector<uint16_t> a(n), b(n);
st_memcpy(a.data(), d[0], n * 2, hipMemcpyDeviceToHost);
st_memcpy(b.data(), d[1], n * 2, hipMemcpyDeviceToHost);
const std::vector<uint16_t>& h0 = t == 0 ? hq : (t == 1 ? hk : hv);
for (size_t i = 0; i < n; ++i) { nd += a[i] != b[i]; moved += b[i] != h0[i]; }
}
ok((what + " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2").c_str(), nd == 0 && moved > 0,
"differs " + std::to_string(nd) + ", changed from the input " + std::to_string(moved));
}
}
}
/* ---- rmsnorm_quant_i8, against the chain it replaces ------------------------------------------
*
* Byte-identical, for the reason the fp8 fusions above give, in all three forms a sandwich-norm
* model issues: the plain norm + quantiser (a first block's entry), the junction without a scalar
* (attention -> feed-forward) and with one (feed-forward -> the next layer). The unfused chain is
* rmsnorm(x; w_post) -> add(residual) -> scale -> rmsnorm(residual; w) -> quant_act_i8, run here
* kernel by kernel. bf16 gains, which is what Gemma's checkpoint stores, and two batch heights so
* both of r4d_act_threads' widths a decode step meets are covered (1024 at M <= 32, 512 above). */
static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16");
const RadKernelInfo* ad = find(pl, "add_bf16");
const RadKernelInfo* scl = find(pl, "scale_bf16");
const RadKernelInfo* qz = find(pl, "quant_act_i8");
const RadKernelInfo* rq = find(pl, "rmsnorm_quant_i8");
if (!nrm || !ad || !scl || !qz || !rq) { ok("rmsnorm_quant_i8 vs its chain", false, "rows absent"); return; }
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)40 }) {
const int64_t K = 5376; /* Gemma 4 31B's hidden width: 336 sixteen-byte k steps, not a power of two */
std::vector<uint16_t> hx((size_t)M * K), hr((size_t)M * K), hw((size_t)K), hp((size_t)K);
for (int64_t r = 0; r < M; ++r)
for (int64_t c = 0; c < K; ++c) {
const float m = std::ldexp(1.0f, (int)((c / 384) % 6) - 3);
const float v = m * (0.037f * (float)((r * 29 + c * 13) % 71) - 1.3f);
hx[(size_t)r * K + c] = h_to_bf16(c == (r * 37) % K ? v * 19.0f : v);
hr[(size_t)r * K + c] = h_to_bf16(0.019f * (float)((r * 13 + c * 29) % 67) - 0.6f);
}
for (int64_t c = 0; c < K; ++c) {
hw[(size_t)c] = h_to_bf16(0.004f * (float)((c * 19) % 51) - 0.1f);
hp[(size_t)c] = h_to_bf16(0.9f + 0.003f * (float)((c * 7) % 41));
}
const uint16_t hs = h_to_bf16(0.373f);
void* d_x = dalloc((size_t)M * K * 2);
void* d_w = dalloc((size_t)K * 2);
void* d_p = dalloc((size_t)K * 2);
void* d_sc = dalloc(4);
void* d_t = dalloc((size_t)M * K * 2);
void* d_r[2] = { dalloc((size_t)M * K * 2), dalloc((size_t)M * K * 2) };
void* d_y[2] = { dalloc((size_t)M * K * 2), dalloc((size_t)M * K * 2) };
void* d_q[2] = { dalloc((size_t)M * K), dalloc((size_t)M * K) };
void* d_s[2] = { dalloc((size_t)M * 4), dalloc((size_t)M * 4) };
if (!d_x || !d_w || !d_p || !d_sc || !d_t || !d_r[1] || !d_y[1] || !d_q[1] || !d_s[1]) {
ok("rmsnorm_quant_i8 alloc", false, "hipMalloc failed");
return;
}
st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_w, hw.data(), hw.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_p, hp.data(), hp.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_sc, &hs, 2, hipMemcpyHostToDevice);
const double eps = 1e-6, wadd = 0.0;
const std::vector<RadParam> pn = { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) };
const std::vector<RadParam> pe = { PI("M", M), PI("n", K), PS("dtype", "bf16") };
const std::vector<RadParam> pq = { PI("M", M), PI("n", K), PI("group", K), PS("dtype", "bf16") };
auto compare = [&](const std::string& what, bool res) {
std::vector<uint16_t> y0((size_t)M * K), y1((size_t)M * K), r0((size_t)M * K), r1((size_t)M * K);
std::vector<uint8_t> q0((size_t)M * K), q1((size_t)M * K);
std::vector<float> s0((size_t)M), s1((size_t)M);
st_memcpy(y0.data(), d_y[0], y0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(y1.data(), d_y[1], y1.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(q0.data(), d_q[0], q0.size(), hipMemcpyDeviceToHost);
st_memcpy(q1.data(), d_q[1], q1.size(), hipMemcpyDeviceToHost);
st_memcpy(s0.data(), d_s[0], s0.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(s1.data(), d_s[1], s1.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(r0.data(), d_r[0], r0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(r1.data(), d_r[1], r1.size() * 2, hipMemcpyDeviceToHost);
int ny = 0, nq = 0, ns = 0, nr = 0, nz = 0;
for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i];
for (size_t i = 0; i < q0.size(); ++i) nq += q0[i] != q1[i];
for (size_t i = 0; i < s0.size(); ++i) ns += std::memcmp(&s0[i], &s1[i], 4) != 0;
if (res) for (size_t i = 0; i < r0.size(); ++i) nr += r0[i] != r1[i];
for (size_t i = 0; i < q1.size(); ++i) nz += q1[i] != 0;
ok((what + " M=" + std::to_string(M)).c_str(), ny == 0 && nq == 0 && ns == 0 && nr == 0 && nz > (int)q1.size() / 2,
"bf16 differs " + std::to_string(ny) + ", codes " + std::to_string(nq) + ", scales " +
std::to_string(ns) + ", residual " + std::to_string(nr) + ", nonzero codes " + std::to_string(nz));
};
auto norm_quant = [&](void* src) { /* rmsnorm(src; w) -> quant_act_i8, into slot 0 */
int rc = launch_row(nrm, { T(src, RAD_BF16, { M, K }), T(d_w, RAD_BF16, { K }), T(d_y[0], RAD_BF16, { M, K }) }, pn);
if (rc == RAD_OK)
rc = launch_row(qz, { T(d_y[0], RAD_BF16, { M, K }), T(d_q[0], RAD_I8, { M, K }),
T(d_s[0], RAD_F32, { M }), T(nullptr, RAD_F32, {}) }, pq);
return rc;
};
/* --- the plain form --- */
int rc = norm_quant(d_x);
if (rc == RAD_OK)
rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(nullptr, RAD_BF16, {}), T(d_w, RAD_BF16, { K }),
T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M }), T(d_y[1], RAD_BF16, { M, K }),
T(nullptr, RAD_BF16, {}), T(nullptr, RAD_BF16, {}) }, pn);
if (rc != RAD_OK) ok("rmsnorm_quant_i8 vs rmsnorm + quant_act_i8", false, "rc=" + std::to_string(rc));
else compare("rmsnorm_quant_i8 is byte-identical to rmsnorm + quant_act_i8", false);
/* --- the junction, without and with the scalar --- */
for (const bool with_sc : { false, true }) {
st_memcpy(d_r[0], hr.data(), hr.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_r[1], hr.data(), hr.size() * 2, hipMemcpyHostToDevice);
rc = launch_row(nrm, { T(d_x, RAD_BF16, { M, K }), T(d_p, RAD_BF16, { K }), T(d_t, RAD_BF16, { M, K }) }, pn);
if (rc == RAD_OK)
rc = launch_row(ad, { T(d_r[0], RAD_BF16, { M, K }), T(d_t, RAD_BF16, { M, K }), T(d_r[0], RAD_BF16, { M, K }) }, pe);
if (rc == RAD_OK && with_sc)
rc = launch_row(scl, { T(d_r[0], RAD_BF16, { M, K }), T(d_sc, RAD_BF16, { 1 }), T(d_r[0], RAD_BF16, { M, K }) }, pe);
if (rc == RAD_OK) rc = norm_quant(d_r[0]);
if (rc == RAD_OK)
rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(d_r[1], RAD_BF16, { M, K }), T(d_w, RAD_BF16, { K }),
T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M }), T(d_y[1], RAD_BF16, { M, K }),
T(d_p, RAD_BF16, { K }),
with_sc ? T(d_sc, RAD_BF16, { 1 }) : T(nullptr, RAD_BF16, {}) }, pn);
const std::string what = with_sc ? "rmsnorm_quant_i8 junction with scalar" : "rmsnorm_quant_i8 junction";
if (rc != RAD_OK) ok((what + " vs rmsnorm + add + scale + rmsnorm + quant_act_i8").c_str(), false, "rc=" + std::to_string(rc));
else compare(what + " is byte-identical to its chain", true);
}
}
}
/* THE fp8 lm_head, end to end through its OWN hooks.
*
* The arrangement is the odd one in this library -- E4M3 codes with the row's own bf16 scales in
@@ -11261,6 +12059,41 @@ static void device_phase(const Plugin& pl) {
attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0);
attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 32, "bf16", 1);
attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 1, "bf16", 1);
/* Gemma 4 dense sliding window: decode only, so the window is threaded through -- 1024 is the
* model's window. It exercises the windowed split law and the WIN=1 template the way the
* drafter leg does; max_ctx here is smaller than the window, so the span clamps to the context. */
attn_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 0, 1024);
attn_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 0, 1024);
/* Gemma 4 dense sliding window: the PREFILL leg, the band above q_len 32 that a trunk layer
* needs on the device (libref is an opt-in fallback the engine refuses by default, spec §17).
* The windowed query-tiled prefill kernel; window 1024 is the model's, threaded through to
* instantiate WIN=1 the way the decode leg does. max_ctx here (64) is smaller than the window, so the span clamps to the
* context and the launch is the full-attention form. */
attn_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 32, "fp8_e4m3", 1, 1024);
attn_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 32, "bf16", 1, 1024);
/* Gemma 4 dense global: head_dim 512, full attention. Launch-only cases at prefill q_len 32 and
* decode 1, mirroring the gqa6 leg's pair; the numeric check of the same rows follows. */
attn_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1);
attn_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1);
attn_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
attn_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0);
/* The numeric attention check: the same rows, but with random data and a comparison
* against the inline oracle, plus a negative control. h512 is prefill + decode; h256/gqa2 is
* decode-only (the windowed sliding-window leg, window 1024). */
attn_numeric_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 0);
attn_numeric_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 0);
attn_numeric_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
attn_numeric_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0);
/* The h256/gqa2 PREFILL numeric check. Unlike the decode leg (ctx 64 < window, so the window
* clamps to the context), ctx here is 2048 > window 1024, so the window actually bites: for
* query row 0, pos = 2048-64 = 1984 and the visible keys are [961..1984], so the kernel's
* wlo0 = 961 and tstart = 961/48 = 20 -- exercising both the window mask (keys below 961 are
* masked) and the below-window tile skip (tiles 0..19 are never walked). The oracle's
* visible() is the same bound, so the two agree. */
attn_numeric_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 64, "fp8_e4m3", 1024, 2048);
attn_numeric_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 64, "bf16", 1024, 2048);
attn_numeric_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 1024);
attn_numeric_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 1024);
attn_gq_fold_case(pl, 3, false);
attn_gq_fold_case(pl, 24, false);
attn_gq_fold_case(pl, 3, true);
@@ -12544,6 +13377,31 @@ static void device_phase(const Plugin& pl) {
qsa_block_key_yarn_case(pl);
}
if (sel("logit_softcap_bf16")) {
if (!g_case) std::printf("\nthe final-logit softcap, against the formula it implements\n");
logit_softcap_case(pl);
}
if (sel("rmsnorm_p_bf16")) {
if (!g_case) std::printf("\nthe weightless RMS norm, against the formula it implements\n");
rmsnorm_p_case(pl);
}
if (sel("gelu_mul_bf16")) {
if (!g_case) std::printf("\nthe gelu-gated product, against the formula it implements\n");
gelu_mul_case(pl);
}
if (sel("scale_bf16")) {
if (!g_case) std::printf("\nthe per-tensor scalar scale, against the multiply it implements\n");
scale_case(pl);
}
if (sel("rope_bf16")) {
if (!g_case) std::printf("\nthe rotary ladder, against an f32 mirror of the kernel at each width\n");
rope_ladder_case(pl);
}
if (sel("moe_gemm_w4a8")) {
if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM, against a host decode\n");
/* One geometry; a gate/up pair whose odd experts are half as wide; a down projection
@@ -12763,6 +13621,18 @@ static void device_phase(const Plugin& pl) {
if (!g_case) std::printf("\nthe fp8 fusions, against the pair each one replaces\n");
fused_quant_fp8_numeric(pl);
}
if (sel("gelu_mul_quant_i8")) {
if (!g_case) std::printf("\ngelu_mul_quant_i8, against the pair it replaces\n");
gelu_mul_quant_i8_numeric(pl);
}
if (sel("qkv_norm_rope_bf16")) {
if (!g_case) std::printf("\nqkv_norm_rope, against the five ops it replaces\n");
qkv_norm_rope_numeric(pl);
}
if (sel("rmsnorm_quant_i8")) {
if (!g_case) std::printf("\nrmsnorm_quant_i8, against the chain it replaces\n");
rmsnorm_quant_i8_numeric(pl);
}
/* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape in
* the tree asks these kernels for.
@@ -12843,6 +13713,7 @@ static void device_phase(const Plugin& pl) {
* at every one of the 128 sites, and the generated text is compared byte for byte against a
* build that issues the pair instead. */
skip_pair("ar_rmsnorm_quant_fp8", "two-rank fusion: needs a peer rank");
skip_pair("ar_rmsnorm_quant_i8", "two-rank fusion: needs a peer rank");
dfree_all();
}
+11
View File
@@ -1272,6 +1272,17 @@ extern "C" int r4d_shape_scale_rows(const RadParam* p, int n_p, int operand, Rad
R4D_PICK(l);
}
/* The per-tensor scalar: one [1] weight broadcast over the whole [M, n] extent. `s` is the middle
* operand; its extent is 1, not M (that would be scale_rows) and not M*n (that would be a
* per-element mask). The scalar's dtype is the stream's, so a bf16 or f32 `s` both read. */
extern "C" int r4d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, n), opd(D, 1), opd(D, M, n) };
R4D_PICK(l);
}
extern "C" int r4d_shape_router_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t ne = pi(p, n_p, "n_expert");