From f92cce07f12691788bd2b5a4fec6aee3b62468c7 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH] libr4d: Gemma 3's rows -- windowed h128/gqa2 attention, qkv_norm_rope at h128 without a value norm, ar_rmsnorm_post_quant_fp8 - r4d_attn_paged_h128_gqa2w.hip: decode and query-tiled prefill at head_dim 128, gqa 2, window >= 1, instantiations of the h256/gqa6 templates with WIN = 1 (as h256_gqa2 for Gemma 4); the h128/gqa2 rows keep window 0. - qkv_norm_rope: head_dim 128, and an optional v_norm (0 leaves v alone). - ar_rmsnorm_post_quant_fp8: ar_rmsnorm_quant_fp8 with a post-norm of the reduced sum against w_post before the residual add (the sandwich junction), exact wire only. Its own op: an optional seventh operand on ar_rmsnorm_quant_fp8 broke every plugin issuing its six. r4d_selftest: the windowed rows against the inline oracle over a history past the window, and qkv_norm_rope at h128 / v_norm 0 byte-identical to its chain. Co-Authored-By: Claude Opus 5.5 --- docs/OPS.md | 3 +- libr4d/CMakeLists.txt | 2 + libr4d/r4d.h | 8 ++- libr4d/r4d_ar_entry.hip | 10 ++- libr4d/r4d_attn_paged_h128_gqa2w.hip | 82 +++++++++++++++++++++ libr4d/r4d_attn_paged_h256_gqa6.hip | 21 ++++++ libr4d/r4d_fused_quant_fp8.hip | 41 +++++++++-- libr4d/r4d_plugin.h | 7 ++ libr4d/r4d_qkv_norm_rope.hip | 12 ++-- libr4d/r4d_rows.cpp | 103 +++++++++++++++++++++++++++ libr4d/r4d_selftest.cpp | 21 ++++-- 11 files changed, 291 insertions(+), 19 deletions(-) create mode 100644 libr4d/r4d_attn_paged_h128_gqa2w.hip diff --git a/docs/OPS.md b/docs/OPS.md index 81c231ab..3592b153 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -687,7 +687,7 @@ bytes). | `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 `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/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 | +| `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 `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | **`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each band. @@ -1644,6 +1644,7 @@ device code. | op | params | operands | |---|---|---| | `ar_rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | +| `ar_rmsnorm_post_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w | | `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? | | `ar_hc_write` | `M`(range) `n` `hc` `world_size` `dtype` `wire`/opt | `y`:inout, `inj`, `h`:inout | | `ar_gather_hc_write` | `M`(range) `n` `hc` `top_k` `world_size` `dtype` `act`/opt `wire`/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`?, `y`:inout, `inj`, `h`:inout | diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 05afe635..a8944e37 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -44,6 +44,8 @@ set(R4D_UNITS # Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode and # prefill. "r4d_attn_paged_h256_gqa2|" + # Gemma 3 sliding window: head_dim 128, 2 queries per KV head, windowed decode and prefill. + "r4d_attn_paged_h128_gqa2w|" # Eight queries per KV head, one body instantiated at head_dim 256 (the routed 35B-A3B) and 128 # (MiniCPM5-2B). "r4d_attn_paged_gqa8|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 869c12c9..9308639e 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -100,6 +100,12 @@ int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa2_bf16kv (const R4DArgs* a, hipStream_t stream); long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a); +/* Gemma 3 sliding window (r4d_attn_paged_h128_gqa2w.hip): head_dim 128, gqa 2, window >= 1. */ +int r4d_attn_prefill_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream); +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); // 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); @@ -726,7 +732,7 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off); + long loc_pack, long loc_scale_off, long wp = 0); int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void); // The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 80cf89fd..1f348c96 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -1156,7 +1156,7 @@ extern "C" int r4d_rad_ar_twoshot_4rank_ti8(const RadArgs* a, RadStream s) { /* ------------------------------------------------------------------ the fused all-reduce + norm */ -enum { AL_X = 0, AL_RESID, AL_W, AL_Q, AL_SCALE, AL_OUTBF16 }; +enum { AL_X = 0, AL_RESID, AL_W, AL_Q, AL_SCALE, AL_OUTBF16, AL_WPOST }; extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); @@ -1250,8 +1250,13 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const RadTensor* q = r4d_opt(a, AL_Q); const RadTensor* sc = r4d_opt(a, AL_SCALE); const RadTensor* ob = r4d_opt(a, AL_OUTBF16); + /* ar_rmsnorm_quant_fp8's optional post-norm (Gemma 3's sandwich); ar_ln_had_quant_i8 has no + * seventh operand, and this function serves only the fp8 op. */ + const RadTensor* wpo = r4d_opt(a, AL_WPOST); if (!x || !w || !q || !sc) return RAD_E_INVAL; if (!r4d_contig(w)) return RAD_E_STRIDE; + if (wpo && (!rs || !r4d_contig(wpo) || r4d_numel(wpo) != r4d_numel(w) || wpo->dtype != w->dtype)) + return RAD_E_SHAPE; /* Rank 2 everywhere, as in rmsnorm_quant_fp8: a norm has a gain per channel, so flattening * everything after dim 0 into the row would put one gain across several heads. */ @@ -1291,6 +1296,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { /* This rank's packed-half side buffer exists for every bf16 instance; missing means a * broken init. */ if (!in->locpack) return RAD_E_STATE; + if (wpo) return RAD_E_UNSUPPORTED; // the post-norm is the exact wire's only } R4dArCfg cfgv; @@ -1327,7 +1333,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32, (int)rp, (int)yp, (int)qp, (int)sp, (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire, - in->locpack, in->slot_bytes / 2); + in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0); return e == 0 ? RAD_OK : RAD_E_SHAPE; } diff --git a/libr4d/r4d_attn_paged_h128_gqa2w.hip b/libr4d/r4d_attn_paged_h128_gqa2w.hip new file mode 100644 index 00000000..8024553e --- /dev/null +++ b/libr4d/r4d_attn_paged_h128_gqa2w.hip @@ -0,0 +1,82 @@ +// R4D attention dispatch for Gemma 3's sliding-window layers (arch/gemma3, TranslateGemma 27B): +// head_dim 128, 2 queries per KV head (32 over 16, 16 over 8 at TP2), paged block 16, window 1024 +// (52 of 62 layers). Instantiations of the h256/gqa6 kernel templates with WIN = 1, as +// r4d_attn_paged_h256_gqa2.hip does at head_dim 256 for Gemma 4. +// +// Both bands: decode (q_len * gqa <= 64, so q_len <= 32) and the query-tiled prefill kernel. The +// windowless h128/gqa2 rows (r4d_attn_paged_h128_gqa2.hip) keep window == 0; these rows take +// window >= 1 only, so the global layers stay on the tuned full-attention legs. +#include "r4d.h" +#include "r4d_attn_args.h" +#include "r4d_common.h" +#include +#include +using std::max; +// The decode kernel uses helpers from the prefill unit, so prefill is included first. Both kernels +// are instantiated here with WIN = 1. +#include "r4d_attn_prefill_h256_gqa6.hip" +#include "r4d_attn_decode_h256_gqa6.hip" + +#define CHK4() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0) + +#define B_HEAD_DIM 128 +#define B_GQA 2 +#define B_BLOCK_SIZE 16 +#define B_TILE 16 // decode: r4d_decode_launch_win (r4d_attn_decode_h256_gqa6.hip) +// The DFlash2 drafter's head_dim 128 windowed decode set (r4d_attn_paged_h128_gqa4.hip): K +// prefetch 2 and O_KRAW. Not separately tuned for gqa 2. +#define B_OPT 20207163 + +extern "C" long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a) { + return r4d_decode_scratch(a, r4d_decode_splits_win(a, B_TILE), B_OPT); +} + +extern "C" int r4d_attn_decode_h128_gqa2w_fp8kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} +extern "C" int r4d_attn_decode_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} + +// ---- prefill --------------------------------------------------------------------------------- +// The windowless h128 prefill option set (r4d_attn_paged_gqa8.hip, G8_P_OPT_128: no O_KWIDE, which +// is a head_dim 256 fetch, K prefetch 4) with WIN on. At gqa 2 a block covers NWARPS * 16 / 2 = 192 +// query positions. window <= 0 would give full attention, but the rows never send one here. +#define P_NWARPS 24 +#define P_TILE 48 +#define P_OPT 3430923 + +template +static int prefill_launch_h128_gqa2w(const R4DArgs* a, hipStream_t s) { + if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1; + if (a->q_heads / a->kv_heads != B_GQA) return -2; + constexpr int BQ = (P_NWARPS * 16) / B_GQA; + dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs); + hipLaunchKernelGGL((r4d_attn_prefill_kernel), + grid, dim3(P_NWARPS * 32), 0, s, *a); + CHK4(); + return 0; +} + +extern "C" int r4d_attn_prefill_h128_gqa2w_fp8kv(const R4DArgs* a, hipStream_t s) { + return prefill_launch_h128_gqa2w<0>(a, s); +} +extern "C" int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s) { + return prefill_launch_h128_gqa2w<1>(a, s); +} + +/* Prefill RadArgs wrappers. Absent descales mean 1.0 (fill_paged leaves them null). The decode + * wrappers are in r4d_attn_paged_h256_gqa6.hip beside decode_common. */ +extern "C" int r4d_rad_attn_prefill_h128_gqa2w_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = fill_paged(a, &r, B_HEAD_DIM); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h128_gqa2w_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_prefill_h128_gqa2w_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = fill_paged(a, &r, B_HEAD_DIM); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h128_gqa2w_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 947612a1..6a94e226 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -186,6 +186,7 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) { static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) { if (which == 1) return (int64_t)r4d_attn_decode_h128_gqa4_scratch_bytes(r); if (which == 2) return (int64_t)r4d_attn_decode_h256_gqa2_scratch_bytes(r); + if (which == 3) return (int64_t)r4d_attn_decode_h128_gqa2w_scratch_bytes(r); return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r); } @@ -297,3 +298,23 @@ extern "C" int r4d_rad_attn_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) if (rc != RAD_OK) return rc; return r4d_attn_decode_h256_gqa2_bf16kv(&r, (hipStream_t)s); } + +/* Gemma 3 sliding window (head_dim 128, gqa 2, window 1024) decode; its prefill entry points + * are in r4d_attn_paged_h128_gqa2w.hip. */ +extern "C" int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs* a) { + return decode_scratch(a, 128, 3); +} + +extern "C" int r4d_rad_attn_decode_h128_gqa2w_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 128, 3); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h128_gqa2w_fp8kv(&r, (hipStream_t)s); +} + +extern "C" int r4d_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 128, 3); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h128_gqa2w_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index 7fb8b679..ea31d0dd 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -363,9 +363,13 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) { return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM); } -template +// POST: a sandwich-norm junction (Gemma 3): the reduced sum is post-normed against `wp` before the +// residual add, `v = bf16(sum * s1 * (wp + wadd))` with s1 the sum's own rms, as rmsnorm_quant_i8's +// POST computes it. `x` still receives the reduced sum. Exact wire and a residual only. +template __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s, int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, char* loc_pack, long loc_scale_off, int M, uint32_t n, uint32_t nkb, @@ -546,6 +550,27 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( (void)pr; float ss = 0.0f; + if constexpr (POST && WIRE == 0 && RES) { + /* Pass one reduces and takes the sum's sum of squares; pass two post-norms it, adds it + * into the stream and takes the stream's. Each thread reads back only its own columns. */ + float s1s = 0.0f; + for (uint32_t i = tid; i < n; i += THR) { + const uint16_t a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); + xr[i] = a; + const float av = bf2f(a); + s1s += av * av; + } + const float s1 = rsqrtf(block_sum(s1s, lds) / (float)n + eps); + __syncthreads(); // lds is reused by the second sum + for (uint32_t i = tid; i < n; i += THR) { + const float g = WF32 ? ((const float*)wp)[i] : bf2f(((const uint16_t*)wp)[i]); + const uint16_t pv = f2bf(bf2f(xr[i]) * s1 * (g + wadd)); + const uint16_t h = f2bf(bf2f(rr[i]) + bf2f(pv)); + rr[i] = h; + const float v = bf2f(h); + ss += v * v; + } + } else for (uint32_t i = tid; i < n; i += THR) { /* The exact wire reduces here, in the norm's first pass; the compressed one already * reduced into `x`. */ @@ -741,8 +766,9 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off) { + long loc_pack, long loc_scale_off, long wp) { if (!x || !w || !q || !s) return -1; + if (wp && (!res || wire != 0)) return -10; // a post-norm needs the stream and the exact wire if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1; if (M <= 0 || n <= 0) return -2; // n % 8: n bf16 is a whole number of 16B words (see the push), which also gives every lane its @@ -765,18 +791,22 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long // The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order). const int thr = nthreads ? nthreads : r4d_act_threads(M, n); if (thr != 256 && thr != 512 && thr != 1024) return -6; -#define R4D_ARQ_T(wf, rs, T, W) \ - hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel), dim3((uint32_t)nb), dim3(T), \ +#define R4D_ARQ_P(wf, rs, T, W, PO) \ + hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel), dim3((uint32_t)nb), dim3(T), \ 0, \ (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, (const void*)w, \ + (const void*)wp, \ (uint16_t*)y, (uint8_t*)q, (float*)s, (int4*)peer_scratch, \ (const int4*)my_scratch, (unsigned int*)peer_flags, \ (unsigned int*)my_flags, (unsigned int*)seq_ctrs, (char*)loc_pack, \ (long)loc_scale_off, M, (uint32_t)n, \ (uint32_t)nkb, eps, wadd, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \ (uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw) +#define R4D_ARQ_T(wf, rs, T, W) R4D_ARQ_P(wf, rs, T, W, false) #define R4D_ARQ_W(wf, rs, T) \ - do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); else R4D_ARQ_T(wf, rs, T, 0); } while (0) + do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \ + else if (rs && wp) R4D_ARQ_P(wf, rs, T, 0, true); \ + else R4D_ARQ_T(wf, rs, T, 0); } while (0) #define R4D_ARQ(wf, rs) \ do { if (thr == 1024) R4D_ARQ_W(wf, rs, 1024); \ else if (thr == 512) R4D_ARQ_W(wf, rs, 512); \ @@ -786,6 +816,7 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long #undef R4D_ARQ #undef R4D_ARQ_W #undef R4D_ARQ_T +#undef R4D_ARQ_P return hipGetLastError() == hipSuccess ? 0 : -4; } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index b6a81f1c..41253c21 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -104,6 +104,13 @@ int r4d_rad_attn_prefill_h256_gqa2_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*); +/* Gemma 3 sliding window (r4d_attn_paged_h128_gqa2w.hip): head_dim 128, 2 queries per KV head, + * window >= 1. Decode (q_len*gqa <= 64) and windowed prefill, as the h256/gqa2 pair above. */ +int r4d_rad_attn_prefill_h128_gqa2w_fp8 (const RadArgs*, RadStream); +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*); /* 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. */ diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip index 8947fbdb..0ebf24d9 100644 --- a/libr4d/r4d_qkv_norm_rope.hip +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -136,7 +136,10 @@ 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); - if (hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE); + // v_norm 0: no value norm at all (Gemma 3); the v heads are left out of the grid. + 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 (r4d_numel(qw) != hd || r4d_numel(kw) != hd) return R4D_NO(RAD_E_SHAPE); const char* mode = r4d_gets(a, "mode"); @@ -169,7 +172,7 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { 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 dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + (vk ? 0 : nkv))); + const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + ((vk || !vn) ? 0 : nkv))); #define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(stream, (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), \ @@ -178,8 +181,9 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { #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); + if (hd == 128) R4D_QNR(128); + else if (hd == 256) R4D_QNR(256); + else R4D_QNR(512); #undef R4D_QNR #undef R4D_QNR_T return emit_rc; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index ef5fd83b..77bc9c73 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1252,6 +1252,19 @@ static const RadOperandSpec oArRmsNormQuantFp8[] = { { "out_bf16", RAD_OPD_OUT, 1 }, }; +/* ar_rmsnorm_post_quant_fp8: the same with a sandwich post-norm of the reduced sum before the add + * (Gemma 3's junction, arch/gemma3), exact wire only. Its own op: an optional seventh operand on + * ar_rmsnorm_quant_fp8 would break every plugin that issues that op's six. */ +static const RadOperandSpec oArRmsNormPostQuantFp8[] = { + { "x", RAD_OPD_INOUT, 0 }, + { "residual", RAD_OPD_INOUT, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, + { "w_post", RAD_OPD_WEIGHT, 0 }, +}; + /* `rmsnorm_quant_i8` is the norm with r4d_gemm_w4a8_nt_m64's activation producer on its pass: * int8 codes in the GEMM's fragment order and one f32 scale per row (quant_act_i8's grid, not * quant_act_i8g's per-group one nor the rotated rmsnorm_had_quant_i8's). Its first six operands are @@ -1295,6 +1308,7 @@ static const RadParamSpec pQkvNormRope[] = { { "ladder", RAD_P_STR, RAD_OPTIONAL }, P_F64O("wadd"), { "v_from_k", RAD_P_INT, RAD_OPTIONAL }, + { "v_norm", RAD_P_INT, RAD_OPTIONAL }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; static const RadOperandSpec oQkvNormRope[] = { @@ -2908,6 +2922,10 @@ static const RadOpSchema kSchemas[] = { "the two-rank all-reduce and the residual add, RMS norm, rotation and quantisation " "that always follow it, in one kernel."), + SCHEMA("ar_rmsnorm_post_quant_fp8", pArRmsNormQuantFp8, oArRmsNormPostQuantFp8, + "ar_rmsnorm_quant_fp8 with a post-norm of the reduced sum against w_post before the " + "residual add (a sandwich-norm junction), exact wire only, byte-identical to all_reduce, " + "rmsnorm, rmsnorm_quant_fp8."), SCHEMA("ar_rmsnorm_quant_fp8", pArRmsNormQuantFp8, oArRmsNormQuantFp8, "the two-rank all-reduce and the residual add, RMS norm and block-scaled fp8 " "quantisation that always follow it, in one kernel. Both wires."), @@ -3149,6 +3167,25 @@ static const RadConstraint cAttnPrefillH256Gqa2Bf16[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; +/* Gemma 3 sliding window: head_dim 128, 2 queries per kv head (r4d_attn_paged_h128_gqa2w.hip). + * window >= 1 only: window 0 at this geometry is the tuned full-attention pair above. Decode is + * q_len <= 32 (q_len*gqa <= 64), prefill takes the rest. */ +static const RadConstraint cAttnDecodeH128Gqa2wFp8[] = { + C_GE("window", 1), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnDecodeH128Gqa2wBf16[] = { + C_GE("window", 1), C_EQ("head_dim", 128), 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"), +}; +static const RadConstraint cAttnPrefillH128Gqa2wFp8[] = { + C_GE("window", 1), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnPrefillH128Gqa2wBf16[] = { + C_GE("window", 1), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; /* Eight queries per KV head, at both head widths (r4d_attn_paged_gqa8.hip). q_len <= 8 is * `q_len * gqa <= 64` at gqa 8: a decode workgroup holds 64 rows, each query position claims gqa * of them. As on the gqa6 leg, it is also the decode/prefill bucket boundary (spec §2.2). */ @@ -3894,6 +3931,10 @@ static const RadConstraint cRmsNormQuantI8[] = { static const RadConstraint cQkvNormRope[] = { C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), }; +/* Gemma 3's prologue (arch/gemma3): head_dim 128, usually with v_norm 0. */ +static const RadConstraint cQkvNormRopeH128[] = { + C_EQ("head_dim", 128), C_IN("dtype", "bf16"), +}; static const RadConstraint cGeluMulQuantI8[] = { C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), }; @@ -5057,6 +5098,46 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_prefill_h128_gqa2w_fp8kv", "attn_paged", "attn", + "paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)", + "head_dim 128, 2 queries per kv head, paged block 16, varlen, window >= 1 from the launch argument", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH128Gqa2wFp8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa2w_fp8, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_prefill_h128_gqa2w_bf16kv", "attn_paged", "attn", + "paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)", + "head_dim 128, 2 queries per kv head, paged block 16, varlen, window >= 1 from the launch argument", + "bf16 query, bf16 kv cache, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH128Gqa2wBf16), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa2w_bf16, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h128_gqa2w_fp8kv", "attn_paged", "attn", + "paged causal attention with a sliding window, split-KV (decode / verify)", + "head_dim 128, 2 queries per kv head, paged block 16, q_len*gqa <= 64, window >= 1 from the " + "launch argument", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH128Gqa2wFp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2w_fp8, r4d_rad_attn_decode_h128_gqa2w_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h128_gqa2w_bf16kv", "attn_paged", "attn", + "paged causal attention with a sliding window, split-KV (decode / verify)", + "head_dim 128, 2 queries per kv head, paged block 16, q_len*gqa <= 64, window >= 1 from the " + "launch argument", + "bf16 query, bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH128Gqa2wBf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2w_bf16, r4d_rad_attn_decode_h128_gqa2w_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + { "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 8 queries per kv head, paged block 16, varlen", @@ -6550,6 +6631,17 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cQkvNormRope), NOTUNE, nullptr, nullptr, r4d_rad_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, " + "and the rotary of q and k, in place, in one dispatch", + "head_dim 128; 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(cQkvNormRopeH128), NOTUNE, + nullptr, nullptr, r4d_rad_qkv_norm_rope }, + { "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", @@ -6625,6 +6717,17 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, /* `all_reduce` + `rmsnorm_quant_fp8`, both wires (r4d_fuse.cpp). */ r4d_fuse_ar_rmsnorm_quant_fp8 }, +{ "ar_rmsnorm_post_quant_fp8", "ar_rmsnorm_post_quant_fp8", "quant", + "the two-rank all-reduce, a post-norm of the reduced sum, the residual add, RMS norm and " + "block-scaled fp8 quantisation in one kernel: a sandwich-norm junction (Gemma 3)", + "exactly 2 ranks, the exact wire; n a multiple of 8 and x unpitched; group 128; a block owns whole " + "rows; the residual is required", + "bf16 in, E4M3 out with an f32 scale per (row, 128 columns); x receives the reduced sum", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cArRmsNormQuantFp8), ROW(tAr), nullptr, + r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_fp8, nullptr, nullptr, nullptr, + nullptr }, + { "ar_hc_write", "ar_hc_write", "norm", "the two-rank all-reduce and the gated residual's write that always follows it, in one kernel: " "h[s] += inj[s] * y over the reduced y", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 9a49f50f..bf57bd61 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -9208,16 +9208,19 @@ static void gelu_mul_quant_i8_numeric(const Plugin& pl) { * over q and 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 reaching - * every width r4d_act_threads answers, including 256 at head_dim 512 (two channels per thread). */ + * every width r4d_act_threads answers, including 256 at head_dim 512 (two channels per thread). + * Gemma 3's class (head_dim 128, 16 q over 8 kv heads at one rank of two) has no value norm + * (v_norm 0), so its chain is four ops and v must come back untouched. */ 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 } }) { + 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 } }) { 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); @@ -9248,7 +9251,8 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { 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 }) }, + 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) 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 }) }, @@ -9268,7 +9272,7 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { { 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_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); if (rc != RAD_OK) { ok((what + " vs its five").c_str(), false, "rc=" + std::to_string(rc)); continue; } int nd = 0, moved = 0; @@ -18393,6 +18397,11 @@ static void device_phase(const Plugin& pl) { attn_case(pl, "attn_decode_h128_gqa2_fp8kv", 128, 2, 1, "fp8_e4m3", 0); attn_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 1, "bf16", 0); attn_numeric_case(pl, "attn_prefill_h128_gqa2_fp8kv", 128, 2, 64, "fp8_e4m3", 0, 256); + /* Gemma 3's sliding layers: head_dim 128, gqa 2, window 1024, over a history past it. */ + attn_numeric_case(pl, "attn_prefill_h128_gqa2w_fp8kv", 128, 2, 64, "fp8_e4m3", 1024, 2048); + attn_numeric_case(pl, "attn_prefill_h128_gqa2w_bf16kv", 128, 2, 64, "bf16", 1024, 2048); + attn_numeric_case(pl, "attn_decode_h128_gqa2w_fp8kv", 128, 2, 1, "fp8_e4m3", 1024, 2048); + attn_numeric_case(pl, "attn_decode_h128_gqa2w_bf16kv", 128, 2, 8, "bf16", 1024, 2048); attn_numeric_case(pl, "attn_prefill_h128_gqa2_bf16kv", 128, 2, 64, "bf16", 0, 256); attn_numeric_case(pl, "attn_decode_h128_gqa2_fp8kv", 128, 2, 1, "fp8_e4m3", 0, 256); attn_numeric_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 1, "bf16", 0, 256);