radiance 1.5.0

- Gemma 4 31B (PRs #74, #75, #81, #86; sfjes, keptn42): sliding and global attention with their
  own kernels, the assistant head as a drafter that reads the trunk's cache, the vision tower, a
  fused w4a8 decode step, bf16 and compressed-tensors int4 checkpoints, and window snapshots so a
  prefix hit on a sliding-window model resumes instead of prefilling again.
  deploy/compose/gemma4-31b-w4a8.yaml serves keptn42's container on two cards
- ParoQuant (PRs #65, #66, #67; malic): Qwen3.8-27B checkpoints with learned Givens rotations,
  as int4, int5 and MXFP4, imported without re-quantising, the prefill's rotations on the matrix
  cores. deploy/compose/qwen3.8-27b-paro.yaml serves them on one card. A ParoQuant container made
  with the PR builds is refused: convert it again with --reuse <old container>
- Gemma 4 26B-A4B with z-lab's DFlash drafter (PR #88; Perire): arch/gemma4 serves Google's bf16
  checkpoint with the routed experts in block fp8 or bf16 (data/recipes/gemma4-26b-a4b-df*.recipe),
  and libr4d gains its windowed paged attention, the fused sandwich-norm joins, expert_scale and
  the sharded draft head's pair_argmax. A prefill chunk runs as two slices with its all-reduces
  beside the compute, bit-exact with the whole step. The 31B's global layers take the windowed
  attention too: an 11.5K-token prefill on two R9700s in 3.1 s instead of 4.9
- a startup that logs nothing for two minutes says where it waits (#89): the system call (a KFD
  request by name), the library that made it, and its stack, which addr2line resolves against the
  binary
- the prefix cache is kept in VRAM and host memory only (#70): the disk tier wrote every block and
  snapshot a prompt produced, and its copies never outlived the process. --prefix-cache-host-mib
  is renamed --prefix-cache-mib; --prefix-cache-dir and --prefix-cache-disk-mib are removed, and
  startup refuses all three with what replaced them. The compose files no longer mount /data, and
  .env no longer needs RADIANCE_STATE
- --prefix-cache-ttl S (default 3600, 0 never): a conversation no request has used for that long
  leaves the cache, whichever tier holds it; radiance:prefix_cache_expired_total counts them. A
  full host tier now drops its least recently used conversations
- --vision-tower-placement vram|ram (#84): ram keeps an encoder tower in pinned host memory and
  gives its VRAM to the KV cache, read over the link once an image
- timings carry ttft_ms and total_ms (#85): the server's own time from the request body's arrival
  to the first and the last token, queueing and tokenisation included
- a KV-cache recall that found a moved expert with nowhere to go stopped halfway and leaked the
  slots it had already freed: after it every recall failed, the cache stayed short until a
  restart, and requests failed with HTTP 500. A recall now waits for the slots it is owed and
  always finishes
- a tool result or tool-call arguments that are not JSON are no longer refused as nesting past
  1024 levels for their unmatched brackets (#90): only text that parses as JSON is held to the
  bound, since nothing else is parsed into a tree
- the host-pool refusal names the limit that applies to pinned memory (RAM less 1/64 and
  1.5 GiB), not ttm.pages_limit
- --embedding-placement auto, removed in 1.3.0, is refused with what replaced it
- for out-of-tree kernel libraries: gemm_nt_q gains two operands (pb1, pb2, the part bounds), and
  the loader requires identical op schemas, so a library built against 1.4.0 must be rebuilt. For
  architecture plugins, rad_op_declared(b, op) asks whether an op is in the loaded vocabulary
  without declaring it
This commit is contained in:
Deadcode committed 2026-10-13 19:35:16 +02:00
commit b93b531f63
127 files changed
+9609 -4796

No files matched your search

+12 -6
View File
@@ -57,13 +57,9 @@ 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.
# Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode and
# prefill. 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|"
@@ -76,6 +72,10 @@ set(R4D_UNITS
# Six, head_dim 256 and the same 4-token page: the same QSA layers at four ranks, where each KV
# head is replicated across a rank pair. Again four lines that set the ratio and include the body.
"r4d_attn_paged_h256_gqa6_bs4|"
# head_dim 256 and 512 at 1, 2, 4 or 8 queries per KV head with ANY window: Gemma 4's sliding
# (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers. One kernel a geometry for
# every q_len, reading q at any row pitch, which is what attn_paged_qrow is.
"r4d_attn_paged_window|"
"r4d_attn_vit_h72_bf16|"
# An encoder's dense attention (bidirectional, GQA in the workgroup, a two-sided window) and
# the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening.
@@ -156,6 +156,12 @@ set(R4D_UNITS
"r4d_gdn_gated_norm_had_quant_i8|"
"r4d_dequant_w4_bf16|"
"r4d_rowtopk_bf16|"
# The vocab-sharded draft head's cross-rank top-1, one id a row.
"r4d_pair_argmax_f32|"
# Gemma 4's two sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and
# expert_scale: each one kernel for a chain of small ones.
"r4d_norm_join_bf16|"
"r4d_expert_scale_bf16|"
"r4d_dflash_conv_t2_g16_bf16|"
"r4d_dflash_select_bf16|"
# The routed mixture of experts: router, scatter, the grouped block-scaled fp8 GEMM and
+7 -12
View File
@@ -111,21 +111,12 @@ 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.
// h256/gqa6 dispatch instantiates, 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);
@@ -422,8 +413,12 @@ void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers);
// Shards are as even as the word count allows (the first n16 % ws take one more word), so a
// message need not divide by the rank count -- at three it almost never does. Regions A and B sit
// at 0 and the longest shard, so the slot stride must hold twice that. Above this bound the caller
// falls back:
enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 20971520 }; // a 4096-token hidden-5120 prefill chunk
// falls back to the one-shot. The bound guards the kernel's int word offsets (the message, the
// slot stride) and nothing else: 2^28 elements is 2^26 words at fp32. It was 20971520 -- a
// 4096-token chunk of a 5120-wide residual -- which handed every larger prefill chunk back to the
// one-shot and its (ws-1)*N send: an 8192-token chunk at Gemma 4's 2816 is 23M elements at the
// attention's reduce and 46M at the feed-forward's, which carries both branches.
enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456 };
void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0,
long peer_flags1, long my_scratch, long my_flags, long seq_ctrs,
long slot_stride16, long inp, long out, long n_elem, long dtype,
+1 -1
View File
@@ -38,7 +38,7 @@
#include <vector>
#include <chrono>
static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 20971520,
static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 268435456,
"r4d_rows.cpp restates this bound; libr4d changed it");
static_assert(R4D_MAX_RANKS == 8, "the 8-rank entry point names exactly seven peers");
+6 -6
View File
@@ -8,8 +8,8 @@
// 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:
// h256/gqa6 dispatch instantiates, 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"
@@ -128,8 +128,8 @@ extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t 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
// fetch (O_KWIDE) is valid -- it is written for 16 channels = head_dim 256 exactly, and a wider head
// would read past the tile -- so this leg 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.
@@ -157,8 +157,8 @@ 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.
/* The prefill RadArgs wrappers, defined here (not in the h256 dispatch): 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;
-212
View File
@@ -1,212 +0,0 @@
// 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);
}
File diff suppressed because it is too large. Load diff
+87
View File
@@ -0,0 +1,87 @@
/* r4d_expert_scale_bf16.hip -- expert_scale: each routing weight times its expert's own scale, in place.
*
* Gemma 4's router renormalises its top-k and then multiplies each weight by per_expert_scale of
* the expert it chose. Said in the conventional vocabulary that is two launches a MoE layer -- an
* `embed_lookup` of the [n_expert, 1] scale table by the expert ids, then a `mul` into the weights
* -- each a few dozen elements behind a full dispatch at decode. This is the pair as one:
*
* ew[t, k] = bf16( ew[t, k] * scale[ids[t, k]] )
*
* THE CHAIN'S VALUE, BIT FOR BIT: the lookup copies a bf16 scale and the multiply is one f32
* product rounded once to nearest even, which is all this does. An id outside the table reads a
* zero scale, as embed_lookup writes a zero row for an id it does not hold, and the product's sign
* survives it the same way. One thread an element; a decode step is a handful of rows.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r4d_plugin.h"
#include "r4d_launch.h"
#include "rad_plugin.h"
namespace r4d_escale {
struct EscaleArgs {
const int32_t* ids; long long ids_ld;
const uint16_t* sc; /* [n_expert], bf16 */
uint16_t* ew; long long ew_ld;
long long rows;
int k, n_expert;
};
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); }
__device__ __forceinline__ uint16_t f2bf(float f) {
const unsigned u = __float_as_uint(f);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
__global__ __launch_bounds__(256) void expert_scale_kernel(EscaleArgs A) {
const long long e = (long long)blockIdx.x * 256 + threadIdx.x;
if (e >= A.rows * A.k) return;
const long long r = e / A.k;
const int c = (int)(e - r * A.k);
const int id = A.ids[r * A.ids_ld + c];
const float s = (id >= 0 && id < A.n_expert) ? bf2f(A.sc[id]) : 0.0f;
uint16_t* w = A.ew + r * A.ew_ld + c;
*w = f2bf(bf2f(*w) * s);
}
/* [rows, k] with a dense last axis: its rows and row pitch, or false */
static bool rows_k(const RadTensor* t, uint32_t dt, int64_t k, int64_t* rows, int64_t* ld) {
if (!t || t->dtype != dt || t->rank < 1) return false;
if (rad_tensor_lastdim(t) != k || t->stride[t->rank - 1] != 1) return false;
*rows = rad_tensor_rows(t);
*ld = rad_tensor_row_pitch(t);
return *ld >= k || *rows <= 1;
}
} /* namespace r4d_escale */
extern "C" {
/* operands: ids, w_e (the [n_expert] scale table), ew (inout) */
int r4d_rad_expert_scale_bf16(const RadArgs* a, RadStream stream) {
using namespace r4d_escale;
if (!a || a->n_t < 3) return RAD_E_INVAL;
const int64_t k = rad_args_geti_or(a, "top_k", 0), ne = rad_args_geti_or(a, "n_expert", 0);
if (k <= 0 || k > 64 || ne <= 0 || ne > (1 << 20)) return RAD_E_SHAPE;
const RadTensor *I = rad_arg_in(a, 0), *S = rad_arg_in(a, 1), *W = rad_arg_in(a, 2);
if (!I || !S || !W) return RAD_E_INVAL;
if (S->dtype != RAD_BF16 || rad_tensor_numel(S) < ne) return RAD_E_DTYPE;
int64_t ri = 0, li = 0, rw = 0, lw = 0;
if (!rows_k(I, RAD_I32, k, &ri, &li) || !rows_k(W, RAD_BF16, k, &rw, &lw)) return RAD_E_SHAPE;
const int64_t M = rw; /* the step's rows: the stream's view */
if (M <= 0) return RAD_OK;
if (ri < M || M * k > 0x7fffffff) return RAD_E_SHAPE;
EscaleArgs P{};
P.ids = (const int32_t*)I->data; P.ids_ld = li;
P.sc = (const uint16_t*)S->data;
P.ew = (uint16_t*)W->data; P.ew_ld = lw;
P.rows = M; P.k = (int)k; P.n_expert = (int)ne;
const unsigned blocks = (unsigned)((M * k + 255) / 256);
R4D_KLAUNCH(R4D_KNAME(expert_scale_kernel), dim3(blocks), dim3(256), (hipStream_t)stream, P);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
} /* extern "C" */
+15
View File
@@ -0,0 +1,15 @@
/* r4d_launch.h -- the one spelling of a kernel launch in the libr4d units tests/r4d_emu runs on the
* host: the windowed paged attention, pair_argmax, the sandwich-norm joins and expert_scale.
*
* A template kernel's name carries commas, so it goes through R4D_KNAME the way HIP_KERNEL_NAME
* exists for hipLaunchKernelGGL. R4D_KLAUNCH is overridable so the same sources can be driven by a
* host-side SIMT emulator in a test -- the kernels are ordinary C++ once the HIP names are
* supplied. A build never defines it, and gets the triple-chevron launch, which the engine answers
* through hipLaunchKernel on its own queues (docs/PLUGIN.md §5). */
#ifndef R4D_LAUNCH_H
#define R4D_LAUNCH_H
#define R4D_KNAME(...) __VA_ARGS__
#ifndef R4D_KLAUNCH
#define R4D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<<grid, block, 0, stream>>>(__VA_ARGS__)
#endif
#endif
+17 -4
View File
@@ -338,13 +338,18 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel(
// 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.
//
// A ROW IS SPREAD OVER gridDim.y BLOCKS, because a row is a vocabulary shard: 65536 wide at Gemma
// 4's tp 4, and the step's rows are a decode's few. One block a row walked 256 elements a thread of
// tanhf on a handful of CUs -- ~85 us at one row, --profile-ops on an R9700, for 256 KiB of f32.
// Elementwise, so the spread moves no bits.
__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)
for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads)
yr[i] = f32_to_bf16(cap * tanhf(bf2f(xr[i]) / cap));
}
@@ -357,10 +362,16 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32(
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)
for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads)
yr[i] = cap * tanhf(xr[i] / cap);
}
/* The blocks a softcap row is spread over: eight elements a thread, at most 64 blocks a row. */
static uint32_t softcap_blocks_per_row(int n) {
uint32_t b = (uint32_t)((n + kThreads * 8 - 1) / (kThreads * 8));
return b < 1 ? 1 : (b > 64 ? 64 : b);
}
// ---------------------------------------------------------------------------- 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
@@ -915,7 +926,8 @@ extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
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,
hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M, softcap_blocks_per_row(n)),
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);
@@ -929,7 +941,8 @@ extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
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,
hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M, softcap_blocks_per_row(n)),
dim3(kThreads), 0,
(hipStream_t)stream,
(const float*)x, (float*)y, (uint32_t)n, cap,
(uint32_t)x_ld, (uint32_t)y_ld);
+434
View File
@@ -0,0 +1,434 @@
/* r4d_norm_join_bf16.hip -- Gemma 4's sandwich-norm joins, each one kernel instead of a chain of small ones.
*
* A decode step of the 26B-A4B launches ~250 rmsnorms and ~90 adds a step, each a few hundred
* bytes of work behind a full launch: --profile-ops measured 2.0 ms and 0.85 ms of a 16.6 ms step.
* Two places in every layer are pure chains of them:
*
* norm_add_norm the attention's join: t = norm(a) * w_a; x += t; y = norm(x) * w_y
* (post_attention_layernorm, the residual add, pre_feedforward_layernorm)
* join_add_scale the feed-forward's: d' = norm(d) * w_d; r' = norm(r) * w_r;
* j = norm(d' + r') * w_j; x = (x + j) * s; and optionally y = norm(x) * w_n
* (post_feedforward_layernorm_1 and _2, the arms' sum, post_feedforward_layernorm,
* the residual add, layer_scalar -- and the NEXT layer's input_layernorm, or the
* final norm after the last layer, which read the x this writes)
*
* THE SAME FUNCTION AS THE CHAIN, ROUNDING FOR ROUNDING. Every value the chain stores as bf16 is
* rounded to bf16 here at the same point, and every element is computed with libr4d's own
* expression: a norm is bf16((v * rsqrtf(mean(v^2) + eps)) * g), an add bf16(u + v), a scale
* bf16(x * s). The one thing that can differ is the ORDER the sum of squares is added in -- libr4d
* picks its block width from a measured table -- which moves the f32 norm factor by an ulp at most
* and, rarely, a bf16 output by one ulp. The arch plugin asks for these first and falls back to
* the chain where nothing serves them (gemma4.cpp).
*
* AND THE ROUTED ARM'S TWO INPUTS (norm_add_norm_route). The 26B-A4B's router reads norm(x) * w_r *
* hidden^-0.5 and its experts norm(x) * w_e, quantised to E4M3 -- two more launches a layer
* (`rmsnorm`, `rmsnorm_quant_fp8`), each reading back the x norm_add_norm has just written and
* taking the sum of squares norm_add_norm has just taken. The route form writes both from the norm
* factor it holds: the router's row by libr4d's rmsnorm expression, ((x * s) * w) * mult, and the
* experts' codes as libr4d's rmsnorm_quant_fp8 writes them -- the bf16-rounded norm, a scale of
* amax * (1 / 448) a 128 columns (1 where the group is all zero), the value times its reciprocal
* clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256 at slot i / 256, so a group
* is four waves at one slot: a wave's max, then the four.
*
* One 256-thread block a row: a decode step is a handful of rows, so the row is latency-bound and
* a block's three reductions beat seven launches. Values a later stage reuses stay in registers
* (PER a thread, 12 to n = 3072 and kMaxPer = 24 to 6144; the row table says so).
*
* EVERY LOAD IS ISSUED FIRST. A barrier is a fence, so a load written after a reduction waits for
* it: the first version fetched the gains, the residual and the layer scalar phase by phase and
* paid a global round trip for each on top of the reductions -- 17.8 us for join_add_scale and 13.2
* for norm_add_norm at decode under --profile-ops, against ~7 for a launch that does nothing. Now
* the row's every operand is in flight at once, the two arm norms share one barrier pair, and a
* thread holds the elements it touches and no more. Nothing about the arithmetic moved: the same
* expressions in the same order, a sum's extra terms past n were +0.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r4d_plugin.h"
#include "r4d_launch.h"
#include "rad_plugin.h"
namespace r4d_join {
constexpr int kThreads = 256;
constexpr int kWaves = kThreads / 32;
constexpr int kMaxPer = 24; /* elements a thread holds: n <= 6144 */
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); }
/* round to nearest even, as libr4d's f32_to_bf16 */
__device__ __forceinline__ uint16_t f2bf(float f) {
const unsigned u = __float_as_uint(f);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
__device__ __forceinline__ float rbf(float f) { return bf2f(f2bf(f)); }
__device__ __forceinline__ int lane_id() { return (int)(threadIdx.x & 31u); }
__device__ __forceinline__ float shfl_xor(float v, int m) {
return __int_as_float(__builtin_amdgcn_ds_bpermute((lane_id() ^ m) << 2, __float_as_int(v)));
}
/* the block's sum, every thread the same value: a wave butterfly, then the waves in order */
__device__ __forceinline__ float block_sum(float v, float* lds) {
#pragma unroll
for (int d = 16; d >= 1; d >>= 1) v += shfl_xor(v, d);
const int lane = lane_id(), wave = (int)(threadIdx.x >> 5);
__syncthreads(); /* lds is free: the last read of it is done */
if (lane == 0) lds[wave] = v;
__syncthreads();
float s = 0.0f;
#pragma unroll
for (int w = 0; w < kWaves; ++w) s += lds[w];
return s;
}
/* two block sums for one barrier pair: each value takes block_sum's butterfly and wave order */
__device__ __forceinline__ void block_sum2(float& a, float& b, float* lds) {
#pragma unroll
for (int d = 16; d >= 1; d >>= 1) { a += shfl_xor(a, d); b += shfl_xor(b, d); }
const int lane = lane_id(), wave = (int)(threadIdx.x >> 5);
__syncthreads();
if (lane == 0) { lds[wave] = a; lds[kWaves + wave] = b; }
__syncthreads();
float sa = 0.0f, sb = 0.0f;
#pragma unroll
for (int w = 0; w < kWaves; ++w) { sa += lds[w]; sb += lds[kWaves + w]; }
a = sa;
b = sb;
}
__device__ __forceinline__ float norm_factor(float ss, int n, float eps) {
return rsqrtf(ss / (float)n + eps);
}
struct NormArgs {
const uint16_t* a; long long a_ld; /* norm_add_norm: the block output */
const uint16_t* d; long long d_ld; /* join_add_scale: the dense partial */
const uint16_t* r; long long r_ld; /* the routed partial */
uint16_t* x; long long x_ld; /* the residual stream, read and written */
uint16_t* y; long long y_ld; /* norm_add_norm: the next norm's output */
const float* w0; /* w_a, or w_d */
const float* w1; /* w_y, or w_r */
const float* w2; /* w_j */
const float* w3; /* w_n, the next norm's gain (or null) */
const uint16_t* s; /* the layer scalar, bf16, one element */
/* norm_add_norm_route: the router's input, the experts' codes and their scales; the router's
* gain is w2 and the experts' w3 */
uint16_t* rt; long long rt_ld;
uint8_t* q; long long q_ld;
float* qs; long long qs_ld;
float mult;
int n;
float eps;
};
/* t = norm(a) * w_a; x += t; y = norm(x) * w_y -- and with ROUTE, from the same norm of x, the
* router's input norm(x) * w_r * mult and the experts' norm(x) * w_e as E4M3 codes and scales */
template <int PER, bool ROUTE>
__global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) {
__shared__ float lds[kWaves];
__shared__ float gmax[ROUTE ? PER * kWaves : 1];
const int tid = (int)threadIdx.x, n = A.n;
const long long m = (long long)blockIdx.x;
const uint16_t* ar = A.a + m * A.a_ld;
uint16_t* xr = A.x + m * A.x_ld;
uint16_t* yr = A.y + m * A.y_ld;
/* every operand of the row in flight at once: the block output, the residual, the gains */
float av[PER], xv[PER], wa[PER], wy[PER], wr[ROUTE ? PER : 1], we[ROUTE ? PER : 1];
#pragma unroll
for (int k = 0; k < PER; ++k) {
const int i = tid + k * kThreads;
const bool in = i < n;
av[k] = in ? bf2f(ar[i]) : 0.0f;
xv[k] = in ? bf2f(xr[i]) : 0.0f;
wa[k] = in ? A.w0[i] : 0.0f;
wy[k] = in ? A.w1[i] : 0.0f;
if constexpr (ROUTE) {
wr[k] = in ? A.w2[i] : 0.0f;
we[k] = in ? A.w3[i] : 0.0f;
}
}
float ss = 0.0f;
#pragma unroll
for (int k = 0; k < PER; ++k) ss += av[k] * av[k];
const float sa = norm_factor(block_sum(ss, lds), n, A.eps);
ss = 0.0f;
#pragma unroll
for (int k = 0; k < PER; ++k) {
const int i = tid + k * kThreads;
if (i < n) {
const float t = rbf((av[k] * sa) * wa[k]);
xv[k] = rbf(xv[k] + t);
xr[i] = f2bf(xv[k]);
}
ss += xv[k] * xv[k];
}
const float sx = norm_factor(block_sum(ss, lds), n, A.eps);
uint16_t* rr = ROUTE ? A.rt + m * A.rt_ld : nullptr;
#pragma unroll
for (int k = 0; k < PER; ++k) {
const int i = tid + k * kThreads;
if (i < n) {
yr[i] = f2bf((xv[k] * sx) * wy[k]);
if constexpr (ROUTE) {
rr[i] = f2bf(((xv[k] * sx) * wr[k]) * A.mult);
av[k] = rbf((xv[k] * sx) * we[k]); /* the experts' row, as quantised */
}
} else if constexpr (ROUTE) {
av[k] = 0.0f;
}
}
if constexpr (ROUTE) {
/* group 2k + tid / 128 at slot k is waves 0..3 or 4..7: each wave's max, then its four */
const int wave = tid >> 5, half = tid >> 7;
#pragma unroll
for (int k = 0; k < PER; ++k) {
float mx = fabsf(av[k]);
#pragma unroll
for (int d = 16; d >= 1; d >>= 1) mx = fmaxf(mx, shfl_xor(mx, d));
if (lane_id() == 0) gmax[k * kWaves + wave] = mx;
}
__syncthreads();
uint8_t* qr = A.q + m * A.q_ld;
float* sr = A.qs + m * A.qs_ld;
#pragma unroll
for (int k = 0; k < PER; ++k) {
const int i = tid + k * kThreads;
if (i >= n) continue; /* n is whole groups: a group is in or out */
const float* g = gmax + k * kWaves + 4 * half;
const float am = fmaxf(fmaxf(g[0], g[1]), fmaxf(g[2], g[3]));
const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / sc;
const float v = fminf(fmaxf(av[k] * inv, -448.0f), 448.0f);
qr[i] = (uint8_t)(__builtin_amdgcn_cvt_pk_fp8_f32(v, v, 0, false) & 0xff);
if ((tid & 127) == 0) sr[i >> 7] = sc;
}
}
}
/* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s, and with NEXT y = norm(x) * w_n: the
* next layer's input norm taken over the bf16 x this stores, which is what that norm would read. */
template <int PER, bool NEXT>
__global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) {
__shared__ float lds[2 * kWaves];
const int tid = (int)threadIdx.x, n = A.n;
const long long m = (long long)blockIdx.x;
const uint16_t* dr = A.d + m * A.d_ld;
const uint16_t* rr = A.r + m * A.r_ld;
uint16_t* xr = A.x + m * A.x_ld;
/* every operand of the row in flight at once: both arms, the residual, the three gains (four
* with the next norm's) and the layer scalar */
float dv[PER], rv[PER], xo[PER], wd[PER], wr[PER], wj[PER], wn[NEXT ? PER : 1];
const float sc = bf2f(*A.s);
#pragma unroll
for (int k = 0; k < PER; ++k) {
const int i = tid + k * kThreads;
const bool in = i < n;
dv[k] = in ? bf2f(dr[i]) : 0.0f;
rv[k] = in ? bf2f(rr[i]) : 0.0f;
xo[k] = in ? bf2f(xr[i]) : 0.0f;
wd[k] = in ? A.w0[i] : 0.0f;
wr[k] = in ? A.w1[i] : 0.0f;
wj[k] = in ? A.w2[i] : 0.0f;
if constexpr (NEXT) wn[k] = in ? A.w3[i] : 0.0f;
}
float sd2 = 0.0f, sr2 = 0.0f;
#pragma unroll
for (int k = 0; k < PER; ++k) {
sd2 += dv[k] * dv[k];
sr2 += rv[k] * rv[k];
}
block_sum2(sd2, sr2, lds);
const float sd = norm_factor(sd2, n, A.eps);
const float sr = norm_factor(sr2, n, A.eps);
/* the join, kept in dv */
float ss = 0.0f;
#pragma unroll
for (int k = 0; k < PER; ++k) {
const int i = tid + k * kThreads;
if (i < n) {
const float u = rbf((dv[k] * sd) * wd[k]);
const float v = rbf((rv[k] * sr) * wr[k]);
dv[k] = rbf(u + v);
}
ss += dv[k] * dv[k];
}
const float sj = norm_factor(block_sum(ss, lds), n, A.eps);
ss = 0.0f;
#pragma unroll
for (int k = 0; k < PER; ++k) {
const int i = tid + k * kThreads;
if (i < n) {
const float j = rbf((dv[k] * sj) * wj[k]);
const float x1 = rbf(xo[k] + j);
const uint16_t xn = f2bf(x1 * sc);
xr[i] = xn;
rv[k] = bf2f(xn); /* the new x, kept for the next norm */
} else {
rv[k] = 0.0f;
}
if (NEXT) ss += rv[k] * rv[k];
}
if (NEXT) {
const float sn = norm_factor(block_sum(ss, lds), n, A.eps);
uint16_t* yr = A.y + m * A.y_ld;
#pragma unroll
for (int k = 0; k < PER; ++k) {
const int i = tid + k * kThreads;
if (i < n) yr[i] = f2bf((rv[k] * sn) * wn[k]);
}
}
}
/* ------------------------------------------------------------------ host: the launch adapters */
/* [rows..., n] of `dt` with a dense last axis: its row count and pitch, or false */
static bool rows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) {
if (!t || t->dtype != dt || t->rank < 1) return false;
if (rad_tensor_lastdim(t) != n || (t->stride[t->rank - 1] != 1)) return false;
*rows = rad_tensor_rows(t);
*ld = rad_tensor_row_pitch(t);
return *ld >= n || *rows <= 1;
}
static bool rows_of(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) {
return rows_as(t, RAD_BF16, n, rows, ld);
}
static bool gain(const RadTensor* w, int64_t n) {
return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n &&
(w->rank == 0 || w->stride[w->rank - 1] == 1);
}
static int params(const RadArgs* a, int64_t* n, float* eps) {
*n = rad_args_geti_or(a, "n", 0);
*eps = (float)rad_args_getf_or(a, "eps", 1e-6);
if (*n <= 0 || *n > (int64_t)kThreads * kMaxPer) return RAD_E_SHAPE;
return RAD_OK;
}
} /* namespace r4d_join */
extern "C" {
/* operands: a, w_a, x (inout), w_y, y */
int r4d_rad_norm_add_norm_bf16(const RadArgs* a, RadStream stream) {
using namespace r4d_join;
if (!a || a->n_t < 5) return RAD_E_INVAL;
int64_t n = 0;
float eps = 0.0f;
if (int rc = params(a, &n, &eps)) return rc;
const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2),
*Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4);
if (!A_ || !X || !Y) return RAD_E_INVAL;
if (!gain(Wa, n) || !gain(Wy, n)) return RAD_E_DTYPE;
int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0;
if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly))
return RAD_E_SHAPE;
const int64_t M = rx; /* the step's rows: the stream's view */
if (M <= 0) return RAD_OK;
if (ra < M || ry < M || M > 0x7fffffff) return RAD_E_SHAPE;
NormArgs P{};
P.a = (const uint16_t*)A_->data; P.a_ld = la;
P.x = (uint16_t*)X->data; P.x_ld = lx;
P.y = (uint16_t*)Y->data; P.y_ld = ly;
P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data;
P.n = (int)n; P.eps = eps;
if (n <= (int64_t)kThreads * 12)
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, false>), dim3((unsigned)M), dim3(kThreads),
(hipStream_t)stream, P);
else
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<kMaxPer, false>), dim3((unsigned)M),
dim3(kThreads), (hipStream_t)stream, P);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
/* operands: a, w_a, x (inout), w_y, y, w_r, r, w_e, q, qs */
int r4d_rad_norm_add_norm_route_bf16(const RadArgs* a, RadStream stream) {
using namespace r4d_join;
if (!a || a->n_t < 10) return RAD_E_INVAL;
int64_t n = 0;
float eps = 0.0f;
if (int rc = params(a, &n, &eps)) return rc;
if (n % 128 || rad_args_geti_or(a, "group", 0) != 128) return RAD_E_SHAPE;
const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2),
*Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4), *Wr = rad_arg_in(a, 5),
*R = rad_arg_in(a, 6), *We = rad_arg_in(a, 7), *Q = rad_arg_in(a, 8),
*S = rad_arg_in(a, 9);
if (!A_ || !X || !Y || !R || !Q || !S) return RAD_E_INVAL;
if (!gain(Wa, n) || !gain(Wy, n) || !gain(Wr, n) || !gain(We, n)) return RAD_E_DTYPE;
int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0, rr = 0, lr = 0, rq = 0, lq = 0,
rs = 0, ls = 0;
if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly) ||
!rows_of(R, n, &rr, &lr) || !rows_as(Q, RAD_F8E4M3, n, &rq, &lq) ||
!rows_as(S, RAD_F32, n / 128, &rs, &ls))
return RAD_E_SHAPE;
const int64_t M = rx; /* the step's rows: the stream's view */
if (M <= 0) return RAD_OK;
if (ra < M || ry < M || rr < M || rq < M || rs < M || M > 0x7fffffff) return RAD_E_SHAPE;
NormArgs P{};
P.a = (const uint16_t*)A_->data; P.a_ld = la;
P.x = (uint16_t*)X->data; P.x_ld = lx;
P.y = (uint16_t*)Y->data; P.y_ld = ly;
P.rt = (uint16_t*)R->data; P.rt_ld = lr;
P.q = (uint8_t*)Q->data; P.q_ld = lq;
P.qs = (float*)S->data; P.qs_ld = ls;
P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data;
P.w2 = (const float*)Wr->data; P.w3 = (const float*)We->data;
P.mult = (float)rad_args_getf_or(a, "mult", 1.0);
P.n = (int)n; P.eps = eps;
if (n <= (int64_t)kThreads * 12)
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, true>), dim3((unsigned)M), dim3(kThreads),
(hipStream_t)stream, P);
else
R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<kMaxPer, true>), dim3((unsigned)M),
dim3(kThreads), (hipStream_t)stream, P);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
/* operands: d, w_d, r, w_r, w_j, x (inout), s, w_n?, y? -- the last two both or neither */
int r4d_rad_join_add_scale_bf16(const RadArgs* a, RadStream stream) {
using namespace r4d_join;
if (!a || a->n_t < 7) return RAD_E_INVAL;
int64_t n = 0;
float eps = 0.0f;
if (int rc = params(a, &n, &eps)) return rc;
const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2),
*Wr = rad_arg_in(a, 3), *Wj = rad_arg_in(a, 4), *X = rad_arg_in(a, 5),
*Sc = rad_arg_in(a, 6);
if (!D || !R || !X || !Sc) return RAD_E_INVAL;
if (!gain(Wd, n) || !gain(Wr, n) || !gain(Wj, n)) return RAD_E_DTYPE;
if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE;
const RadTensor *Wn = a->n_t > 7 ? rad_arg_in(a, 7) : nullptr,
*Y = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr;
if (!Wn != !Y) return RAD_E_INVAL;
if (Wn && !gain(Wn, n)) return RAD_E_DTYPE;
int64_t rd = 0, ld = 0, rr = 0, lr = 0, rx = 0, lx = 0, ry = 0, ly = 0;
if (!rows_of(D, n, &rd, &ld) || !rows_of(R, n, &rr, &lr) || !rows_of(X, n, &rx, &lx))
return RAD_E_SHAPE;
if (Y && !rows_of(Y, n, &ry, &ly)) return RAD_E_SHAPE;
const int64_t M = rx; /* the step's rows: the stream's view */
if (M <= 0) return RAD_OK;
if (rd < M || rr < M || (Y && ry < M) || M > 0x7fffffff) return RAD_E_SHAPE;
NormArgs P{};
P.d = (const uint16_t*)D->data; P.d_ld = ld;
P.r = (const uint16_t*)R->data; P.r_ld = lr;
P.x = (uint16_t*)X->data; P.x_ld = lx;
P.w0 = (const float*)Wd->data; P.w1 = (const float*)Wr->data; P.w2 = (const float*)Wj->data;
P.s = (const uint16_t*)Sc->data;
if (Y) { P.w3 = (const float*)Wn->data; P.y = (uint16_t*)Y->data; P.y_ld = ly; }
P.n = (int)n; P.eps = eps;
const bool narrow = n <= (int64_t)kThreads * 12;
if (narrow && Y)
R4D_KLAUNCH(R4D_KNAME(join_add_scale_kernel<12, true>), dim3((unsigned)M), dim3(kThreads),
(hipStream_t)stream, P);
else if (narrow)
R4D_KLAUNCH(R4D_KNAME(join_add_scale_kernel<12, false>), dim3((unsigned)M), dim3(kThreads),
(hipStream_t)stream, P);
else if (Y)
R4D_KLAUNCH(R4D_KNAME(join_add_scale_kernel<kMaxPer, true>), dim3((unsigned)M),
dim3(kThreads), (hipStream_t)stream, P);
else
R4D_KLAUNCH(R4D_KNAME(join_add_scale_kernel<kMaxPer, false>), dim3((unsigned)M),
dim3(kThreads), (hipStream_t)stream, P);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
} /* extern "C" */
+105
View File
@@ -0,0 +1,105 @@
/* r4d_pair_argmax_f32.hip -- pair_argmax: the global argmax of a row of gathered (id, value) pairs, written as
* ONE CONTIGUOUS COLUMN of token ids.
*
* WHY THIS OP EXISTS. A vocab-sharded draft head finds each rank's best candidates with `row_topk`
* and moves them with `all_gather`. The gather moves whole 16-byte words a row, and one (int32 id,
* f32 value) pair is 8 bytes, so a rank contributes at least R = 2 (rad_block_mtp_hc.h states the
* same bound). `row_topk_merge` then returns R = 2 columns a row, and a BLOCK drafter's proposal
* is `steps` contiguous ids a sequence -- column 0 of an [S, 2] plane is not that, and nothing in
* libr4d copies a strided i32 column. This reduces the gathered row to its top-1 and writes it
* where the proposal reads it.
*
* It is row_topk_merge at R = 1 with a strided output, rule for rule: the largest value wins, a tie
* goes to the LOWER id, and a pair whose id is negative (a slot a shard could not fill) is skipped.
* A row with no valid pair writes id -1 and value -inf. One wave a row, eight rows a workgroup.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r4d_plugin.h"
#include "r4d_launch.h"
#include "rad_plugin.h"
namespace r4d_pick {
struct PickArgs {
const float* pairs; long long p_rs; /* [M, n, 2]: int32 id bits, then f32 value */
int* tok; long long t_rs;
float* val; long long v_rs; /* optional */
long long rows;
int n;
};
__device__ __forceinline__ int pk_lane() { return (int)(threadIdx.x & 31u); }
__device__ __forceinline__ int pk_xor_i(int v, int m) {
return __builtin_amdgcn_ds_bpermute((pk_lane() ^ m) << 2, v);
}
__device__ __forceinline__ float pk_xor_f(float v, int m) {
return __int_as_float(pk_xor_i(__float_as_int(v), m));
}
/* (v, id) beats (bv, bid)? Larger value, then lower id; an invalid id (< 0) never wins. */
__device__ __forceinline__ bool pk_better(float v, int id, float bv, int bid) {
if (id < 0) return false;
if (bid < 0) return true;
return v > bv || (v == bv && id < bid);
}
__global__ __launch_bounds__(256) void pick_kernel(PickArgs A) {
const long long r = (long long)blockIdx.x * 8 + (threadIdx.x >> 5);
if (r >= A.rows) return; /* uniform across the wave */
const int lane = pk_lane();
const float* row = A.pairs + r * A.p_rs;
float bv = -__builtin_inff();
int bid = -1;
for (int j = lane; j < A.n; j += 32) {
const int id = __float_as_int(row[2 * j]);
const float v = row[2 * j + 1];
if (pk_better(v, id, bv, bid)) { bv = v; bid = id; }
}
#pragma unroll
for (int m = 16; m >= 1; m >>= 1) {
const float ov = pk_xor_f(bv, m);
const int oid = pk_xor_i(bid, m);
if (pk_better(ov, oid, bv, bid)) { bv = ov; bid = oid; }
}
if (lane == 0) {
A.tok[r * A.t_rs] = bid;
if (A.val) A.val[r * A.v_rs] = bv;
}
}
} /* namespace r4d_pick */
/* pairs as [M, n, 2] (rank 3) or [M, 2n] (rank 2), last axes dense; the outputs one element a row
* at their own row pitch. */
extern "C" int r4d_rad_pair_argmax_f32(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
const RadTensor* p = rad_arg_in(a, 0);
const RadTensor* t = rad_arg_in(a, 1);
const RadTensor* v = rad_arg_in(a, 2);
if (!p || !t) return RAD_E_INVAL;
if (p->dtype != RAD_F32 || t->dtype != RAD_I32 || (v && v->dtype != RAD_F32)) return RAD_E_DTYPE;
const long long n = rad_args_geti_or(a, "n", 0);
if (n <= 0 || p->rank < 2) return RAD_E_SHAPE;
if (p->rank == 3) {
if (p->shape[1] < n || p->shape[2] != 2 || p->stride[2] != 1 || p->stride[1] != 2) return RAD_E_SHAPE;
} else if (p->rank == 2) {
if (p->shape[1] < 2 * n || p->stride[1] != 1) return RAD_E_SHAPE;
} else {
return RAD_E_SHAPE;
}
const int64_t rows = p->shape[0];
if (rows == 0) return RAD_OK;
if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE;
r4d_pick::PickArgs A{};
A.pairs = (const float*)p->data; A.p_rs = p->stride[0];
A.tok = (int*)t->data; A.t_rs = t->rank >= 2 ? t->stride[0] : 1;
A.val = v ? (float*)v->data : nullptr;
A.v_rs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0;
A.rows = rows;
A.n = (int)n;
R4D_KLAUNCH(R4D_KNAME(r4d_pick::pick_kernel), dim3((unsigned)((rows + 7) / 8)), dim3(256),
(hipStream_t)stream, A);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
+40 -9
View File
@@ -36,6 +36,14 @@ enum {
* caller selecting an entry point by hand would make. */
R4D_PRIO_ATTN_DECODE = 70,
R4D_PRIO_ATTN_PREFILL = 60,
/* The windowed kernels (r4d_attn_paged_window.hip) serve every q_len, so where their geometry
* meets another leg's -- h256 at gqa 2 -- they match in both of that leg's bands, and rank
* below both: timed by rad-kbench on two R9700s at the 31B's shapes (window 1024, fp8 cache),
* the h256/gqa2 decode kernel takes 0.26-0.71 of the windowed kernel's time at q_len 1..32 and
* its prefill kernel 0.43-0.67 at 33..512, a bf16 cache the same order. The windowed rows keep
* that geometry's non-causal band past q_len 32, and attn_paged_qrow, which no other kernel
* serves. */
R4D_PRIO_ATTN_WINDOW = 50,
/* At M<=16 with K%256==0 both bf16 skinny rows match and the m16 (dot2) kernel is taken.
* The m64 WMMA kernel is faster on every shape measured, so a caller that wants it at low M
@@ -97,6 +105,37 @@ int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs*);
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*);
/* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not
* (r4d_attn_paged_window.hip): one entry point a geometry and cache dtype, serving every q_len and
* reading q at any row pitch, so the same entry points serve attn_paged and attn_paged_qrow. */
int r4d_rad_attn_window_h256_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa2_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa4_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa2_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa4_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_fp8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*);
/* The top-1 of a row of all-gathered (id, value) pairs, written one id a row: the vocab-sharded
* draft head's merge (r4d_pair_argmax_f32.hip). */
int r4d_rad_pair_argmax_f32(const RadArgs*, RadStream);
/* Gemma 4's two sandwich-norm joins, each one kernel for a chain of rmsnorm / add / mul_weight
* launches (r4d_norm_join_bf16.hip), and expert_scale, the embed_lookup + mul pair that scales
* each routing weight by its expert's scale (r4d_expert_scale_bf16.hip). */
int r4d_rad_norm_add_norm_bf16 (const RadArgs*, RadStream);
int r4d_rad_norm_add_norm_route_bf16(const RadArgs*, RadStream);
int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream);
int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream);
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
@@ -122,15 +161,6 @@ 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);
@@ -600,6 +630,7 @@ 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_pair_argmax (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_quant_act_i8 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_had_quant_act_i8 (const RadParam*, int, int operand, RadOpdDesc*);
+234 -59
View File
@@ -71,7 +71,7 @@
/* libr4d's R4D_AR_TWOSHOT_WIDE_MAX_ELEMS, restated because this file must not include r4d.h.
* r4d_ar_entry.hip static_asserts the two against each other. */
#define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 20971520
#define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 268435456
/* The largest message, in elements, a 4- or 8-rank exact all-reduce keeps on the one-shot; above it
* the two-shot rows take it. 1 MiB of a 16-bit payload. The one-shot sends (ws-1)*N bytes a rank
@@ -2110,6 +2110,80 @@ static const RadOperandSpec oMergeTopk[] = {
{ "cand_val", RAD_OPD_OUT, 0 },
};
/* ------------------------------------------------------- pair_argmax, the joins, expert_scale
*
* pair_argmax is libref's schema restated field for field. The other four ops are this library's
* own, and attn_paged_qrow, whose schema is attn_paged's above: libref has no row for any of them
* ON PURPOSE. A reference row would resolve them wherever this library is not loaded -- a CPU-only
* build, a --kernels list without it -- and the architecture's fallback to the chain each one
* replaces would never be taken. docs/OPS.md carries all six, which is what the ops_doc test holds
* them to. */
static const RadParamSpec pPairArgmax[] = {
P_INT("M"),
P_INT("n"),
P_STR("dtype"),
};
static const RadOperandSpec oPairArgmax[] = {
{ "pairs", RAD_OPD_IN, 0 },
{ "idx", RAD_OPD_OUT, 0 },
{ "val", RAD_OPD_OUT, 1 },
};
static const RadParamSpec pNormJoin[] = {
P_INT("M"),
P_INT("n"),
P_F64("eps"),
P_STR("dtype"),
};
static const RadOperandSpec oNormAddNorm[] = {
{ "a", RAD_OPD_IN, 0 },
{ "w_a", RAD_OPD_WEIGHT, 0 },
{ "x", RAD_OPD_INOUT, 0 },
{ "w_y", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pNormAddNormRoute[] = {
P_INT("M"),
P_INT("n"),
P_F64("eps"),
P_STR("dtype"),
P_F64("mult"),
P_INT("group"),
};
static const RadOperandSpec oNormAddNormRoute[] = {
{ "a", RAD_OPD_IN, 0 },
{ "w_a", RAD_OPD_WEIGHT, 0 },
{ "x", RAD_OPD_INOUT, 0 },
{ "w_y", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
{ "w_r", RAD_OPD_WEIGHT, 0 },
{ "r", RAD_OPD_OUT, 0 },
{ "w_e", RAD_OPD_WEIGHT, 0 },
{ "q", RAD_OPD_OUT, 0 },
{ "qs", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oJoinAddScale[] = {
{ "d", RAD_OPD_IN, 0 },
{ "w_d", RAD_OPD_WEIGHT, 0 },
{ "r", RAD_OPD_IN, 0 },
{ "w_r", RAD_OPD_WEIGHT, 0 },
{ "w_j", RAD_OPD_WEIGHT, 0 },
{ "x", RAD_OPD_INOUT, 0 },
{ "s", RAD_OPD_WEIGHT, 0 },
{ "w_n", RAD_OPD_WEIGHT, 1 },
{ "y", RAD_OPD_OUT, 1 },
};
static const RadParamSpec pExpertScale[] = {
P_INT("M"),
P_INT("n_expert"),
P_INT("top_k"),
P_STR("dtype"),
};
static const RadOperandSpec oExpertScale[] = {
{ "ids", RAD_OPD_IN, 0 },
{ "w_e", RAD_OPD_WEIGHT, 0 },
{ "ew", RAD_OPD_INOUT, 0 },
};
#define SCHEMA(op, p, o, doc) { (op), ROW(p), ROW(o), (doc) }
static const RadOpSchema kSchemas[] = {
@@ -2302,6 +2376,17 @@ static const RadOpSchema kSchemas[] = {
"paged causal attention, varlen. The ranged parameter is q_len, not M: one query row "
"at decode, up to 64/gqa at a speculative verify, thousands in a prefill chunk, and "
"libr4d has a different kernel for each band."),
/* attn_paged under a name of its own, for a q read at its own row pitch. The windowed kernels
* (r4d_attn_paged_window.hip) read q where a fused [q|k|v] projection left it; the other
* attn_paged kernels, this library's included, read q dense and refuse the slice
* (RAD_E_STRIDE), which stops the engine at the first step. Under attn_paged, whichever row
* resolved would decide whether the slice works; under this name the op resolves to a kernel
* that takes it or to nothing, and the architecture lifts q into a dense block for attn_paged
* where it is nothing. */
SCHEMA("attn_paged_qrow", pAttnPaged, oAttnPaged,
"attn_paged, parameter for parameter and value for value, with q read at its own row "
"pitch: a column slice of a wider row -- the q part of a fused [q|k|v] projection -- read "
"where it lies rather than lifted into a dense block first."),
SCHEMA("attn_paged_gate_quant", pAttnPagedGq, oAttnPagedGq,
"attn_paged followed by gate_quant_fp8 over its output, in the split-KV merge: each "
"merged (token, head) row is gated, rounded, written to `out` and quantised to E4M3 "
@@ -2607,6 +2692,32 @@ static const RadOpSchema kSchemas[] = {
"token order (with the shared arm folded when present) ARE the all-reduce's message, "
"and the gated residual's write follows the reduction. Both wires at two ranks, the "
"exact one at four."),
SCHEMA("pair_argmax", pPairArgmax, oPairArgmax,
"idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in "
"the first f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties "
"to the lower id, a negative id skipped, -1 and -inf where nothing is valid. "
"row_topk_merge at R = 1, written one element a row at the output's own pitch."),
SCHEMA("norm_add_norm", pNormJoin, oNormAddNorm,
"t = rmsnorm(a) * w_a; x = x + t; y = rmsnorm(x) * w_y, over [M, n] rows; every value "
"the unfused rmsnorm, add, rmsnorm chain stores is rounded to the activation dtype at "
"the same point. A post-norm, the residual add and the next pre-norm (Gemma's "
"sandwich)."),
SCHEMA("norm_add_norm_route", pNormAddNormRoute, oNormAddNormRoute,
"norm_add_norm, then from the same rmsnorm of the x it writes r = rmsnorm(x) * w_r * "
"mult and the E4M3 codes q of rmsnorm(x) * w_e with an f32 scale qs per (row, `group` "
"columns): rmsnorm_quant_fp8's codes, taken over the bf16-rounded norm. A MoE layer's "
"router input and its experts' fp8 input, written by the attention join that already "
"holds the norm."),
SCHEMA("join_add_scale", pNormJoin, oJoinAddScale,
"x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s, over [M, n] rows, s "
"one element; and with w_n and y, y = rmsnorm(x) * w_n over the x written. Rounding "
"where the unfused chain rounds. Two arms' post-norms, their sum, its norm, the residual "
"add, a per-layer scalar and the next layer's input norm (Gemma 4's feed-forward "
"join)."),
SCHEMA("expert_scale", pExpertScale, oExpertScale,
"ew[t, k] = ew[t, k] * w_e[ids[t, k]] over [M, top_k], w_e an [n_expert] table, an id "
"outside it reading 0; one product rounded once, so the embed_lookup + mul pair's value "
"bit for bit. Gemma 4's per_expert_scale on the renormalised routing weights."),
};
/* ================================================================================ constraints
@@ -2726,25 +2837,31 @@ 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"),
};
/* THE WINDOWED KERNELS (r4d_attn_paged_window.hip): head_dim 256 and 512, 1/2/4/8 queries per KV
* head, ANY window, causal or not -- Gemma 4's sliding layers are h256/gqa2 with a 1024-token
* window, its full layers h512 at gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8). One kernel serves every
* q_len -- decode, verify and prefill, splitting the key range where there are too few tiles to
* fill the card -- so `q_len` carries no constraint and cuts no band. `causal` and `window` are
* runtime fields of the kernel; block_size is the kernel's (RAD_DERIVED): 16.
*
* h256 AT gqa 4 AND 8 TAKE A WINDOW ONLY (C_GE 1): their window-0 band is the gqa4 / gqa8 legs'
* above (Qwen3.5-0.8B, the routed 35B-A3B), which these rows leave to them. At h256/gqa2 the
* rows overlap the sliding leg's two bands and rank below it (R4D_PRIO_ATTN_WINDOW says why);
* every other geometry here is these rows' alone. */
#define R4D_WIN_C(NAME, HD, G, KV, WMIN) \
static const RadConstraint NAME[] = { \
C_EQ("head_dim", HD), C_EQ("gqa", G), C_EQ("block_size", 16), C_GE("causal", 0), \
C_GE("window", WMIN), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", KV), \
};
R4D_WIN_C(cWinH256G1Bf16, 256, 1, "bf16", 0) R4D_WIN_C(cWinH256G1Fp8, 256, 1, "fp8_e4m3", 0)
R4D_WIN_C(cWinH256G2Bf16, 256, 2, "bf16", 0) R4D_WIN_C(cWinH256G2Fp8, 256, 2, "fp8_e4m3", 0)
R4D_WIN_C(cWinH256G4Bf16, 256, 4, "bf16", 1) R4D_WIN_C(cWinH256G4Fp8, 256, 4, "fp8_e4m3", 1)
R4D_WIN_C(cWinH256G8Bf16, 256, 8, "bf16", 1) R4D_WIN_C(cWinH256G8Fp8, 256, 8, "fp8_e4m3", 1)
R4D_WIN_C(cWinH512G1Bf16, 512, 1, "bf16", 0) R4D_WIN_C(cWinH512G1Fp8, 512, 1, "fp8_e4m3", 0)
R4D_WIN_C(cWinH512G2Bf16, 512, 2, "bf16", 0) R4D_WIN_C(cWinH512G2Fp8, 512, 2, "fp8_e4m3", 0)
R4D_WIN_C(cWinH512G4Bf16, 512, 4, "bf16", 0) R4D_WIN_C(cWinH512G4Fp8, 512, 4, "fp8_e4m3", 0)
R4D_WIN_C(cWinH512G8Bf16, 512, 8, "bf16", 0) R4D_WIN_C(cWinH512G8Fp8, 512, 8, "fp8_e4m3", 0)
#undef R4D_WIN_C
/* 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
@@ -3023,6 +3140,21 @@ static const RadConstraint cDflashSelect[] = {
C_GE("steps", 1), C_GE("top_k", 1), C_LE("top_k", 32),
C_DIV("rank", 32), C_LE("rank", 512), C_IN("dtype", "bf16"),
};
/* The sandwich-norm joins hold 24 elements a thread over a 256-thread block (n <= 6144), and the
* route form quantises in whole 128-column groups. pair_argmax takes any row; expert_scale's top_k
* is the router's, at most 64. */
static const RadConstraint cNormJoin[] = {
C_GE("n", 1), C_LE("n", 6144), C_IN("dtype", "bf16"),
};
static const RadConstraint cNormJoinRoute[] = {
C_GE("n", 128), C_LE("n", 6144), C_DIV("n", 128), C_EQ("group", 128), C_IN("dtype", "bf16"),
};
static const RadConstraint cPairArgmax[] = {
C_GE("n", 1), C_IN("dtype", "f32 fp32"),
};
static const RadConstraint cExpertScale[] = {
C_GE("top_k", 1), C_LE("top_k", 64), C_GE("n_expert", 1), C_IN("dtype", "bf16"),
};
/* ---- the routed mixture of experts ----------------------------------------------------------
*
@@ -4084,7 +4216,7 @@ static const RadKernelInfo kKernels[] = {
r4d_shape_unary },
{ "logit_softcap_bf16", "logit_softcap", "elem",
"cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent",
"cap * tanh(x / cap), the final-logit softcap, a row spread over up to 64 blocks",
"any extent; contiguous in and out",
"bf16 in and out, fp32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
@@ -4093,7 +4225,7 @@ static const RadKernelInfo kKernels[] = {
r4d_shape_unary },
{ "logit_softcap_f32", "logit_softcap", "elem",
"cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent",
"cap * tanh(x / cap), the final-logit softcap, a row spread over up to 64 blocks",
"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,
@@ -4537,43 +4669,37 @@ 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 },
/* The windowed kernels (r4d_attn_paged_window.hip), under attn_paged and, the same launches with
* the same constraints, under attn_paged_qrow. The qrow rows carry no opd_shape: libref has no row
* for that op, so there is no oracle to run them against, and tests/r4d_emu's attention cases
* already take q as a pitched slice of a wider row. */
#define R4D_WIN_ROW(HD, G, KVN, KVS, C, KVDOC) \
{ "attn_window_h" #HD "_gqa" #G "_" #KVN, "attn_paged", "attn", \
"paged attention, any window, causal or not; split-KV with a merge where tiles are few", \
"head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \
"bf16 query, " KVDOC " kv cache, bf16 out, f32 partials", \
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_WINDOW, \
ROW(C), NOTUNE, \
nullptr, nullptr, r4d_rad_attn_window_h##HD##_gqa##G##_##KVS, \
r4d_rad_attn_window_h##HD##_scratch, \
nullptr, nullptr, \
r4d_shape_attn_paged }, \
{ "attn_qrow_h" #HD "_gqa" #G "_" #KVN, "attn_paged_qrow", "attn", \
"paged attention reading q at its own row pitch, any window, causal or not", \
"head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \
"bf16 query (any row pitch), " KVDOC " kv cache, bf16 out, f32 partials", \
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, \
ROW(C), NOTUNE, \
nullptr, nullptr, r4d_rad_attn_window_h##HD##_gqa##G##_##KVS, \
r4d_rad_attn_window_h##HD##_scratch, \
nullptr, nullptr, nullptr },
#define R4D_WIN_PAIR(HD, GQ) \
R4D_WIN_ROW(HD, GQ, bf16kv, bf16, cWinH##HD##G##GQ##Bf16, "bf16") \
R4D_WIN_ROW(HD, GQ, fp8kv, fp8, cWinH##HD##G##GQ##Fp8, "fp8-e4m3 (per-(seq,head) descales)")
R4D_WIN_PAIR(256, 1) R4D_WIN_PAIR(256, 2) R4D_WIN_PAIR(256, 4) R4D_WIN_PAIR(256, 8)
R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, 8)
#undef R4D_WIN_PAIR
#undef R4D_WIN_ROW
{ "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
@@ -6150,6 +6276,55 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_dflash_select, nullptr, nullptr, nullptr,
r4d_shape_dflash_select },
/* pair_argmax, the sandwich-norm joins and expert_scale. NO opd_shape on the joins and
* expert_scale: libref has no row for them (see their schemas), so there is no oracle to run them
* against; tests/r4d_emu runs these kernels' source on the host and holds them to the chain they
* replace, bit for bit. pair_argmax is described as libref describes it, so rad-kbench runs it
* against the oracle. */
{ "pair_argmax_f32", "pair_argmax", "select",
"the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped",
"any M and n; one wave a row; the outputs one element a row at their own pitch",
"f32 pairs (int32 id bits, f32 value), i32 idx, f32 val",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cPairArgmax), NOTUNE,
nullptr, nullptr, r4d_rad_pair_argmax_f32, nullptr, nullptr, nullptr,
r4d_shape_pair_argmax },
{ "norm_add_norm_bf16", "norm_add_norm", "norm",
"post-norm, residual add, next pre-norm: one block a row, rounding where the chain rounds",
"n <= 6144, any M, row pitches honoured",
"bf16 activations, f32 gains",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cNormJoin), NOTUNE,
nullptr, nullptr, r4d_rad_norm_add_norm_bf16, nullptr, nullptr, nullptr,
nullptr },
{ "norm_add_norm_route_bf16", "norm_add_norm_route", "norm",
"norm_add_norm, and the routed arm's router input and fp8 expert input from the same norm",
"n <= 6144 in whole 128-column groups, any M, row pitches honoured",
"bf16 activations, f32 gains; E4M3 codes with an f32 scale a 128 columns",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cNormJoinRoute), NOTUNE,
nullptr, nullptr, r4d_rad_norm_add_norm_route_bf16, nullptr, nullptr, nullptr,
nullptr },
{ "join_add_scale_bf16", "join_add_scale", "norm",
"two arms' post-norms, sum, norm, residual add, layer scalar: one block a row",
"n <= 6144, any M, row pitches honoured",
"bf16 activations, f32 gains, bf16 scalar",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cNormJoin), NOTUNE,
nullptr, nullptr, r4d_rad_join_add_scale_bf16, nullptr, nullptr, nullptr,
nullptr },
{ "expert_scale_bf16", "expert_scale", "moe",
"routing weight times its expert's scale, in place: one thread an element",
"any M, top_k <= 64, row pitches honoured",
"i32 ids, bf16 table and weights",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cExpertScale), NOTUNE,
nullptr, nullptr, r4d_rad_expert_scale_bf16, nullptr, nullptr, nullptr,
nullptr },
};
/* ================================================================================== the exports */
+22 -15
View File
@@ -393,6 +393,7 @@ static void cross_check(const Plugin& pl) {
/* The libr4d orderings the integer priority has to preserve. */
int p_ts = -1, p_os = -1, p_dec = -1, p_pre = -1, p_m16 = -1, p_m64 = -1, p_bt = -1;
int p_g2dec = -1, p_g2pre = -1, p_g2win = -1;
for (int k = 0; k < nk; ++k) {
const RadKernelInfo* r = pl.kernel_at(k);
if (!std::strcmp(r->name, "ar_twoshot_4rank_exact")) p_ts = r->priority;
@@ -402,12 +403,17 @@ static void cross_check(const Plugin& pl) {
if (!std::strcmp(r->name, "gemm_bf16_nt_m16")) p_m16 = r->priority;
if (!std::strcmp(r->name, "gemm_bf16_nt_m64")) p_m64 = r->priority;
if (!std::strcmp(r->name, "gemm_bf16_nt_tiled")) p_bt = r->priority;
if (!std::strcmp(r->name, "attn_decode_h256_gqa2_fp8kv")) p_g2dec = r->priority;
if (!std::strcmp(r->name, "attn_prefill_h256_gqa2_fp8kv")) p_g2pre = r->priority;
if (!std::strcmp(r->name, "attn_window_h256_gqa2_fp8kv")) p_g2win = r->priority;
}
ok("two-shot all-reduce outranks one-shot (libr4d row order)", p_ts > p_os && p_ts > 0);
ok("paged decode outranks paged prefill in the shared band", p_dec > p_pre && p_dec > 0);
ok("gemm_bf16_nt_m16 outranks _m64 (libr4d row order, see the ladder)", p_m16 > p_m64);
ok("gemm_bf16_nt_tiled outranks _m64 and not _m16 (M > 64 is its band)",
p_bt > p_m64 && p_bt < p_m16);
ok("the h256/gqa2 legs outrank the windowed kernel in both their bands",
p_g2win > 0 && p_g2dec > p_g2win && p_g2pre > p_g2win);
std::printf("\n");
}
@@ -12010,7 +12016,7 @@ static void ar_three_rank(const Plugin& pl, const std::vector<int>& devs, const
* sums correctly. This one gives every element its own value, so a word reduced by the wrong
* owner, gathered from the wrong slot or dropped at a short shard's end is a wrong number at a
* known index. The sizes walk the uneven split: words % 3 of 0, 1 and 2, from a 16-word message
* to the row's 20971520-element ceiling, in place (how every block issues it) and once out of
* to past the old 20971520 ceiling, in place (how every block issues it) and once out of
* place, back to back on ONE instance so the slot parity and the changing block count are
* exercised the way a step's mixed messages exercise them. The oracle is the fold the kernel
* claims -- fp32 in ascending rank order, rounded once -- so it is bit for bit, and so it is also
@@ -12089,8 +12095,9 @@ static void ar_three_rank_pattern(const Plugin& pl, const std::vector<int>& devs
struct Run { const char* dtype; std::vector<int64_t> sizes; int oop; };
const std::vector<Run> runs = {
/* bf16, the residual: words = numel / 8. 2048 x 2048 rows is words % 3 == 2, x 2049 is
* 0, x 2050 is 1; 128 is 16 words (1), 24008 is 3001 (1); 20971520 the ceiling (1). */
{ "bf16", { 4194304, 128, 4196352, 24008, 4198400, 20971520, 4194304 }, 2 },
* 0, x 2050 is 1; 128 is 16 words (1), 24008 is 3001 (1); 20971520 the old ceiling (1);
* 46137344, Gemma 4's feed-forward reduce at an 8192-token chunk, past it (1). */
{ "bf16", { 4194304, 128, 4196352, 24008, 4198400, 20971520, 46137344, 4194304 }, 2 },
/* fp32: words = numel / 4. 8196 -> 2049 (0), 4100 -> 1025 (2), 1048580 -> 262145 (2). */
{ "fp32", { 8196, 4100, 1048580 }, 0 },
};
@@ -12579,19 +12586,19 @@ static void device_phase(const Plugin& pl) {
* 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);
/* Gemma 4 dense global: head_dim 512, full attention, on the windowed kernel -- one row for
* every q_len, so a prefill-shaped launch (q_len 32) and a decode one (1) of the same row; the
* numeric check of both follows. */
attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1);
attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1);
attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
attn_case(pl, "attn_window_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);
* against the inline oracle, plus a negative control. */
attn_numeric_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 0);
attn_numeric_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 0);
attn_numeric_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
attn_numeric_case(pl, "attn_window_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
+15
View File
@@ -1519,6 +1519,21 @@ extern "C" int r4d_shape_row_topk_merge(const RadParam* p, int n_p, int operand,
R4D_PICK(l);
}
/* pair_argmax (r4d_pair_argmax_f32.hip): row_topk_merge at R = 1 over `n` gathered pairs, so the
* same f32 plane and the same reading of it -- the value lane draws proper floats, the id lane
* their bit patterns, a negative one a pad and a positive one a legal id -- and one id and one
* value a row out. */
extern "C" int r4d_shape_pair_argmax(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 RadOpdDesc l[] = {
opd((uint32_t)RAD_F32, M, n, 2),
opd((uint32_t)RAD_I32, M),
opd((uint32_t)RAD_F32, M),
};
R4D_PICK(l);
}
/* ==========================================================================================
* Quantisation, the norms and the fusions (shims in r4d_quant.cpp and r4d_fp8.cpp).
*