libr4d, arch: the 31B and DFlash2 with fewer launches a step, same bytes

Attention reads q and the gqa-8 drafter's KV in place (attn_paged_qrow); the 31B's attention
prologue stores k and v itself (qkv_norm_rope_kv_store); DFlash2's norm/rope/cache-store chains
and add-then-norm pairs run as one launch each. Carries the launch-cliff padding until that PR
merges.

Squashed from:

- libr4d: attn_paged_qrow on the split-KV decode kernel -- h256/gqa2, and h128/gqa8 by two groups a kv head
- arch: the 31B's sliding layers and its drafter read through attn_paged_qrow where a card serves it
- libr4d: step past the full-card launch cliff in qkv_norm_rope and the row norms
- libr4d: qkv_norm_rope describes its operands, so rad-kbench and rad-tune can time it
- libr4d, arch/gemma4_bf16: qkv_norm_rope_kv_store -- the 31B's prologue stores k and v itself
- libr4d, arch/common: qkv_norm_rope takes v_norm; DFlash2's query pass folds its q/k chain
- libr4d, arch/common: qkv_norm_rope takes n_head 0; DFlash2's context pass folds its key chain
- libr4d, arch/common: add_rmsnorm; DFlash2 issues each residual add with the norm after it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
AshlynandClaude Opus 5.5 authored and StillDeadcode committed 2026-10-21 09:48:20 +02:00
1 parent 04e5480387
commit 015cba8837
20 files changed
+1332 -164

No files matched your search

