From d90d90e43a55780a0499b26a4650a1269fa63c42 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Sun, 11 Oct 2026 02:22:48 +0000 Subject: [PATCH] libr4d: qkv_norm_rope -- q/k/v norms and both rotaries of separate projections in one dispatch An attention block with separate q, k and v projections and per-head norms (Gemma 4) runs five single-pass ops between the projections and the cache store: rmsnorm_p on v (or on the raw k where v is k), rmsnorm over the q heads, rmsnorm over the k heads, rope on q, rope on k. qkv_norm_rope does them in one dispatch, one workgroup a (token, head). Byte-identical to the five: the same norm widths r4d_act_threads picks and rope's ladders, head included. The row is constrained to head_dim 256..512 in steps of 256; other shapes keep the five. The selftest compares both of Gemma 4 31B's attention classes at M 1/4/40. --- docs/OPS.md | 6 ++ libr4d/CMakeLists.txt | 1 + libr4d/r4d_plugin.h | 2 + libr4d/r4d_qkv_norm_rope.hip | 190 +++++++++++++++++++++++++++++++++++ libr4d/r4d_rows.cpp | 49 +++++++++ libr4d/r4d_selftest.cpp | 90 +++++++++++++++++ 6 files changed, 338 insertions(+) create mode 100644 libr4d/r4d_qkv_norm_rope.hip diff --git a/docs/OPS.md b/docs/OPS.md index 155a353d..c49ca41d 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -453,6 +453,7 @@ that folds dequantisation into its epilogue still receives them. | `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt | `qkv`:inout, `positions` | | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | | `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w | +| `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | **`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a softcap. Query row `i` of a segment sees the key rows `j` of the same segment with `0 <= i - j <= @@ -485,6 +486,11 @@ of radius `r` (`|i - j| <= r`) is `window = r + 1`. `q`, `k` and `v` may each be `[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read at that projection's row pitch -- which is how a tower's `[q|k|v]` row reaches it without a copy. +**`qkv_norm_rope`** is the same prologue over SEPARATE `q`, `k` and `v` projections (Gemma 4's text +attention, three GEMMs): the q and k norms, the unit-gain value norm and the rotary in one dispatch. +`v_from_k` 1 takes v from the RAW k before the k norm (the k == v global class). The rotary parameters +are `rope`'s, `ladder` included; byte-identical to `rmsnorm_p` + `rmsnorm` x2 + `rope` x2. + **`qk_norm_rope`'s `v_norm`** set to 1 also RMS-norms every v head of the fused row with a UNIT gain and does not rotate it: Gemma 4's value norm, which has no weight to name. diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 8eeb56a0..528ccaec 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -142,6 +142,7 @@ set(R4D_UNITS "r4d_sample_stages_f32|" "r4d_quant_act_i8|" "r4d_rmsnorm_quant_i8|" + "r4d_qkv_norm_rope|" "r4d_had_quant_act_i8|" "r4d_rmsnorm_had_quant_i8|" "r4d_ar_ln_had_quant_i8|" diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 78783ef5..2ab2f1d8 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -301,6 +301,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_quant_act_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream); +int r4d_rad_qkv_norm_rope_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream); int r4d_rad_rmsnorm_quant_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream); diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip new file mode 100644 index 00000000..eb1072fa --- /dev/null +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -0,0 +1,190 @@ +// r4d_qkv_norm_rope.hip - r4d_qkv_norm_rope: the per-head norms and the rotary of separate q, k and +// v projections in one dispatch -- Gemma 4's attention prologue. +// +// WHY. Between its projections and the cache store a Gemma 4 attention block runs five single-pass +// kernels over a few dozen heads: the weightless value norm (rmsnorm_p), the q and the k norms +// (rmsnorm, one row a head) and the two rotaries (rope). At a decode batch each is a handful of +// workgroups, so the block pays five dispatches for work the card does in a fraction of one. This is +// the five as one, one workgroup a (token, head). +// +// BYTE-IDENTICAL TO THE FIVE, for the reason r4d_rmsnorm_quant_i8.hip gives. What makes that hold: +// +// * each norm's sum of squares is taken by THE PARTITION ITS STANDALONE KERNEL USES. rmsnorm runs +// one workgroup a row at r4d_act_threads(rows, head_dim) threads and rmsnorm_p at 256; thread t +// folds columns t, t+THR, ... in order, the waves are summed in order through LDS. Here a +// workgroup is head_dim threads, and thread t < min(THR, head_dim) folds the same columns in the +// same order while the rest hold zero -- which is what the standalone kernel's surplus waves hold +// too, and adding +0.0 to a sum of squares changes no bit; +// * the norm output is rounded to bf16 as the standalone norm stores it, and the rotary reads that; +// * the rotary's per-pair arithmetic is rope_kernel's, written the same way (powf ladder, +// sincosf, `x0*c - x1*s`, `x0*s + x1*c`), under the library's -ffp-contract=off. +// +// `v_from_k` IS GEMMA'S GLOBAL CLASS: k == v, so v is the value norm of the RAW k, taken before the +// k norm rewrites it -- the order the unfused block issues them in. +// +// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_common.h" +#include +#include +#include + +namespace { + +constexpr uint32_t kWave = 32; + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } + +// THR threads' partition of one head's sum of squares, reproduced inside a head_dim-wide workgroup: +// thread t < P = min(THR, HD) folds t, t+P, ...; the waves are then summed in order. +template +__device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_t P, float* lds) { + float ss = 0.0f; + if (threadIdx.x < P) + for (uint32_t i = threadIdx.x; i < HD; i += P) { const float v = bf2f(x[i]); ss += v * v; } + ss = r4d_wave_sum(ss); + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + if (lane == 0) lds[wave] = ss; + __syncthreads(); + float s = 0.0f; +#pragma unroll + for (uint32_t w = 0; w < HD / kWave; ++w) s += lds[w]; + return s; +} + +// The rotary over a normed head staged in `nb`, written to `out`: rope_kernel's body for pair i. +template +__device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t* __restrict__ out, + float p0, uint32_t rot, uint32_t nfreq, int den, float theta) { + const uint32_t half = rot / 2, t = threadIdx.x; + if (t < half) { + float inv = 1.0f / powf(theta, (float)(2 * t) / (float)den); + if (t >= nfreq) inv = 0.0f; + const float ang = p0 * inv; + float c, s; + sincosf(ang, &s, &c); + const float x0 = bf2f(nb[t]), x1 = bf2f(nb[t + half]); + out[t] = f32_to_bf16(x0 * c - x1 * s); + out[t + half] = f32_to_bf16(x0 * s + x1 * c); + } + for (uint32_t i = rot + t; i < HD; i += HD) out[i] = nb[i]; // the unrotated tail +} + +// blockIdx.y: [0, nq) a query head, [nq, nq+nkv) a key head (and with VK its value, from the raw +// key), [nq+nkv, nq+2nkv) a value head normalised in place (without VK). +template +__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( + uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, + const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, + uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, + uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, float mult, + uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos) { + __shared__ float l1[HD / kWave], l2[HD / kWave]; + __shared__ uint16_t nb[HD]; + const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x; + const float div = rscale != 0.0f ? rscale : 1.0f; + // rope rotates the rows its positions cover; a row past them is normed and left unrotated + const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f; + + if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p + uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)(hh - nq - nkv) * HD; + const float s = rsqrtf(head_ss(x, pv, l1) / (float)HD + eps); + __syncthreads(); // every thread has read x before any writes it + for (uint32_t i = t; i < HD; i += HD) x[i] = f32_to_bf16(bf2f(x[i]) * s); + return; + } + const bool isq = hh < nq; + const uint32_t h = isq ? hh : hh - nq; + uint16_t* __restrict__ x = isq ? q + (size_t)m * q_ld + (size_t)h * HD + : k + (size_t)m * k_ld + (size_t)h * HD; + const void* __restrict__ w = isq ? qw : kw; + + if (VK && !isq) { // v = rmsnorm_p(raw k), before the k norm rewrites k + uint16_t* __restrict__ vo = v + (size_t)m * v_ld + (size_t)h * HD; + const float sv = rsqrtf(head_ss(x, pv, l2) / (float)HD + eps); + for (uint32_t i = t; i < HD; i += HD) vo[i] = f32_to_bf16(bf2f(x[i]) * sv); + } + const float s = rsqrtf(head_ss(x, isq ? pq : pk, l1) / (float)HD + eps); + for (uint32_t i = t; i < HD; i += HD) { + const float g = WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]); + nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd) * mult); + } + __syncthreads(); // the normed head is complete before any pair reads across it + if (m < n_pos) rotate(nb, x, p0, rot, nfreq, den, theta); + else for (uint32_t i = t; i < HD; i += HD) x[i] = nb[i]; +} + +} // namespace + +// ============================================================== the plugin ABI entry point +enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW }; + +static int rad_qkv_norm_rope_body(const RadArgs* a, const R4dSink& sk) { + int emit_rc = RAD_OK; + const RadTensor* q = r4d_opt(a, QN_Q); + const RadTensor* k = r4d_opt(a, QN_K); + const RadTensor* v = r4d_opt(a, QN_V); + const RadTensor* ps = r4d_opt(a, QN_POS); + const RadTensor* qw = r4d_opt(a, QN_QW); + const RadTensor* kw = r4d_opt(a, QN_KW); + if (!q || !k || !v || !ps || !qw || !kw) return R4D_NO(RAD_E_INVAL); + if (q->dtype != RAD_BF16 || k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (ps->dtype != RAD_I32 || ps->rank != 1 || !r4d_contig(ps)) return R4D_NO(RAD_E_SHAPE); + if (qw->dtype != kw->dtype || (qw->dtype != RAD_BF16 && qw->dtype != RAD_F32)) return R4D_NO(RAD_E_DTYPE); + const long long hd = r4d_geti_or(a, "head_dim", 0); + const long long nq = r4d_geti_or(a, "n_head", 0); + const long long nkv = r4d_geti_or(a, "n_head_kv", 0); + const long long rot = r4d_geti_or(a, "rotary_dim", hd); + const long long vk = r4d_geti_or(a, "v_from_k", 0); + if (hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE); + if (nq <= 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(qw) != hd || r4d_numel(kw) != hd) return R4D_NO(RAD_E_SHAPE); + const char* mode = r4d_gets(a, "mode"); + if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); + if (r4d_getf(a, "yarn_factor", 0.0) != 0.0) return R4D_NO(RAD_E_UNSUPPORTED); + // rope's ladder, resolved exactly as r4d_rad_rope resolves it + const char* lad = r4d_gets(a, "ladder"); + long long den = rot; + if (lad) { + if (!std::strcmp(lad, "head")) den = hd; + else if (std::strcmp(lad, "rotary")) return R4D_NO(RAD_E_UNSUPPORTED); + } + const long long nfreq = rot / 2; + const long long rot_l = (den == hd && rot < hd) ? hd : rot; + + long long M = 0, Mk = 0, Mv = 0; + const long long q_ld = r4d_rows_pitch(q, nq * hd, &M); + const long long k_ld = r4d_rows_pitch(k, nkv * hd, &Mk); + const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv); + if (q_ld < 0 || k_ld < 0 || v_ld < 0) return R4D_NO(RAD_E_STRIDE); + const long long Mp = r4d_numel(ps); + if (Mp <= 0 || M < Mp || Mk != M || Mv != M) return R4D_NO(RAD_E_SHAPE); + + // the standalone kernels' widths, from the same function: rmsnorm one row a head at + // r4d_act_threads(rows, head_dim), rmsnorm_p at 256 + const uint32_t pq = (uint32_t)std::min(r4d_act_threads((int)(M * nq), (int)hd), hd); + const uint32_t pk = (uint32_t)std::min(r4d_act_threads((int)(M * nkv), (int)hd), hd); + const uint32_t pv = (uint32_t)std::min(256, hd); + const float eps = (float)r4d_getf(a, "eps", 1e-6); + const float wadd = (float)r4d_getf(a, "wadd", 0.0); + const float theta = (float)r4d_getf(a, "theta", 10000.0); + const float rsc = (float)r4d_getf(a, "scale", 1.0); + const float mult = 1.0f; + const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + (vk ? 0 : nkv))); + +#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(sk, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ + (uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \ + r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \ + (uint32_t)v_ld, eps, wadd, mult, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp) +#define R4D_QNR(HD) \ + do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \ + else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0) + if (hd == 256) R4D_QNR(256); + else R4D_QNR(512); +#undef R4D_QNR +#undef R4D_QNR_T + return emit_rc; +} +R4D_ENTRY(r4d_rad_qkv_norm_rope, rad_qkv_norm_rope_body) diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 8796fa22..4b9e8d03 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1340,6 +1340,36 @@ static const RadOperandSpec oRmsNormQuantI8[] = { { "scalar", RAD_OPD_WEIGHT, 1 }, /* [1], multiplies the sum; needs the residual */ }; +/* `qkv_norm_rope` is `qk_norm_rope` over SEPARATE q, k and v projections rather than one fused row: + * the per-head q and k norms, the weightless value norm and the rotary of q and k, in one + * dispatch -- Gemma 4's attention prologue, whose projections are three GEMMs. `v_from_k` 1 is its + * global class (k == v): v is the value norm of the RAW k, written before the k norm rewrites it. + * The rotary parameters are `rope`'s (`ladder` included), the norm parameters `rmsnorm`'s, and the + * op is byte-identical to rmsnorm_p + rmsnorm + rmsnorm + rope + rope. */ +static const RadParamSpec pQkvNormRope[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "head_dim", RAD_P_INT, RAD_REQUIRED }, + { "n_head", RAD_P_INT, RAD_REQUIRED }, + { "n_head_kv", RAD_P_INT, RAD_REQUIRED }, + P_F64("theta"), + P_F64("eps"), + P_F64O("scale"), + { "mode", RAD_P_STR, RAD_OPTIONAL }, + { "rotary_dim", RAD_P_INT, RAD_OPTIONAL }, + { "ladder", RAD_P_STR, RAD_OPTIONAL }, + P_F64O("wadd"), + { "v_from_k", RAD_P_INT, RAD_OPTIONAL }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec oQkvNormRope[] = { + { "q", RAD_OPD_INOUT, 0 }, + { "k", RAD_OPD_INOUT, 0 }, + { "v", RAD_OPD_INOUT, 0 }, /* written from the raw k under v_from_k */ + { "positions", RAD_OPD_IN, 0 }, + { "q_w", RAD_OPD_WEIGHT, 0 }, + { "k_w", RAD_OPD_WEIGHT, 0 }, +}; + static const RadParamSpec pGatedQuantFp8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -2333,6 +2363,9 @@ 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("qkv_norm_rope", pQkvNormRope, oQkvNormRope, + "per-head q and k RMS norms, the weightless v norm and the rotary of q and k over separate " + "q, k and v projections, in one dispatch; v from the raw k under v_from_k."), SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, "silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."), SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, @@ -3192,6 +3225,10 @@ static const RadConstraint cQuantActI8[] = { static const RadConstraint cRmsNormQuantI8[] = { C_DIV("n", 16), C_IN("dtype", "bf16"), }; +/* head_dim 256 or 512: a workgroup is one head, a thread one channel. */ +static const RadConstraint cQkvNormRope[] = { + C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), +}; static const RadConstraint cHadQuantActI8[] = { C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"), }; @@ -5588,6 +5625,18 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_rmsnorm_quant_i8, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, r4d_rad_rmsnorm_quant_i8_describe }, +{ "qkv_norm_rope_bf16", "qkv_norm_rope", "attn", + "per-head RMS norms of separate q and k projections, the weightless norm of v (or of the raw k), " + "and the rotary of q and k, in place, in one dispatch", + "head_dim 256 or 512; neox, `rotary` or `head` ladder, one position component, no YaRN; one " + "workgroup a (token, head), a thread a channel", + "bf16 q/k/v and gains (or f32 gains), i32 positions; byte-identical to rmsnorm_p + rmsnorm x2 + " + "rope x2, each norm taken by its standalone kernel's partition", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkvNormRope), NOTUNE, + nullptr, nullptr, r4d_rad_qkv_norm_rope, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, r4d_rad_qkv_norm_rope_describe }, + { "had_quant_act_i8", "had_quant_act_i8", "quant", "block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes " "int8 activations usable at all: unrotated, the per-row absmax is set by a few outlier channels " diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index c6fe32aa..2ccffe25 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -4922,6 +4922,92 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { } } +/* ---- qkv_norm_rope, against the five ops it replaces ------------------------------------------ + * + * rmsnorm_p (v, or the raw k under v_from_k), rmsnorm over the q heads and over the k heads, then + * rope over q and over k -- kernel by kernel, against the one dispatch. Both of Gemma 4 31B's + * classes at one rank of two: sliding (head_dim 256, 16 q over 8 kv heads, full rotary, separate v) + * and global (512, 16 over 2, the proportional `head` ladder over 128, k == v), at batch heights + * that put the q/k norms at every width r4d_act_threads answers -- including 256 at head_dim 512, + * where a thread of the standalone norm folds two channels. */ +static void qkv_norm_rope_numeric(const Plugin& pl) { + const RadKernelInfo* np = find(pl, "rmsnorm_p_bf16"); + const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); + const RadKernelInfo* rp = find(pl, "rope_bf16"); + const RadKernelInfo* fz = find(pl, "qkv_norm_rope_bf16"); + if (!np || !nrm || !rp || !fz) { ok("qkv_norm_rope vs its five", false, "rows absent"); return; } + struct Cls { int64_t hd, nq, nkv, rot; const char* ladder; double theta; bool vk; }; + for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false }, + Cls{ 512, 16, 2, 128, "head", 1000000.0, true } }) { + for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40 }) { + const int64_t QD = cl.nq * cl.hd, KD = cl.nkv * cl.hd; + std::vector hq((size_t)M * QD), hk((size_t)M * KD), hv((size_t)M * KD); + std::vector hqw((size_t)cl.hd), hkw((size_t)cl.hd); + std::vector hp((size_t)M); + for (size_t i = 0; i < hq.size(); ++i) hq[i] = h_to_bf16(0.031f * (float)((i * 37) % 97) - 1.4f); + for (size_t i = 0; i < hk.size(); ++i) hk[i] = h_to_bf16(0.027f * (float)((i * 53) % 89) - 1.1f); + for (size_t i = 0; i < hv.size(); ++i) hv[i] = h_to_bf16(0.023f * (float)((i * 29) % 83) - 0.9f); + for (int64_t c = 0; c < cl.hd; ++c) { + hqw[(size_t)c] = h_to_bf16(0.6f + 0.004f * (float)((c * 19) % 51)); + hkw[(size_t)c] = h_to_bf16(0.5f + 0.005f * (float)((c * 11) % 47)); + } + for (int64_t m = 0; m < M; ++m) hp[(size_t)m] = (int32_t)(1000 + 7 * m); + void* dq[2] = { dalloc(hq.size() * 2), dalloc(hq.size() * 2) }; + void* dk[2] = { dalloc(hk.size() * 2), dalloc(hk.size() * 2) }; + void* dv[2] = { dalloc(hv.size() * 2), dalloc(hv.size() * 2) }; + void* dqw = dalloc(hqw.size() * 2); + void* dkw = dalloc(hkw.size() * 2); + void* dp = dalloc(hp.size() * 4); + if (!dq[1] || !dk[1] || !dv[1] || !dqw || !dkw || !dp) { ok("qkv_norm_rope alloc", false, "hipMalloc failed"); return; } + for (int j = 0; j < 2; ++j) { + st_memcpy(dq[j], hq.data(), hq.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dk[j], hk.data(), hk.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dv[j], hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + } + st_memcpy(dqw, hqw.data(), hqw.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dkw, hkw.data(), hkw.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dp, hp.data(), hp.size() * 4, hipMemcpyHostToDevice); + const double eps = 1e-6, wadd = 0.0; + /* --- the five, in the order the unfused block issues them --- */ + int rc = launch_row(np, { T(cl.vk ? dk[0] : dv[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dv[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, + { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(nrm, { T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }), T(dqw, RAD_BF16, { cl.hd }), T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }) }, + { PI("M", M * cl.nq), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); + if (rc == RAD_OK) + rc = launch_row(nrm, { T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dkw, RAD_BF16, { cl.hd }), T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, + { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); + for (int j = 0; j < 2 && rc == RAD_OK; ++j) + rc = launch_row(rp, { T(j ? dk[0] : dq[0], RAD_BF16, { M, (j ? cl.nkv : cl.nq) * cl.hd }), T(dp, RAD_I32, { M }) }, + { PI("M", M), PI("head_dim", cl.hd), PI("n_head", j ? cl.nkv : cl.nq), PI("n_head_kv", 0), + PF("theta", cl.theta), PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), + PS("ladder", cl.ladder) }); + /* --- the one --- */ + if (rc == RAD_OK) + rc = launch_row(fz, { T(dq[1], RAD_BF16, { M, QD }), T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }), + T(dp, RAD_I32, { M }), T(dqw, RAD_BF16, { cl.hd }), T(dkw, RAD_BF16, { cl.hd }) }, + { PI("M", M), PI("head_dim", cl.hd), PI("n_head", cl.nq), PI("n_head_kv", cl.nkv), + PF("theta", cl.theta), PF("eps", eps), PF("scale", 1.0), PS("mode", "neox"), + PI("rotary_dim", cl.rot), PS("ladder", cl.ladder), PF("wadd", wadd), + PI("v_from_k", cl.vk ? 1 : 0), PS("dtype", "bf16") }); + const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + " M=" + std::to_string(M); + if (rc != RAD_OK) { ok((what + " vs its five").c_str(), false, "rc=" + std::to_string(rc)); continue; } + int nd = 0, moved = 0; + for (int t = 0; t < 3; ++t) { + void* const* d = t == 0 ? dq : (t == 1 ? dk : dv); + const size_t n = t == 0 ? hq.size() : hk.size(); + std::vector a(n), b(n); + st_memcpy(a.data(), d[0], n * 2, hipMemcpyDeviceToHost); + st_memcpy(b.data(), d[1], n * 2, hipMemcpyDeviceToHost); + const std::vector& h0 = t == 0 ? hq : (t == 1 ? hk : hv); + for (size_t i = 0; i < n; ++i) { nd += a[i] != b[i]; moved += b[i] != h0[i]; } + } + ok((what + " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2").c_str(), nd == 0 && moved > 0, + "differs " + std::to_string(nd) + ", changed from the input " + std::to_string(moved)); + } + } +} + /* ---- rmsnorm_quant_i8, against the chain it replaces ------------------------------------------ * * Byte-identical, for the reason the fp8 fusions above give, in all three forms a sandwich-norm @@ -13473,6 +13559,10 @@ static void device_phase(const Plugin& pl) { if (!g_case) std::printf("\nthe fp8 fusions, against the pair each one replaces\n"); fused_quant_fp8_numeric(pl); } + if (sel("qkv_norm_rope_bf16")) { + if (!g_case) std::printf("\nqkv_norm_rope, against the five ops it replaces\n"); + qkv_norm_rope_numeric(pl); + } if (sel("rmsnorm_quant_i8")) { if (!g_case) std::printf("\nrmsnorm_quant_i8, against the chain it replaces\n"); rmsnorm_quant_i8_numeric(pl);