+20
View File
@@ -65,6 +65,20 @@ struct R4DArgs {
// null.
const int* cu_q; // (num_seqs+1,) int32 device, or null for a uniform q_len
int total_q; // rows of q/out; ignored unless cu_q is set
// ---- Views the split-KV decode kernel reads (r4d_attn_decode_h256_gqa6.hip); every other
// kernel leaves them at zero and reads q dense with one cache head per query group.
//
// `q_ld` is the element distance between q rows, 0 for dense (q_heads * head_dim): the q part
// of a fused [q|k|v] projection read where it lies (attn_paged_qrow). A multiple of 4.
//
// `kv_rep` maps query groups onto cache heads: group g (q heads g*GQA .. g*GQA+GQA-1) reads
// cache head g / kv_rep, and the descales are per cache head. kv_heads then counts the groups
// (q_heads / GQA) and the cache holds kv_heads / kv_rep heads. 0 or 1 is one head a group. It
// runs a gqa of GQA * kv_rep on the kernel compiled for GQA, whose workgroup holds at most 64
// rows of q_len * GQA: the 31B's DFlash drafter, gqa 8 at a block of 16, on the gqa-4 kernel.
long q_ld;
int kv_rep;
};
// Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook
@@ -89,6 +103,9 @@ int r4d_attn_decode_h256_gqa6_bf16kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a);
// ...with R4DArgs::kv_rep and q_ld read: a gqa of 4 * kv_rep over a cache of kv_heads / kv_rep.
int r4d_attn_decode_h128_gqa4_rep_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa4_rep_bf16kv (const R4DArgs* a, hipStream_t stream);
// 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);
@@ -106,6 +123,9 @@ int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h128_gqa2w_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a);
// ...with q at R4DArgs::q_ld (attn_paged_qrow).
int r4d_attn_decode_h256_gqa2_qld_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_qld_bf16kv (const R4DArgs* a, hipStream_t stream);
// The geometry the attention kernels above are compiled for, so a caller can check a model
// before the first launch.
void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows);
+19 -5
View File
@@ -39,10 +39,14 @@ enum { AP_Q = 0, AP_KV, AP_BT, AP_SEQ, AP_KDS, AP_VDS, AP_CU, AP_OUT };
* would abort the engine. So cu_seqlens is used whenever present, and the uniform arithmetic
* (q_len = total_q / num_seqs) only when it is not. In the ragged case q_len is the batch maximum,
* taken from the parameter the arch block issued the op with (batch->max_q_len).
*
* `q_pitched`: q may be a column slice of a wider row (attn_paged_qrow), its pitch in r->q_ld. Only
* the split-KV decode kernel reads q_ld; every other caller leaves this off.
*/
/* `row` is a token's bytes (elements for a 16-bit cache) in a (block, head) page: 2 * head_dim,
* or 25 * head_dim / 16 for the fp8_v4 cache (E4M3 K, int4 V, f16 group scales). */
static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_dim, long long row) {
static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_dim, long long row,
bool q_pitched = false) {
const RadTensor* q = r4d_opt(a, AP_Q);
const RadTensor* kv = r4d_opt(a, AP_KV);
const RadTensor* bt = r4d_opt(a, AP_BT);
@@ -74,8 +78,16 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d
}
/* q and out are indexed as one dense [total_q, q_heads, head_dim] block; the kernel has no
* pitch argument for either. */
if (!r4d_contig(q) || !r4d_contig(o)) return R4D_NO(RAD_E_STRIDE);
* pitch argument for either -- except q under q_pitched, whose rows may be apart: dense inside
* a row, a pitch in whole 8-byte loads (the kernel reads q four elements at a time). */
long long q_ld = 0;
if (q_pitched && !r4d_contig(q)) {
q_ld = r4d_row_pitch(q);
if (q_ld < q_heads * head_dim || q_ld % 4) return R4D_NO(RAD_E_STRIDE);
} else if (!r4d_contig(q)) {
return R4D_NO(RAD_E_STRIDE);
}
if (!r4d_contig(o)) return R4D_NO(RAD_E_STRIDE);
if (o->shape[0] != total_q || r4d_numel(o) != total_q * q_heads * head_dim)
return R4D_NO(RAD_E_SHAPE);
if (su->shape[0] != num_seqs) return R4D_NO(RAD_E_SHAPE);
@@ -104,6 +116,7 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d
r->k_descale = kds ? (const float*)kds->data : nullptr;
r->v_descale = vds ? (const float*)vds->data : nullptr;
r->q_descale = nullptr; /* the query is bf16 in every variant */
r->q_ld = (long)q_ld; /* 0: dense */
r->scratch = a->scratch;
r->num_seqs = (int)num_seqs;
r->cu_q = ragged ? (const int*)cu->data : nullptr;
@@ -152,8 +165,9 @@ static inline int split_of(const RadArgs* a) {
}
static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) {
return fill_paged_row(a, r, expect_head_dim, 2LL * expect_head_dim);
static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim,
bool q_pitched = false) {
return fill_paged_row(a, r, expect_head_dim, 2LL * expect_head_dim, q_pitched);
}
#endif /* R4D_ATTN_ARGS_H */
+27 -10
View File
@@ -56,6 +56,13 @@
// k6_v4 cache (int6 K, int4 V); a token's row layout is RadBuildCtx::kv_quant's (abi/rad_builder.h).
#define O_V4 33554432
#define O_K6 67108864
// The two views of R4DArgs (r4d.h), compiled in only where a row asks for them, since the h256
// instances sit at the 256-VGPR bound and a runtime pitch and head map spill there:
// QLD q rows at R4DArgs::q_ld (attn_paged_qrow), not dense.
// KVREP query group g reads cache head g / R4DArgs::kv_rep, descales per cache head.
// Neither changes the arithmetic.
#define O_QLD 134217728
#define O_KVREP 268435456
__host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; }
__host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) {
int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits;
@@ -103,6 +110,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
static_assert(!K6 || (!KLDS && (OPT & O_CONTIG) && !KRAW),
"k6_v4 K is widened from the paged cache, a lane's eight dims contiguous");
static_assert(!V4 || (OPT & O_F16), "fp8_v4 widens to f16");
constexpr int QLD = (OPT & O_QLD) ? 1 : 0;
constexpr int KVREP = (OPT & O_KVREP) ? 1 : 0;
typedef DT16<F16> D;
typedef typename D::frag frag16;
@@ -133,6 +142,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
const int c = lane & 15, h = lane >> 4;
const int sp = blockIdx.x, kvh = blockIdx.y, seq = blockIdx.z;
// kvh is the query group; under KVREP the cache head it reads is kvh / kv_rep
const int kvc = KVREP ? kvh / a.kv_rep : kvh;
const int ctx = a.seqused_k[seq];
if (ctx <= 0) return;
@@ -161,13 +172,17 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
const int qhead = kvh * GQA + hi;
const int* __restrict__ bt = a.block_table + (size_t)seq * a.max_blocks;
const float kdesc = a.k_descale ? a.k_descale[seq * a.kv_heads + kvh] : 1.0f;
const float kdesc = a.k_descale
? a.k_descale[seq * (KVREP ? a.kv_heads / a.kv_rep : a.kv_heads) + kvc]
: 1.0f;
const float mul = a.scale * kdesc * 1.44269504089f;
frag16 qf[NKS];
{
const uint16_t* qp = (const uint16_t*)a.q
+ ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM;
const uint16_t* qp = QLD ? (const uint16_t*)a.q + (size_t)(qoff + qrow) * a.q_ld
+ (size_t)qhead * HEAD_DIM
: (const uint16_t*)a.q
+ ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM;
#pragma unroll
for (int t = 0; t < NKS; ++t) {
const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h));
@@ -267,7 +282,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
const int d0 = dg * (KVP ? 32 : 64) + vg * (KVP ? 8 : 16);
const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
const size_t o = (size_t)blk * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride
+ (size_t)kvc * a.kv_head_stride
+ (size_t)(kk % BS) * ROWB + HEAD_DIM + d0;
const void* p = KVP ? (const void*)((const uint16_t*)a.kv + o)
: (const void*)((const uint8_t*)a.kv + o);
@@ -345,7 +360,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
if (WIN && kk < wlo0) kk = wlo0;
const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS];
const size_t o = (size_t)kb * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
+ (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
uint16_t* kd = &sK[key * KSTR];
uint32_t w4[4];
if (KVP) {
@@ -372,7 +387,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
if (WIN && kk < wlo0) kk = wlo0;
const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS];
grow = (const uint8_t*)a.kv + ((size_t)kb * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB)
+ (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB)
* (KVP ? 2 : 1);
}
// A fragment's raw K: 8 elements of 1 byte (fp8) or 2 (bf16).
@@ -730,8 +745,9 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG
}
}
const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads);
const float vd = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f;
const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); /* the query group */
const int krep = a.kv_rep > 1 ? a.kv_rep : 1; /* its cache head: kvh / krep */
const float vd = a.v_descale ? a.v_descale[seq * (a.kv_heads / krep) + kvh / krep] : 1.0f;
uint16_t ob[DPL];
#pragma unroll
for (int j = 0; j < DPL; ++j) {
@@ -873,8 +889,9 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ
#pragma unroll
for (int i = 0; i < CHAINS; ++i) av += ch[i];
const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads);
const float vd = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f;
const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); /* the query group */
const int krep = a.kv_rep > 1 ? a.kv_rep : 1; /* its cache head: kvh / krep */
const float vd = a.v_descale ? a.v_descale[seq * (a.kv_heads / krep) + kvh / krep] : 1.0f;
finish(f32_to_bf16(tot > 0.0f ? av * vd / tot : 0.0f));
}
+1 -1
View File
@@ -106,7 +106,7 @@ extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) {
}
template <int HEAD_DIM, int KVP, int XOPT = 0>
/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168
/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (184
* bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the
* combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). `XOPT` adds
* option bits to the attention kernel's (O_V4, O_K6: the cache layout). */
+8
View File
@@ -37,3 +37,11 @@ extern "C" int r4d_attn_decode_h128_gqa4_fp8kv(const R4DArgs* a, hipStream_t s)
extern "C" int r4d_attn_decode_h128_gqa4_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
}
// The same over a cache holding each kv head once for kv_rep query groups (O_KVREP), q at
// R4DArgs::q_ld (O_QLD): gqa 8 on this gqa-4 kernel, under attn_paged_qrow.
extern "C" int r4d_attn_decode_h128_gqa4_rep_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_KVREP, 0>(a, s);
}
extern "C" int r4d_attn_decode_h128_gqa4_rep_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_KVREP, 1>(a, s);
}
+8
View File
@@ -36,6 +36,14 @@ extern "C" int r4d_attn_decode_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s)
extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT, 1>(a, s);
}
// The same with q at R4DArgs::q_ld (O_QLD), for attn_paged_qrow; its own instances, so the dense
// ones above keep their registers.
extern "C" int r4d_attn_decode_h256_gqa2_qld_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD, 0>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa2_qld_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD, 1>(a, s);
}
// ---- prefill ---------------------------------------------------------------------------------
// The h256/gqa6 prefill option set but at K prefetch 4 (P_OPT there is 3954187); O_KWIDE is valid
+57 -5
View File
@@ -219,7 +219,11 @@ static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) {
return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r);
}
static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long long row = 0) {
/* `row`: a token's bytes in a (block, head) page (fill_paged_row), 0 for 2 * head_dim; `rep`: the
* launch maps each kv head onto `rep` query groups (R4DArgs::kv_rep), so the split law counts
* groups, gqa / rep of them a kv head; `q_pitched`: q may be a slice (attn_paged_qrow). */
static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long long row = 0,
int rep = 1, bool q_pitched = false) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
@@ -231,7 +235,8 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo
r.head_dim = head_dim;
r.q_heads = (int)n_head;
const long long gqa = r4d_geti_or(a, "gqa", 1);
r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head);
r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head) * rep;
r.kv_rep = rep;
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);
@@ -249,8 +254,10 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo
return worst;
}
int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim);
int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim, q_pitched);
if (rc != RAD_OK) return rc;
r.kv_heads *= rep;
r.kv_rep = rep;
r.splits = sp;
return decode_scratch_bytes_of(&r, which);
}
@@ -263,11 +270,17 @@ extern "C" int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 1);
}
static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which, long long row = 0) {
static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which, long long row = 0,
int rep = 1, bool q_pitched = false) {
const int sp = split_of(a);
if (sp < 0) return R4D_NO(RAD_E_INVAL);
int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim);
int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim, q_pitched);
if (rc != RAD_OK) return rc;
/* a QLD instance reads q_ld whatever q is: dense is the pitch q_heads * head_dim */
if (q_pitched && r->q_ld == 0) r->q_ld = (long)r->q_heads * head_dim;
/* each cache head serves `rep` query groups: the kernel's grid and its gqa check count groups */
r->kv_heads *= rep;
r->kv_rep = rep;
r->splits = sp;
const int64_t need = decode_scratch_bytes_of(r, which);
if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH);
@@ -389,3 +402,42 @@ extern "C" int r4d_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa2w_bf16kv(&r, (hipStream_t)s);
}
/* The same decode under attn_paged_qrow: q read at its own row pitch (R4DArgs::q_ld), the sliding
* layers' q where Gemma 4 31B's fused q|k|v projection left it. Same kernel, same arithmetic. */
extern "C" int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs* a) {
return decode_scratch(a, 256, 2, 0, 1, true);
}
extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2, 0, 1, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_qld_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2, 0, 1, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_qld_bf16kv(&r, (hipStream_t)s);
}
/* Head_dim 128 at 8 queries per kv head, any window, causal or not, q_len up to 16, under
* attn_paged_qrow: the gqa-4 kernel with each kv head mapped onto two query groups
* (R4DArgs::kv_rep = 2), the 31B's DFlash drafter's attention over a cache that holds each kv head
* once. The workgroup holds q_len * 4 rows, so a block of 16 fits where gqa 8 (128 rows) does not;
* the two groups of a kv head read its blocks twice, as the copies they replace did. */
extern "C" int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs* a) {
return decode_scratch(a, 128, 1, 0, 2, true);
}
extern "C" int r4d_rad_attn_qrow_h128_gqa8_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 1, 0, 2, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa4_rep_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_qrow_h128_gqa8_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 128, 1, 0, 2, true);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h128_gqa4_rep_bf16kv(&r, (hipStream_t)s);
}
+65
View File
@@ -586,6 +586,71 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u
}
}
/* ==========================================================================================
* qkv_norm_rope_kv_store -- qkv_norm_rope, then kv_store of its finished k and v.
* (rows: qkv_norm_rope_kv_store_fp8 and _bf16; kernel: libr4d/r4d_qkv_norm_rope.hip,
* qkv_norm_rope_kernel under KV)
*
* Operands: [0] q [1] k [2] v [3] positions [4] q_w [5] k_w [6] slot_mapping [7] kv_cache
*
* No temporaries: the prologue rewrites q, k and v in place and the store reads k and v as the
* prologue left them, which is what the kernel stores. */
extern "C" int r4d_fuse_qkv_norm_rope_kv_store(const RadParam* p, int n_p, uint64_t present,
int step, RadFuseStep* out) {
(void)present;
if (!out) return RAD_E_INVAL;
switch (step) {
case 0: {
Step s(out, "qkv_norm_rope");
s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head")
.mirror(p, n_p, "n_head_kv").mirror(p, n_p, "theta").mirror(p, n_p, "eps")
.mirror_opt(p, n_p, "scale").mirror_opt(p, n_p, "mode").mirror_opt(p, n_p, "rotary_dim")
.mirror_opt(p, n_p, "ladder").mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "v_from_k")
.mirror(p, n_p, "dtype").mirror_opt(p, n_p, "v_norm");
return s.wire({ 0, 1, 2, 3, 4, 5 });
}
case 1: {
Step s(out, "kv_store");
s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head_kv")
.mirror(p, n_p, "block_size").mirror(p, n_p, "kv_dtype")
.mirror_opt(p, n_p, "k_scale").mirror_opt(p, n_p, "v_scale");
/* k, v, slot_mapping, kv_cache */
return s.wire({ 1, 2, 6, 7 });
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* add_rmsnorm -- add (x += a), then rmsnorm of the x it wrote.
* (row: add_rmsnorm_bf16; kernel: libr4d/r4d_model_bf16.hip, add_rmsnorm_kernel)
*
* Operands: [0] x [1] a [2] w [3] y
*
* No temporaries: the add writes x in place and the norm reads it. */
extern "C" int r4d_fuse_add_rmsnorm(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out) {
(void)present;
if (!out) return RAD_E_INVAL;
switch (step) {
case 0: {
Step s(out, "add");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype");
/* a = x, b = the addend, y = x */
return s.wire({ 0, 1, 0 });
}
case 1: {
Step s(out, "rmsnorm");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "eps").mirror(p, n_p, "dtype")
.mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "mult");
return s.wire({ 0, 2, 3 });
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* attn_paged_gate_quant -- attn_paged, then gate_quant_fp8 over its output.
* (row: attn_decode_gq_h256_gqa12_fp8kv; kernels: libr4d/r4d_attn_decode_h256_gqa6.hip, the
+79
View File
@@ -226,6 +226,38 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
}
}
// ---------------------------------------------------------------------------- add_rmsnorm
// x = x + a, rounded as `add` rounds it, then y = rmsnorm(x) over the x just written, computed as
// rmsnorm_kernel computes it: the same width (r4d_act_threads), the same columns a thread, the same
// block_sum. A thread re-reads only the x it wrote itself, so no barrier separates the passes.
// Byte-identical to `add` followed by `rmsnorm`, on x and on y.
template <bool WF32, uint32_t THR>
__global__ __launch_bounds__(THR) void add_rmsnorm_kernel(
uint16_t* __restrict__ x, const uint16_t* __restrict__ a, const void* __restrict__ w,
uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld,
uint32_t a_ld, uint32_t y_ld, uint32_t M) {
__shared__ float lds[THR / kWave];
const uint32_t m = blockIdx.x;
if (m >= M) return; // a row the launch added past the full-card cliff (r4d_cliff_rows)
uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
const uint16_t* __restrict__ ar = a + (size_t)m * a_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint16_t h = f32_to_bf16(bf16_to_f32(xr[i]) + bf16_to_f32(ar[i]));
xr[i] = h;
const float v = bf16_to_f32(h);
ss += v * v;
}
ss = block_sum<THR / kWave>(ss, lds);
const float s = rsqrtf(ss / (float)n + eps);
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]);
yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * s * (g + wadd) * mult);
}
}
// ---------------------------------------------------------------------------- rmsnorm_p
// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps), rmsnorm with no gain. Gemma's attention applies
// it to V (llama.cpp's ggml_rms_norm(V, eps)), which has no checkpoint gain. Accumulates exactly as
@@ -1420,6 +1452,53 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ add_rmsnorm */
enum { AN_X = 0, AN_A, AN_W, AN_Y };
extern "C" int r4d_rad_add_rmsnorm(const RadArgs* a, RadStream s) {
int emit_rc = RAD_OK;
const RadTensor* x = r4d_opt(a, AN_X);
const RadTensor* ad = r4d_opt(a, AN_A);
const RadTensor* w = r4d_opt(a, AN_W);
const RadTensor* y = r4d_opt(a, AN_Y);
if (!x || !ad || !w || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(ad));
R4D_NEED(dt_bf16(y));
if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE);
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
const bool w_f32 = w->dtype == RAD_F32;
const long long n = r4d_geti_or(a, "n", r4d_dim(w, (int)w->rank - 1));
if (n <= 0 || r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE);
long long M = 0, Ma = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n, &M);
const long long a_ld = r4d_rows_pitch(ad, n, &Ma);
const long long y_ld = r4d_rows_pitch(y, n, &My);
if (x_ld < 0 || a_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Ma < M || My < M) return R4D_NO(RAD_E_SHAPE);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
const float mult = (float)r4d_getf(a, "mult", 1.0);
/* rmsnorm's width, from the same table (see r4d_rmsnorm_mult_bf16) */
const int thr = r4d_act_threads((int)M, (int)n);
#define R4D_AN_T(wf, T) \
emit_rc = R4D_EMIT(s, (add_rmsnorm_kernel<wf, T>), \
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \
(uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \
(uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \
(uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M)
#define R4D_AN(wf) \
do { if (thr == 1024) R4D_AN_T(wf, 1024); \
else if (thr == 512) R4D_AN_T(wf, 512); \
else R4D_AN_T(wf, 256); } while (0)
if (w_f32) R4D_AN(true);
else R4D_AN(false);
#undef R4D_AN
#undef R4D_AN_T
return emit_rc;
}
/* ------------------------------------------------------------------ rmsnorm_p */
extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) {
+15
View File
@@ -117,6 +117,14 @@ int r4d_rad_attn_prefill_h128_gqa2w_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa2w_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa2w_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs*);
/* attn_paged_qrow on the split-KV decode kernel: the h256/gqa2 decode with q at its own pitch, and
* head_dim 128 at gqa 8 as the gqa-4 kernel with two query groups a kv head (R4DArgs::kv_rep). */
int r4d_rad_attn_qrow_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_decode_h256_gqa2_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs*);
int r4d_rad_attn_qrow_h128_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_h128_gqa8_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_qrow_h128_gqa8_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 per geometry and cache dtype, every q_len and any q
* row pitch, so they serve both attn_paged and attn_paged_qrow. */
@@ -461,6 +469,8 @@ 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_qkv_norm_rope (const RadArgs*, RadStream);
int r4d_rad_add_rmsnorm (const RadArgs*, RadStream);
int r4d_rad_qkv_norm_rope_kv_store(const RadArgs*, RadStream);
int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs*, RadStream);
@@ -781,6 +791,9 @@ int r4d_shape_attn_paged (const RadParam*, int, int operand, RadOpdDesc*)
int r4d_shape_attn_paged_gate_quant(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qk_norm_rope_gate (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qkv_norm_rope (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_qkv_norm_rope_kv_store(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_add_rmsnorm(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_rope_table (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gdn_gated_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*);
@@ -853,6 +866,8 @@ int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseSt
int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_add_rmsnorm(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_ar_gather_hc_write (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_attn_paged_gate_quant(const RadParam*, int, uint64_t, int, RadFuseStep*);
+165 -29
View File
@@ -18,7 +18,16 @@
// `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 overwrites it, in the order the unfused block issues them.
// k norm overwrites it, in the order the unfused block issues them. `v_norm` 0 leaves v as it is
// (a Qwen3-shaped layer, the DFlash2 drafter's: q and k normed, v not), so the launch is the two
// norms and two rotaries, and with the store v's heads only store.
//
// `qkv_norm_rope_kv_store` is the same launch followed by `kv_store`: the block of a k head (and of
// a v head) ends holding its token's finished head, so it also writes it into the paged cache at
// the token's slot, converted as kv_store converts it (E4M3: times the inverse descale, clamped to
// +-448, v_cvt_pk_fp8_f32 four columns a lane; bf16: the values as they are). The head is staged in
// LDS for that, since the fp8 store packs four neighbouring columns a lane. Byte-identical to the
// pair at either cache width; the k, v and q rows are still written, as the pair leaves them.
//
// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d.h"
@@ -52,10 +61,12 @@ __device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_
return s;
}
// The rotary over a normed head staged in `nb`, written to `out`: rope_kernel's body for pair i.
// The rotary over a normed head staged in `nb`, written to `out` (and to `st` when the head is also
// stored): 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) {
float p0, uint32_t rot, uint32_t nfreq, int den, float theta,
uint16_t* __restrict__ st) {
const uint32_t half = rot / 2, t = threadIdx.x;
if (t < half) {
float inv = 1.0f / powf(theta, (float)(2 * t) / (float)den);
@@ -64,35 +75,99 @@ __device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t
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);
const uint16_t y0 = f32_to_bf16(x0 * c - x1 * s), y1 = f32_to_bf16(x0 * s + x1 * c);
out[t] = y0;
out[t + half] = y1;
if (st) { st[t] = y0; st[t + half] = y1; }
}
for (uint32_t i = rot + t; i < HD; i += HD) { // the unrotated tail
out[i] = nb[i];
if (st) st[i] = nb[i];
}
}
// One head into the paged cache at element offset `off` (r4d_model_bf16.hip's kv_store kernels):
// KV 1 an E4M3 cache, four columns a lane as kv_store_fp8_kernel converts them; KV 2 a bf16 cache,
// the values as they are. `src` is the head in LDS, complete before the call.
template <uint32_t HD, int KV>
__device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off,
const uint16_t* __restrict__ src, float inv) {
const uint32_t t = threadIdx.x;
if (KV == 1) {
if (t < HD / 4) {
const uint32_t d = t * 4u;
float f[4];
#pragma unroll
for (int e = 0; e < 4; ++e) f[e] = bf2f(src[d + (uint32_t)e]) * inv;
// clamped because v_cvt_pk_fp8_f32 returns NaN out of range instead of saturating
int pk = 0;
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[0], -448.0f), 448.0f),
fminf(fmaxf(f[1], -448.0f), 448.0f), pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[2], -448.0f), 448.0f),
fminf(fmaxf(f[3], -448.0f), 448.0f), pk, true);
*(uint32_t*)((uint8_t*)kv + off + d) = (uint32_t)pk;
}
} else if (KV == 2) {
for (uint32_t i = t; i < HD; i += HD) ((uint16_t*)kv)[off + i] = src[i];
}
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>
//
// KV 1 or 2 also stores each k and v head into the paged cache [n_blocks, nkv, block_size, 2*HD]
// at slot[m] (k at column 0, v at HD), for rows m < n_slot whose slot is in range; KV 0 stores
// nothing and ignores the cache arguments.
template <uint32_t HD, bool WF32, bool VK, int KV>
__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,
uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos,
uint32_t m_rows) {
uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot,
uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm) {
__shared__ float l1[HD / kWave], l2[HD / kWave];
__shared__ uint16_t nb[HD];
__shared__ uint16_t sb[KV ? HD : 1]; // the head this block stores
__shared__ uint16_t vb[(KV && VK) ? HD : 1]; // and, under VK, the value from the raw k
const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x;
if (m >= m_rows) return; // a row the launch added past the full-card cliff (r4d_cliff_rows)
const float div = rscale != 0.0f ? rscale : 1.0f;
// rope rotates only the rows its positions cover; a row past them is normed and not rotated
const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f;
// The row's cache slot, as kv_store reads it: a negative or out-of-range slot stores nothing.
// Uniform over the block, so the barriers below are too.
size_t base = 0;
bool put = false;
if (KV && m < n_slot) {
const int32_t sl = slot[m];
if (sl >= 0 && (uint32_t)sl / block_size < n_blocks) {
put = true;
base = ((size_t)((uint32_t)sl / block_size) * nkv * block_size +
(size_t)((uint32_t)sl % block_size)) * 2 * HD;
}
}
const size_t head_step = (size_t)block_size * 2 * HD;
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);
if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p (or, without v_norm, only stored)
const uint32_t h = hh - nq - nkv;
uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)h * HD;
if (vnorm) {
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) {
const uint16_t y = f32_to_bf16(bf2f(x[i]) * s);
x[i] = y;
if (KV) sb[i] = y;
}
} else if (KV) {
for (uint32_t i = t; i < HD; i += HD) sb[i] = x[i];
}
if (KV && put) {
__syncthreads();
kv_put<HD, KV>(kvc, base + (size_t)h * head_step + HD, sb, v_inv);
}
return;
}
const bool isq = hh < nq;
@@ -104,7 +179,11 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(
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);
for (uint32_t i = t; i < HD; i += HD) {
const uint16_t y = f32_to_bf16(bf2f(x[i]) * sv);
vo[i] = y;
if (KV && VK) vb[i] = y;
}
}
const float s = rsqrtf(head_ss<HD>(x, isq ? pq : pk, l1) / (float)HD + eps);
for (uint32_t i = t; i < HD; i += HD) {
@@ -112,16 +191,24 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(
nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd));
}
__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];
uint16_t* const st = (KV && !isq) ? sb : nullptr;
if (m < n_pos) rotate<HD>(nb, x, p0, rot, nfreq, den, theta, st);
else for (uint32_t i = t; i < HD; i += HD) { x[i] = nb[i]; if (st) st[i] = nb[i]; }
if (KV && !isq && put) {
__syncthreads(); // the stored head (and VK's value) complete in LDS
kv_put<HD, KV>(kvc, base + (size_t)h * head_step, sb, k_inv);
if (VK) kv_put<HD, KV>(kvc, base + (size_t)h * head_step + HD, vb, v_inv);
}
}
} // namespace
// ============================================================== the plugin ABI entry point
enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW };
// ============================================================== the plugin ABI entry points
enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW, QN_SLOT, QN_CACHE };
extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) {
// Both ops' launch: `store` reads qkv_norm_rope_kv_store's slot mapping and cache (operands 6, 7)
// and its kv_store parameters.
static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store) {
int emit_rc = RAD_OK;
const RadTensor* q = r4d_opt(a, QN_Q);
const RadTensor* k = r4d_opt(a, QN_K);
@@ -138,11 +225,12 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) {
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);
// v_norm 0: no value norm at all (Gemma 3); the v heads are left out of the grid.
// v_norm 0: no value norm (Gemma 3; a Qwen3-shaped layer such as the DFlash2 drafter's): the v
// heads are left out of the grid, or with the store only store.
const long long vn = r4d_geti_or(a, "v_norm", 1);
if (hd != 128 && hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE);
if (vk && !vn) return R4D_NO(RAD_E_INVAL);
if (nq <= 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
if (vk && !vn) return R4D_NO(RAD_E_INVAL); // v from k is v's norm
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);
@@ -158,39 +246,87 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) {
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);
/* n_head 0: the k (and v) heads alone, q neither read nor written (a context pass's keys) */
const long long q_ld = nq ? r4d_rows_pitch(q, nq * hd, &M) : 0;
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);
if (!nq) M = Mk;
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 per 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 pq = nq ? (uint32_t)std::min<long long>(r4d_act_threads((int)(M * nq), (int)hd), hd)
: (uint32_t)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 uint32_t heads = (uint32_t)(nq + nkv + ((vk || !vn) ? 0 : nkv));
/* v's own heads: normed (and stored), stored only, or with neither nothing to do */
const uint32_t heads = (uint32_t)(nq + nkv + ((vk || (!vn && !store)) ? 0 : nkv));
// A tp-4 verify of the 31B is 16 rows x 16 heads of 8 wavefronts: exactly a full card, the
// cliff r4d_cliff_rows steps past with one idle row.
const dim3 grid(r4d_cliff_rows((uint32_t)M, heads, (uint32_t)(hd / kWave)), heads);
#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel<HD, WF, VK>), grid, dim3(HD), 0, \
// The store's geometry, checked as kv_store_geom checks it (r4d_model_bf16.hip).
int kvw = 0; // 0 none, 1 E4M3, 2 bf16
const RadTensor* sm = nullptr;
const RadTensor* kv = nullptr;
long long bs = 0, nblk = 0, nslot = 0;
float kinv = 1.0f, vinv = 1.0f;
if (store) {
sm = r4d_opt(a, QN_SLOT);
kv = r4d_opt(a, QN_CACHE);
if (!sm || !kv) return R4D_NO(RAD_E_INVAL);
if (sm->dtype != RAD_I32 || !r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE);
bs = r4d_geti_or(a, "block_size", 0);
if (bs <= 0 || kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs ||
kv->shape[3] != 2 * hd)
return R4D_NO(RAD_E_SHAPE);
nblk = kv->shape[0];
nslot = r4d_numel(sm);
if (nslot <= 0 || nslot > M) return R4D_NO(RAD_E_SHAPE);
if (kv->dtype == RAD_F8E4M3) {
const double ks = r4d_getf(a, "k_scale", 1.0), vs = r4d_getf(a, "v_scale", 1.0);
if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL);
kinv = 1.0f / (float)ks;
vinv = 1.0f / (float)vs;
kvw = 1;
} else if (kv->dtype == RAD_BF16) {
kvw = 2;
} else {
return R4D_NO(RAD_E_DTYPE);
}
}
#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel<HD, WF, VK, KV>), 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, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp, \
(uint32_t)M)
(uint32_t)M, (const int32_t*)(sm ? r4d_p(sm) : nullptr), (void*)(kv ? r4d_wp(kv) : nullptr), \
(uint32_t)nslot, (uint32_t)bs, (uint32_t)nblk, kinv, vinv, (uint32_t)(vn ? 1 : 0))
#define R4D_QNR_KV(HD, WF, VK) \
do { if (kvw == 1) R4D_QNR_T(HD, WF, VK, 1); else if (kvw == 2) R4D_QNR_T(HD, WF, VK, 2); \
else R4D_QNR_T(HD, WF, VK, 0); } while (0)
#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)
do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_KV(HD, true, true); else R4D_QNR_KV(HD, true, false); } \
else { if (vk) R4D_QNR_KV(HD, false, true); else R4D_QNR_KV(HD, false, false); } } while (0)
if (hd == 128) R4D_QNR(128);
else if (hd == 256) R4D_QNR(256);
else R4D_QNR(512);
#undef R4D_QNR
#undef R4D_QNR_KV
#undef R4D_QNR_T
return emit_rc;
}
extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) {
return qkv_norm_rope_launch(a, stream, false);
}
extern "C" int r4d_rad_qkv_norm_rope_kv_store(const RadArgs* a, RadStream stream) {
return qkv_norm_rope_launch(a, stream, true);
}
+164 -2
View File
@@ -728,6 +728,21 @@ static const RadOperandSpec oGemmNt[] = {
* (w5a16, w4a16_asym, w4a8i8_asym, w5a8i8): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each
* meet their own copy of the activation, side by side in a row of `a` ([M, parts * K]). 0 leaves a
* bound out. Absent on other grids, where a fused projection has one activation. */
/* `add_rmsnorm` is `add` (x += a) followed by `rmsnorm` of the x it wrote (docs/OPS.md). */
static const RadParamSpec pAddRmsNorm[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
P_F64("eps"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
P_F64O("wadd"),
P_F64O("mult"),
};
static const RadOperandSpec oAddRmsNorm[] = {
{ "x", RAD_OPD_INOUT, 0 },
{ "a", RAD_OPD_IN, 0 },
{ "w", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pGemmNtQ[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "N", RAD_P_INT, RAD_REQUIRED },
@@ -1404,6 +1419,7 @@ static const RadParamSpec pQkvNormRope[] = {
{ "ladder", RAD_P_STR, RAD_OPTIONAL },
P_F64O("wadd"),
{ "v_from_k", RAD_P_INT, RAD_OPTIONAL },
/* 0 leaves v unnormed (Gemma 3; a Qwen3-shaped layer); absent, 1 */
{ "v_norm", RAD_P_INT, RAD_OPTIONAL },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
@@ -1415,6 +1431,39 @@ static const RadOperandSpec oQkvNormRope[] = {
{ "q_w", RAD_OPD_WEIGHT, 0 },
{ "k_w", RAD_OPD_WEIGHT, 0 },
};
/* `qkv_norm_rope_kv_store` is qkv_norm_rope followed by kv_store in one launch: the prologue's
* operands, then kv_store's slot mapping and paged cache; every parameter is one of the two ops'.
* Byte-identical to the pair (docs/OPS.md). */
static const RadParamSpec pQkvNormRopeKv[] = {
{ "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 },
{ "v_norm", RAD_P_INT, RAD_OPTIONAL },
{ "block_size", RAD_P_INT, RAD_REQUIRED },
{ "kv_dtype", RAD_P_STR, RAD_REQUIRED },
P_F64O("k_scale"),
P_F64O("v_scale"),
};
static const RadOperandSpec oQkvNormRopeKv[] = {
{ "q", RAD_OPD_INOUT, 0 },
{ "k", RAD_OPD_INOUT, 0 },
{ "v", RAD_OPD_INOUT, 0 },
{ "positions", RAD_OPD_IN, 0 },
{ "q_w", RAD_OPD_WEIGHT, 0 },
{ "k_w", RAD_OPD_WEIGHT, 0 },
{ "slot_mapping", RAD_OPD_IN, 0 },
{ "kv_cache", RAD_OPD_INOUT, 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. */
@@ -3097,9 +3146,17 @@ static const RadOpSchema kSchemas[] = {
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("add_rmsnorm", pAddRmsNorm, oAddRmsNorm,
"x = x + a, then y = rmsnorm(x) * (w + wadd) * mult over the x written: a residual add "
"and the next norm in one pass, byte-identical to add then rmsnorm. The norm is taken "
"over the bf16 sum it stores; rmsnorm_add normalises the unrounded one."),
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."),
"q, k and v projections, in one dispatch; v from the raw k under v_from_k. n_head 0 "
"leaves q unread (the k and v heads alone)."),
SCHEMA("qkv_norm_rope_kv_store", pQkvNormRopeKv, oQkvNormRopeKv,
"qkv_norm_rope, then kv_store of the finished k and v heads into the paged cache, in one "
"launch."),
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."),
@@ -3548,6 +3605,19 @@ 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"),
};
/* Head_dim 128 at 8 queries per kv head under attn_paged_qrow: the gqa-4 kernel above with each kv
* head mapped onto two query groups (R4DArgs::kv_rep), so q_len * 4 <= 64 bounds it where gqa 8's
* own decode (q_len <= 8, no window) stops at 8. The 31B's DFlash drafter: 64 heads over 8 kv heads,
* sliding layers over 2048 and a full non-causal one, at a block of 16. Under attn_paged_qrow, which
* no host library declares, so a drafter asking for it learns whether a card serves it. */
static const RadConstraint cAttnQrowH128G8Fp8[] = {
C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnQrowH128G8Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), 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 prefill (r4d_attn_paged_h256_gqa2.hip): the decode leg's geometry
* without a q_len bound, serving q_len > 32. The kernel's WIN bit masks the window and skips tiles
* below it. Without this row the prefill band would have no device kernel, which is fatal (spec
@@ -4480,6 +4550,9 @@ 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 cAddRmsNorm[] = {
C_GE("n", 1), C_IN("dtype", "bf16"),
};
static const RadConstraint cQkvNormRope[] = {
C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"),
};
@@ -4487,6 +4560,14 @@ static const RadConstraint cQkvNormRope[] = {
static const RadConstraint cQkvNormRopeH128[] = {
C_EQ("head_dim", 128), C_IN("dtype", "bf16"),
};
static const RadConstraint cQkvNormRopeKv[] = {
C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"),
C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cQkvNormRopeKvBf16[] = {
C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"),
C_GE("block_size", 1), C_IN("kv_dtype", "bf16"),
};
static const RadConstraint cGeluMulQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"),
};
@@ -5902,6 +5983,52 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2w_bf16, r4d_rad_attn_decode_h128_gqa2w_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
/* The same decode under attn_paged_qrow, reading q at its own row pitch: Gemma 4 31B's sliding
* layers read q in the fused q|k|v row. It outranks the windowed qrow rows (R4D_PRIO_ONLY) in its
* band, as attn_paged's does, since it takes 0.26-0.71 of their time there; above q_len 32 the
* windowed kernel serves the op alone. No opd_shape, as for every qrow row: libref has none. */
{ "attn_qrow_decode_h256_gqa2_fp8kv", "attn_paged_qrow", "attn",
"paged attention reading q at its own row pitch, 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 (any row pitch, a multiple of 4), 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_qrow_decode_h256_gqa2_fp8,
r4d_rad_attn_qrow_decode_h256_gqa2_scratch,
nullptr, nullptr, nullptr },
{ "attn_qrow_decode_h256_gqa2_bf16kv", "attn_paged_qrow", "attn",
"paged attention reading q at its own row pitch, 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 (any row pitch, a multiple of 4), bf16 kv cache, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_qrow_decode_h256_gqa2_bf16,
r4d_rad_attn_qrow_decode_h256_gqa2_scratch,
nullptr, nullptr, nullptr },
/* Head_dim 128 at gqa 8 under attn_paged_qrow (cAttnQrowH128G8Fp8 says why). */
{ "attn_qrow_h128_gqa8_fp8kv", "attn_paged_qrow", "attn",
"paged attention, any window, causal or not, split-KV (draft block); q at any row pitch",
"head_dim 128, 8 queries per kv head as two groups of 4 a kv head, paged block 16, q_len <= 16",
"bf16 query (any row pitch, a multiple of 4), fp8-e4m3 kv cache with per-(seq,head) descales, "
"bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnQrowH128G8Fp8), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_qrow_h128_gqa8_fp8, r4d_rad_attn_qrow_h128_gqa8_scratch,
nullptr, nullptr, nullptr },
{ "attn_qrow_h128_gqa8_bf16kv", "attn_paged_qrow", "attn",
"paged attention, any window, causal or not, split-KV (draft block); q at any row pitch",
"head_dim 128, 8 queries per kv head as two groups of 4 a kv head, paged block 16, q_len <= 16",
"bf16 query (any row pitch, a multiple of 4), bf16 kv cache, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnQrowH128G8Bf16), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_qrow_h128_gqa8_bf16, r4d_rad_attn_qrow_h128_gqa8_scratch,
nullptr, nullptr, nullptr },
{ "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
@@ -7662,7 +7789,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"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, r4d_rad_qkv_norm_rope, nullptr, nullptr, nullptr, r4d_shape_qkv_norm_rope },
{ "qkv_norm_rope_h128_bf16", "qkv_norm_rope", "attn",
"per-head RMS norms of separate q and k projections, the weightless norm of v unless v_norm is 0, "
@@ -7675,6 +7802,41 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cQkvNormRopeH128), NOTUNE,
nullptr, nullptr, r4d_rad_qkv_norm_rope },
/* The prologue and the cache store in one launch: a k (or v) head's block ends holding its token's
* finished head, so it writes it into the cache too, converted as kv_store converts it. Saves the
* store's launch a layer, which at decode is most of its cost. */
{ "qkv_norm_rope_kv_store_fp8", "qkv_norm_rope_kv_store", "attn",
"qkv_norm_rope, and kv_store into an E4M3 paged cache from the same launch",
"qkv_norm_rope's shapes; cache exactly [n_blocks, n_head_kv, block_size, 2*head_dim], one slot "
"a row; a negative or out-of-range slot stores nothing",
"bf16 q/k/v and gains (or f32 gains), i32 positions and slots, fp8-e4m3 cache, scalar "
"k_scale / v_scale descales; byte-identical to qkv_norm_rope + kv_store_fp8",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cQkvNormRopeKv), NOTUNE,
nullptr, nullptr, r4d_rad_qkv_norm_rope_kv_store, nullptr, nullptr, nullptr,
r4d_shape_qkv_norm_rope_kv_store, nullptr, r4d_fuse_qkv_norm_rope_kv_store },
/* The same into a bf16 cache: the store is the values kv_store_bf16 copies. */
{ "qkv_norm_rope_kv_store_bf16", "qkv_norm_rope_kv_store", "attn",
"qkv_norm_rope, and kv_store into a bf16 paged cache from the same launch",
"qkv_norm_rope's shapes; cache exactly [n_blocks, n_head_kv, block_size, 2*head_dim], one slot "
"a row; a negative or out-of-range slot stores nothing",
"bf16 q/k/v, gains, cache; i32 positions and slots; byte-identical to qkv_norm_rope + "
"kv_store_bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cQkvNormRopeKvBf16), NOTUNE,
nullptr, nullptr, r4d_rad_qkv_norm_rope_kv_store, nullptr, nullptr, nullptr,
r4d_shape_qkv_norm_rope_kv_store, nullptr, r4d_fuse_qkv_norm_rope_kv_store },
{ "add_rmsnorm_bf16", "add_rmsnorm", "norm",
"x += a, then the root-mean-square norm of the x written, one workgroup a row as rmsnorm_bf16",
"any n; rmsnorm_bf16's width and column partition, so the sum of squares folds as it does",
"bf16 x / a / y, f32 or bf16 gain, fp32 reduction; byte-identical to add_bf16 + rmsnorm_bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAddRmsNorm), NOTUNE,
nullptr, nullptr, r4d_rad_add_rmsnorm, nullptr, nullptr, nullptr,
r4d_shape_add_rmsnorm, nullptr, r4d_fuse_add_rmsnorm },
{ "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",
+190 -12
View File
@@ -943,9 +943,11 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8
/* Numeric attention check: fill q and the paged k/v with avalanche-random data, run the row, and
* compare the bf16 output against the oracle above. A negative control corrupts part of the
* reference and requires the comparison to fail. */
/* `q_extra` > 0: q is a column slice of rows q_extra elements wider than its heads (an
* attn_paged_qrow row reads it at that pitch, as from a fused q|k|v projection). */
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,
int64_t bs = 16) {
int64_t bs = 16, int64_t q_extra = 0) {
if (!sel(name)) return;
const RadKernelInfo* r = find(pl, name);
if (!r) { ok(name, false, "row absent"); return; }
@@ -992,8 +994,16 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d
}
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);
const int64_t q_ld = q_heads * head_dim + q_extra;
void* d_q = dalloc((size_t)total_q * q_ld * 2);
{
/* the slice's rows at the pitch, the rest of each row a value no head holds */
std::vector<uint16_t> qp((size_t)total_q * q_ld, h_to_bf16(9.0f));
for (int64_t t = 0; t < total_q; ++t)
std::memcpy(&qp[(size_t)(t * q_ld)], &qh[(size_t)(t * q_heads * head_dim)],
(size_t)(q_heads * head_dim) * 2);
st_memcpy(d_q, qp.data(), qp.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);
@@ -1008,6 +1018,7 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d
T(nullptr, RAD_I32, { seqs + 1 }),
T(d_out, RAD_BF16, { total_q, q_heads, head_dim }),
};
ts[0].stride[0] = q_ld;
if (kvdt == RAD_BF16) { absent(ts[4]); absent(ts[5]); }
absent(ts[6]);
std::vector<RadParam> ps = {
@@ -10977,10 +10988,16 @@ static void qkv_norm_rope_numeric(const Plugin& pl) {
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; }
/* vn false: no value norm (Gemma 3's prologue, and a Qwen3-shaped layer such as the DFlash2
* drafter's), q and k normed and v not, so the chain is four ops and v must come out as it went
* in; nq 0 as well: that layer's keys alone (the drafter's context pass), the chain a k norm and
* a k rope, q passed as k's buffer */
struct Cls { int64_t hd, nq, nkv, rot; const char* ladder; double theta; bool vk, vn; };
for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false, true },
Cls{ 512, 16, 2, 128, "head", 1000000.0, true, true },
Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false } }) {
Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false },
Cls{ 256, 8, 4, 256, "rotary", 10000.0, false, false },
Cls{ 256, 0, 4, 256, "rotary", 10000.0, false, false } }) {
/* 8 rows of the head-256 class are 8 x 32 workgroups of 8 wavefronts, a full card: the
* launch adds an idle row past the cliff (r4d_cliff_rows), which must not change a byte. */
for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)8, (int64_t)40 }) {
@@ -10996,9 +11013,11 @@ static void qkv_norm_rope_numeric(const Plugin& pl) {
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* dq[2] = { nullptr, nullptr };
void* dk[2] = { dalloc(hk.size() * 2), dalloc(hk.size() * 2) };
void* dv[2] = { dalloc(hv.size() * 2), dalloc(hv.size() * 2) };
for (int j = 0; j < 2; ++j) dq[j] = cl.nq ? dalloc(hq.size() * 2) : dk[j];
const int64_t QW = cl.nq ? QD : KD; /* q's width as passed (k's buffer at nq 0) */
void* dqw = dalloc(hqw.size() * 2);
void* dkw = dalloc(hkw.size() * 2);
void* dp = dalloc(hp.size() * 4);
@@ -11016,26 +11035,28 @@ static void qkv_norm_rope_numeric(const Plugin& pl) {
int rc = !cl.vn ? RAD_OK
: 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)
if (rc == RAD_OK && cl.nq)
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)
for (int j = cl.nq ? 0 : 1; 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 }),
rc = launch_row(fz, { T(dq[1], RAD_BF16, { M, QW }), 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), PI("v_norm", cl.vn ? 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);
const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) +
(cl.nq ? "" : " n_head=0") + (cl.vn ? "" : " v_norm=0") +
" 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) {
@@ -11047,12 +11068,149 @@ static void qkv_norm_rope_numeric(const Plugin& pl) {
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,
ok((what + (cl.nq ? " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2"
: " is byte-identical to rmsnorm + rope over k")).c_str(),
nd == 0 && moved > 0,
"differs " + std::to_string(nd) + ", changed from the input " + std::to_string(moved));
/* --- and with kv_store folded in (qkv_norm_rope_kv_store): the pair (the prologue's
* output above, then kv_store) against the one launch from the same inputs, at both
* cache widths. Slots are unique with one row's negative (padding, which stores
* nothing), and the caches start marked, so a stray or a missing store shows. --- */
for (const bool f8 : { true, false }) {
const RadKernelInfo* ks = find(pl, f8 ? "kv_store_fp8" : "kv_store_bf16");
const RadKernelInfo* fk = find(pl, f8 ? "qkv_norm_rope_kv_store_fp8"
: "qkv_norm_rope_kv_store_bf16");
const std::string w2 = what + (f8 ? " + kv_store_fp8" : " + kv_store_bf16");
if (!ks || !fk) { ok(w2.c_str(), false, "rows absent"); continue; }
const int64_t bs = 16, nb = (M + bs - 1) / bs + 2, esz = f8 ? 1 : 2;
const size_t cb = (size_t)(nb * cl.nkv * bs * 2 * cl.hd * esz);
std::vector<int32_t> hs((size_t)M);
for (int64_t m = 0; m < M; ++m) hs[(size_t)m] = (int32_t)((m * 37 + 3) % (nb * bs));
if (M > 1) hs[1] = -1;
void* dsl = dalloc(hs.size() * 4);
void* dc[2] = { dalloc(cb), dalloc(cb) };
void* d3[3] = { nullptr, dalloc(hk.size() * 2), dalloc(hv.size() * 2) };
d3[0] = cl.nq ? dalloc(hq.size() * 2) : d3[1];
if (!dsl || !dc[0] || !dc[1] || !d3[0] || !d3[1] || !d3[2]) {
ok(w2.c_str(), false, "hipMalloc failed");
continue;
}
st_memcpy(dsl, hs.data(), hs.size() * 4, hipMemcpyHostToDevice);
st_memset(dc[0], 0x5A, cb);
st_memset(dc[1], 0x5A, cb);
st_memcpy(d3[0], hq.data(), hq.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d3[1], hk.data(), hk.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d3[2], hv.data(), hv.size() * 2, hipMemcpyHostToDevice);
const uint32_t kvdt = f8 ? RAD_F8E4M3 : RAD_BF16;
const char* kvn = f8 ? "fp8_e4m3" : "bf16";
int r2 = launch_row(ks, { T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }),
T(dsl, RAD_I32, { M }),
T(dc[0], kvdt, { nb, cl.nkv, bs, 2 * cl.hd }) },
{ PI("M", M), PI("head_dim", cl.hd), PI("n_head_kv", cl.nkv),
PI("block_size", bs), PS("kv_dtype", kvn) });
if (r2 == RAD_OK)
r2 = launch_row(fk, { T(d3[0], RAD_BF16, { M, QW }), T(d3[1], RAD_BF16, { M, KD }),
T(d3[2], RAD_BF16, { M, KD }), T(dp, RAD_I32, { M }),
T(dqw, RAD_BF16, { cl.hd }), T(dkw, RAD_BF16, { cl.hd }),
T(dsl, RAD_I32, { M }),
T(dc[1], kvdt, { nb, cl.nkv, bs, 2 * 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"),
PI("v_norm", cl.vn ? 1 : 0),
PI("block_size", bs), PS("kv_dtype", kvn) });
if (r2 != RAD_OK) { ok(w2.c_str(), false, "rc=" + std::to_string(r2)); continue; }
std::vector<uint8_t> c0(cb), c1(cb);
st_memcpy(c0.data(), dc[0], cb, hipMemcpyDeviceToHost);
st_memcpy(c1.data(), dc[1], cb, hipMemcpyDeviceToHost);
size_t ncd = 0, written = 0;
for (size_t i = 0; i < cb; ++i) { ncd += c0[i] != c1[i]; written += c1[i] != 0x5A; }
size_t nrow = 0;
for (int t = 0; t < 3; ++t) {
void* const pr = t == 0 ? dq[1] : (t == 1 ? dk[1] : dv[1]);
const size_t n = t == 0 ? hq.size() : hk.size();
std::vector<uint16_t> a(n), b(n);
st_memcpy(a.data(), pr, n * 2, hipMemcpyDeviceToHost);
st_memcpy(b.data(), d3[t], n * 2, hipMemcpyDeviceToHost);
for (size_t i = 0; i < n; ++i) nrow += a[i] != b[i];
}
ok((w2 + " folded into one launch is byte-identical to the pair").c_str(),
ncd == 0 && nrow == 0 && written > 0,
"cache bytes differ " + std::to_string(ncd) + ", q/k/v differ " +
std::to_string(nrow) + ", cache bytes written " + std::to_string(written));
}
}
}
}
/* ---- add_rmsnorm, against add then rmsnorm --------------------------------------------------
*
* x = x + a, then rmsnorm of the x written: a DFlash2 drafter's residual add and its next norm.
* Byte-identical on x and on y at every r4d_act_threads width (a query pass's rows, a prefill
* chunk's), with an f32 gain (as plugins declare) and a bf16 one, with and without Gemma's `1 +`. */
static void add_rmsnorm_numeric(const Plugin& pl) {
const RadKernelInfo* ad = find(pl, "add_bf16");
const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16");
const RadKernelInfo* fz = find(pl, "add_rmsnorm_bf16");
if (!ad || !nrm || !fz) { ok("add_rmsnorm vs add + rmsnorm", false, "rows absent"); return; }
const int64_t K = 5376;
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)16, (int64_t)40, (int64_t)300 })
for (int form = 0; form < 3; ++form) {
const bool f32 = form != 1;
const double wadd = form == 2 ? 1.0 : 0.0;
std::vector<uint16_t> hx((size_t)M * K), ha((size_t)M * K), hwb((size_t)K);
std::vector<float> hwf((size_t)K);
for (int64_t r = 0; r < M; ++r)
for (int64_t c = 0; c < K; ++c) {
hx[(size_t)r * K + c] = h_to_bf16(0.029f * (float)((r * 31 + c * 17) % 73) - 1.1f);
ha[(size_t)r * K + c] = h_to_bf16(0.013f * (float)((r * 11 + c * 23) % 61) - 0.4f);
}
for (int64_t c = 0; c < K; ++c) {
hwf[(size_t)c] = 0.7f + 0.0031f * (float)((c * 19) % 53);
hwb[(size_t)c] = h_to_bf16(hwf[(size_t)c]);
}
const size_t nb = (size_t)M * K * 2;
void* dx[2] = { dalloc(nb), dalloc(nb) };
void* dy[2] = { dalloc(nb), dalloc(nb) };
void* da = dalloc(nb);
void* dw = dalloc((size_t)K * 4);
if (!dx[1] || !dy[1] || !da || !dw) { ok("add_rmsnorm alloc", false, "hipMalloc failed"); return; }
for (int j = 0; j < 2; ++j) st_memcpy(dx[j], hx.data(), nb, hipMemcpyHostToDevice);
st_memcpy(da, ha.data(), nb, hipMemcpyHostToDevice);
if (f32) st_memcpy(dw, hwf.data(), (size_t)K * 4, hipMemcpyHostToDevice);
else st_memcpy(dw, hwb.data(), (size_t)K * 2, hipMemcpyHostToDevice);
const uint32_t wdt = f32 ? RAD_F32 : RAD_BF16;
const double eps = 1e-6;
int rc = launch_row(ad, { T(dx[0], RAD_BF16, { M, K }), T(da, RAD_BF16, { M, K }), T(dx[0], RAD_BF16, { M, K }) },
{ PI("M", M), PI("n", K), PS("dtype", "bf16") });
if (rc == RAD_OK)
rc = launch_row(nrm, { T(dx[0], RAD_BF16, { M, K }), T(dw, wdt, { K }), T(dy[0], RAD_BF16, { M, K }) },
{ PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) });
if (rc == RAD_OK)
rc = launch_row(fz, { T(dx[1], RAD_BF16, { M, K }), T(da, RAD_BF16, { M, K }), T(dw, wdt, { K }),
T(dy[1], RAD_BF16, { M, K }) },
{ PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) });
const std::string what = std::string("add_rmsnorm M=") + std::to_string(M) +
(f32 ? " f32 gain" : " bf16 gain") + (wadd != 0.0 ? " wadd=1" : "");
if (rc != RAD_OK) { ok(what.c_str(), false, "rc=" + std::to_string(rc)); continue; }
size_t ndx = 0, ndy = 0, moved = 0;
for (int t = 0; t < 2; ++t) {
std::vector<uint16_t> u((size_t)M * K), v((size_t)M * K);
st_memcpy(u.data(), t ? dy[0] : dx[0], nb, hipMemcpyDeviceToHost);
st_memcpy(v.data(), t ? dy[1] : dx[1], nb, hipMemcpyDeviceToHost);
for (size_t i = 0; i < u.size(); ++i) {
(t ? ndy : ndx) += u[i] != v[i];
if (!t) moved += v[i] != hx[i];
}
}
ok((what + " is byte-identical to add + rmsnorm").c_str(), ndx == 0 && ndy == 0 && moved > 0,
"x differs " + std::to_string(ndx) + ", y differs " + std::to_string(ndy));
}
}
/* ---- rmsnorm_quant_i8, against the chain it replaces ------------------------------------------
*
* Byte-identical, as the fp8 fusions above, in the three forms a sandwich-norm model issues: the
@@ -23810,6 +23968,20 @@ static void device_phase(const Plugin& pl) {
attn_case(pl, "attn_decode_h256_gqa6_bf16kv", 256, 6, 1, "bf16", 0);
attn_case(pl, "attn_decode_h128_gqa4_fp8kv", 128, 4, 1, "fp8_e4m3", 0);
attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0);
/* attn_paged_qrow on the split-KV decode kernel: head_dim 128 at gqa 8 (two query groups a kv
* head, R4DArgs::kv_rep) at the drafter's block of 16, windowed and not, and the h256/gqa2
* decode with q as a slice of a wider row, at one row and at a verify's sixteen. */
for (const char* kvd : { "fp8_e4m3", "bf16" }) {
const bool f8 = !std::strcmp(kvd, "bf16") ? false : true;
const char* r128 = f8 ? "attn_qrow_h128_gqa8_fp8kv" : "attn_qrow_h128_gqa8_bf16kv";
const char* r256 = f8 ? "attn_qrow_decode_h256_gqa2_fp8kv" : "attn_qrow_decode_h256_gqa2_bf16kv";
attn_numeric_case(pl, r128, 128, 8, 16, kvd, 0, 256);
attn_numeric_case(pl, r128, 128, 8, 16, kvd, 48, 256);
attn_numeric_case(pl, r128, 128, 8, 1, kvd, 0, 256, 16, 2048);
attn_numeric_case(pl, r256, 256, 2, 1, kvd, 0, 256, 16, 2048);
attn_numeric_case(pl, r256, 256, 2, 16, kvd, 0, 256, 16, 2048);
attn_numeric_case(pl, r256, 256, 2, 16, kvd, 64, 256);
}
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, with the model's window of 1024: exercises the
@@ -26131,14 +26303,20 @@ static void device_phase(const Plugin& pl) {
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");
if (sel("qkv_norm_rope_bf16") || sel("qkv_norm_rope_kv_store_fp8") ||
sel("qkv_norm_rope_kv_store_bf16")) {
if (!g_case) std::printf("\nqkv_norm_rope, and with kv_store folded in, against the 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);
}
if (sel("add_rmsnorm_bf16")) {
if (!g_case) std::printf("\nadd_rmsnorm, against add then rmsnorm\n");
add_rmsnorm_numeric(pl);
}
/* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape asks
* these kernels for. Both rows run: an fc declared over M 1..64 resolves to _m16 for small
+56
View File
@@ -340,6 +340,20 @@ extern "C" int r4d_shape_rmsnorm(const RadParam* p, int n_p, int operand,
R4D_PICK(l);
}
/* add_rmsnorm -- rmsnorm's operands with the addend after x. */
extern "C" int r4d_shape_add_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = {
opd(D, M, n),
opd(D, M, n),
opd((uint32_t)RAD_F32, n),
opd(D, M, n),
};
R4D_PICK(l);
}
/* ---- the vision tower's (r4d_vit_bf16.hip). Every optional operand is passed: the norm's bias and
* the GEMM's residual are the same code with a branch taken, so this covers both forms. */
extern "C" int r4d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
@@ -1076,6 +1090,48 @@ extern "C" int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p,
R4D_PICK(l);
}
/* qkv_norm_rope -- separate q [M, n_head * head_dim], k and v [M, n_head_kv * head_dim] (dense
* here; the shim also takes each as a slice of a wider row), the positions, and the q and k gains,
* f32 as every architecture plugin declares them (shim in r4d_qkv_norm_rope.hip). As for `rope`,
* a position is not a lookup: the kernel takes sincos of position x frequency, so it is drawn over
* a context's range, where the angles a decode step sees are, not over the band's rows. */
extern "C" int r4d_shape_qkv_norm_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t hd = pi(p, n_p, "head_dim");
const int64_t nq = pi(p, n_p, "n_head");
const int64_t nkv = pi(p, n_p, "n_head_kv");
const RadOpdDesc l[] = {
/* at n_head 0 the kernel reads no q; it is passed as k's buffer, so drawn like k */
opd((uint32_t)RAD_BF16, M, (nq ? nq : nkv) * hd),
opd((uint32_t)RAD_BF16, M, nkv * hd),
opd((uint32_t)RAD_BF16, M, nkv * hd),
opd_idx(M, 0, 32768),
opd((uint32_t)RAD_F32, hd),
opd((uint32_t)RAD_F32, hd),
};
R4D_PICK(l);
}
/* qkv_norm_rope_kv_store -- qkv_norm_rope's six, then kv_store's slot mapping (unique slots, as
* the engine hands them) and its paged cache, sized as kv_store's description sizes it. */
extern "C" int r4d_shape_qkv_norm_rope_kv_store(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
if (operand < 6) return r4d_shape_qkv_norm_rope(p, n_p, operand, out);
const int64_t M = pi(p, n_p, "M");
const int64_t hd = pi(p, n_p, "head_dim");
const int64_t kvh = pi(p, n_p, "n_head_kv");
const int64_t bs = pi(p, n_p, "block_size");
const uint32_t KV = dt_act(p, n_p, "kv_dtype");
if (M <= 0 || bs <= 0) return RAD_E_UNSUPPORTED;
const int64_t nb = (M + bs - 1) / bs + 2;
const RadOpdDesc l[] = {
opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(),
opd_idx(M, 0, nb * bs, -1, RAD_OPD_F_IDX_UNIQUE),
opd(KV, nb, kvh, bs, 2 * hd),
};
R4D_PICK(l);
}
/* rope_table -- the cos/sin plane the fused prologue reads (shim in r4d_qk_norm_rope_gate.hip). */
extern "C" int r4d_shape_rope_table(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {