From 833173cc049a48d7311ffbde2670069a5a79ba0a Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 09:58:28 -0500 Subject: [PATCH] gemma4k: Gemma 4's kernels beyond libr4d -- paged attention, pair_argmax, the sandwich joins A kernel library beside libr4d, gfx12 only, and AHEAD of it for Gemma 4: `--kernels gemma4k,libr4d,...`. Its own library rather than rows in libr4d: a smaller change, its own gfx12 gating, and no churn in libr4d's row table; folding it in can follow. - attn_paged at head_dim 256 and 512, gqa 1/2/4/8, bf16 or fp8 cache, any window, causal or not. One scalar kernel serves decode, verify and prefill, with a split-KV path whose merge is one wave a row (live pieces found by ballot, four at a time; a piece that saw no key writes only its max and sum); a WMMA prefill kernel takes a query of at least 64 rows and 32 a sequence on average -- Q and K bf16, P and V f16 (bf16 P measured 0.25% of the V range in error), the denominator summed from the rounded P. RADIANCE_G4K_WMMA=0 keeps every launch on the scalar kernel. - pair_argmax, device and host, described as libref describes it so rad-kbench checks both. - norm_add_norm and join_add_scale, ops of its own (docs/OPS.md, a new subsection): each one kernel for a post-norm / residual add / pre-norm chain, rounding where the chain rounds. libref has no row for them on purpose -- a reference row would resolve them where gemma4k is not loaded and the architecture would never fall back to the chain -- and no row declares `replaces`, since rad-kbench assembles a replaced chain from the fusing library's own rows. WHY FIRST. libr4d on this tree also has rows at h256/gqa2 and h512/gqa8, Gemma 4's own geometries, written for the dense 31B (which has no drafter) and not measured on the 26B-A4B or under a DFlash verify; the hierarchy is absolute, so the first library takes them. These rows are the ones every Gemma 4 number below was measured with. No other row overlaps libr4d's (the h256 gqa4/gqa8 rows take a window only), so putting this library first takes nothing else from it. The softcap is libr4d's and libavx's `logit_softcap`. Measured on 4x R9700, gemma-4-26B-A4B-it + z-lab DFlash, TP4: decode attention 3.234 -> 0.104 ms a step on the full layers and 1.906 -> 0.722 on the sliding ones (the split-KV merge); a 20,489-token prefill 4.01 -> 2.83 s (the WMMA kernel); rad-kbench against libref 176/176. Not yet run on the cards: the joins. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 6 + docs/OPS.md | 25 + gemma4k/CMakeLists.txt | 34 ++ gemma4k/g4k.h | 38 ++ gemma4k/g4k_attn.hip | 1146 ++++++++++++++++++++++++++++++++++++++++ gemma4k/g4k_launch.h | 14 + gemma4k/g4k_norm.hip | 252 +++++++++ gemma4k/g4k_pick.hip | 105 ++++ gemma4k/g4k_rows.cpp | 436 +++++++++++++++ tests/CMakeLists.txt | 5 + 10 files changed, 2061 insertions(+) create mode 100644 gemma4k/CMakeLists.txt create mode 100644 gemma4k/g4k.h create mode 100644 gemma4k/g4k_attn.hip create mode 100644 gemma4k/g4k_launch.h create mode 100644 gemma4k/g4k_norm.hip create mode 100644 gemma4k/g4k_pick.hip create mode 100644 gemma4k/g4k_rows.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0d4b60dd..d188d488 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -358,6 +358,12 @@ add_subdirectory(libquant) if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt) add_subdirectory(libr4d) endif() +# gemma4k: Gemma 4's kernels beyond libr4d -- paged attention at head_dim 256/512, pair_argmax, +# and the two sandwich-norm joins (docs/OPS.md). gfx12 only, and ahead of libr4d for Gemma 4: +# `--kernels gemma4k,libr4d,...` (gemma4k/g4k_rows.cpp says why). +if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/gemma4k/CMakeLists.txt) + add_subdirectory(gemma4k) +endif() # libavx: the conventional op vocabulary in hand-written x86 SIMD, runtime-dispatched by CPU # feature -- the production HOST kernels, built wherever libref is, on x86-64. An op the placement # puts on the host needs a host kernel that is not the oracle (rad_gate_reference_kernels refuses diff --git a/docs/OPS.md b/docs/OPS.md index dcbefa00..cbb4451d 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -294,6 +294,31 @@ rounding. -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's torch expressions are, then rounded. +### The sandwich-norm joins — no reference row + +| op | params | operands | +|---|---|---| +| `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | +| `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w | + +Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`. +`norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y` -- a post-norm, the +residual add, the next pre-norm. `join_add_scale` is `x = (x + rmsnorm(rmsnorm(d) * w_d + +rmsnorm(r) * w_r) * w_j) * s` -- two arms' post-norms, their sum, its norm, the residual add and a +one-element layer scalar (Gemma 4's MoE feed-forward). Every value the chain stores is rounded to +the activation dtype at the same point, so the two differ from the chain only in the order a sum +of squares is added in: with the same order they are bit-identical to it, and against a chain +summed in another block width a norm factor can differ in its last bit. + +**libref has no row for either, on purpose.** An architecture asks for a join and declares the +chain where it does not resolve (`rad_op_resolved`), and a reference row would resolve it +everywhere -- so a model loaded without the library that serves the join would resolve it to the +reference and be refused at serve, instead of running the chain on libr4d or libavx. The +`gemma4k` kernel library declares both (device and host rows); with no oracle, its kernels are held +to the chain bit for bit by `tests/g4k_emu`, and no row declares `replaces`, because rad-kbench +assembles a replaced chain from the fusing library's own rows and gemma4k has none of the chain's +ops. + ## Quantisation and rotation | op | params | operands | diff --git a/gemma4k/CMakeLists.txt b/gemma4k/CMakeLists.txt new file mode 100644 index 00000000..6fa5692a --- /dev/null +++ b/gemma4k/CMakeLists.txt @@ -0,0 +1,34 @@ +# gemma4k -- Gemma 4's kernels beyond libr4d: paged attention at head_dim 256/512 (gqa 1/2/4/8, any +# window), pair_argmax (the sharded draft head's cross-rank top-1), and the two sandwich-norm +# joins, which are ops of its own (docs/OPS.md). Ahead of libr4d for Gemma 4 (g4k_rows.cpp). +# +# Built inside radiance's tree (add_subdirectory(gemma4k) beside libr4d) or on its own against an +# installed radiance -- the same rad_add_plugin either way: +# cmake -S gemma4k -B build-g4k -DCMAKE_PREFIX_PATH=/opt/radiance && cmake --build build-g4k +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(gemma4k LANGUAGES CXX HIP) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +if(NOT RAD_HIP_FOUND) + message(STATUS "gemma4k: this radiance has no device build (RAD_HIP_FOUND is OFF) -- skipped") + return() +endif() +# gfx12 only, as libr4d: the kernels are wave32 and read an fp8 cache with RDNA4's hardware +# conversion; the software fallback compiles elsewhere but spills. +rad_plugin_gpu_targets(_g4k_targets "^gfx12") +if(NOT _g4k_targets) + message(STATUS "gemma4k: no gfx12 target in RAD_GPU_TARGETS (${RAD_GPU_TARGETS}) -- skipped") + return() +endif() + +rad_add_plugin(gemma4k kernels + SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/g4k_rows.cpp + HIP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/g4k_attn.hip ${CMAKE_CURRENT_SOURCE_DIR}/g4k_pick.hip + ${CMAKE_CURRENT_SOURCE_DIR}/g4k_norm.hip + GPU_TARGETS ${_g4k_targets}) +string(REPLACE ";" " " _g4k_desc "${_g4k_targets}") +target_compile_definitions(gemma4k PRIVATE "G4K_BUILD_TARGET=\"${_g4k_desc}\"") +set_target_properties(gemma4k PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON) diff --git a/gemma4k/g4k.h b/gemma4k/g4k.h new file mode 100644 index 00000000..d6e109c1 --- /dev/null +++ b/gemma4k/g4k.h @@ -0,0 +1,38 @@ +/* g4k.h -- what gemma4k's row table (g4k_rows.cpp, host C++) needs from its device units + * (g4k_attn.hip, g4k_pick.hip, g4k_norm.hip). Plain C declarations: the row table compiles + * without HIP. */ +#ifndef G4K_H +#define G4K_H + +#include "rad_abi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* attn_paged at (head_dim, gqa, kv dtype). One entry point per instantiation, named for its + * geometry, refusing anything else at launch. */ +#define G4K_ATTN_DECL(HD, G) \ + int g4k_attn_h##HD##_gqa##G##_bf16kv(const RadArgs* a, RadStream s); \ + int g4k_attn_h##HD##_gqa##G##_fp8kv(const RadArgs* a, RadStream s); +G4K_ATTN_DECL(256, 1) G4K_ATTN_DECL(256, 2) G4K_ATTN_DECL(256, 4) G4K_ATTN_DECL(256, 8) +G4K_ATTN_DECL(512, 1) G4K_ATTN_DECL(512, 2) G4K_ATTN_DECL(512, 4) G4K_ATTN_DECL(512, 8) +#undef G4K_ATTN_DECL + +/* The split-KV partials one launch can need, at declare (rad_abi.h RadScratchFn). */ +int64_t g4k_attn_h256_scratch(const RadArgs* a); +int64_t g4k_attn_h512_scratch(const RadArgs* a); + +/* pair_argmax on the device: the top-1 of a row of gathered (id, value) pairs, as one i32 a row. */ +int g4k_pair_argmax_f32(const RadArgs* a, RadStream s); + +/* Gemma 4's sandwich-norm joins, one kernel each (g4k_norm.hip): + * norm_add_norm operands a, w_a, x (inout), w_y, y + * join_add_scale operands d, w_d, r, w_r, w_j, x (inout), s */ +int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream s); +int g4k_join_add_scale_bf16(const RadArgs* a, RadStream s); + +#ifdef __cplusplus +} +#endif +#endif /* G4K_H */ diff --git a/gemma4k/g4k_attn.hip b/gemma4k/g4k_attn.hip new file mode 100644 index 00000000..6ffebce9 --- /dev/null +++ b/gemma4k/g4k_attn.hip @@ -0,0 +1,1146 @@ +/* g4k_attn.hip -- paged attention at the head geometries libr4d does not compile: head_dim 256 and + * 512, 1/2/4/8 queries per KV head, ANY sliding window, causal or not, bf16 or fp8-e4m3 cache. + * + * Gemma 4's text layers need two of them and libr4d has neither: its sliding layers are 16 query + * heads over 8 KV heads at head_dim 256 with a 1024-token window (gqa 2 at every TP), and its full + * layers 16 over 2 at head_dim 512 (gqa 8 at TP1/TP2, 4 at TP4, 2 at TP8). libr4d's h256 rows are + * gqa 4/6/8/12 and all of them `window == 0`. + * + * WHAT THIS IS. Two kernels behind one entry point. The scalar one, for decode and verify steps: one + * workgroup owns one (sequence, KV head, slice of BQ query positions, split of the key range); each + * wave owns RW of the tile's R = BQ*gqa query rows; K and V come through LDS one paged block (or + * two) at a time, prefetched into registers while the previous tile is being consumed; the dot + * products are scalar FMAs with a butterfly reduce-scatter that leaves key j's score in lane j; the + * softmax is online, in the log2 domain. It is memory-bound at decode, where that is the only thing + * that matters. A prefill-shaped launch takes the WMMA kernel further down instead (its own header + * says how), which feeds RDNA4's matrix cores. + * + * WHAT IT COMPUTES is libref's ref_attn_paged, predicate for predicate: + * pos = seqused[s] - q_len(s) + i (seqused INCLUDES this step's queries) + * causal key j visible when j <= pos; non-causal when j < seqused[s] + * window causal: pos - j < window; non-causal: |pos - j| < window; 0 = none + * a block-table entry < 0 is a missing block: its keys are not visible + * no visible key at all -> a zero row + * k_descale / v_descale per (sequence, kv head), absent = 1 + * + * THE PAGED LAYOUT is kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V inside a slot, which + * makes one block of one KV head ONE contiguous run of 16 * 2 * head_dim elements: a key tile is + * one or two such runs, fetched as 16-byte loads. + * + * SPLIT-KV. A launch with few (tile, kv head) pairs -- a decode step, a short verify -- would leave + * most of the card idle, so the key range of each tile is cut into `n_split` pieces, each written + * as an unnormalised partial (acc, max, sum) into the op's scratch, and a second kernel merges + * them. The split count is chosen at launch from host-side numbers only (rows, sequences, the + * window or max_ctx); each workgroup divides ITS OWN key range by it, so a split that receives no + * keys writes (0, -inf, 0) and the merge needs no host knowledge of the device-side context. + * + * Nothing here allocates, synchronises, or uses anything but hipLaunchKernel (docs/PLUGIN.md §5). + * Wave32 (RDNA): the shuffles and the reduce-scatter are written for 32 lanes. + */ +#include + +#include +#include + +#include "g4k.h" +#include "g4k_launch.h" +#include "rad_plugin.h" + +#if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32 +#error "gemma4k's attention is written for wave32 (RDNA): build without -mwavefrontsize64" +#endif + +namespace g4k { + +constexpr int kThreads = 256; +constexpr int kWaves = kThreads / 32; + +/* split-KV bookkeeping: at most this many (tile, kv head, split) triples carry partials, and the + * tile table behind them holds at most kTinfoMax tiles. The launch keeps under both by + * construction; the scratch hook sizes for exactly these. */ +constexpr int kPartBudget = 192; +constexpr int kTinfoMax = 128; +constexpr int kMaxSplit = 64; + +template struct Geo; +/* R query rows a workgroup (R / 8 a wave), BK keys a tile. BK * 2 * HD bf16 = 32 KiB of LDS either + * way: two paged blocks at 256, one at 512. */ +template <> struct Geo<256> { static constexpr int R = 32, BK = 32; }; +template <> struct Geo<512> { static constexpr int R = 16, BK = 16; }; + +/* ------------------------------------------------------------------ device helpers */ +__device__ __forceinline__ int lane_id() { return (int)(threadIdx.x & 31u); } + +__device__ __forceinline__ float shfl_xor(float v, int m) { + return __int_as_float(__builtin_amdgcn_ds_bpermute((lane_id() ^ m) << 2, __float_as_int(v))); +} +__device__ __forceinline__ int shfl_up(int v, int d) { + const int l = lane_id(); + return __builtin_amdgcn_ds_bpermute((l >= d ? l - d : l) << 2, v); +} +__device__ __forceinline__ float readlane(float v, int l) { + return __int_as_float(__builtin_amdgcn_readlane(__float_as_int(v), l)); +} +__device__ __forceinline__ float wave_max(float v) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v = __builtin_fmaxf(v, shfl_xor(v, d)); + return v; +} +__device__ __forceinline__ float wave_sum(float v) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v += shfl_xor(v, d); + return v; +} +__device__ __forceinline__ float ex2(float x) { +#if __has_builtin(__builtin_amdgcn_exp2f) + return __builtin_amdgcn_exp2f(x); /* v_exp_f32: exp2(-inf) = 0 */ +#else + return exp2f(x); +#endif +} +__device__ __forceinline__ int imin(int a, int b) { return a < b ? a : b; } +__device__ __forceinline__ int imax(int a, int b) { return a > b ? a : b; } + +/* f(Ic<0>{}), ..., f(Ic{}): a loop whose index is a CONSTANT in every body, unconditionally. + * `#pragma unroll` is a request the unroller drops past a size threshold -- the fp8 legs of the + * row loop crossed it -- and a register array indexed by a loop variable that survives is demoted + * to scratch memory. This cannot be dropped. */ +template struct Ic { static constexpr int value = I; }; +template struct StaticFor { + template __device__ __forceinline__ static void run(F& f) { + if constexpr (I < N) { + f(Ic{}); + StaticFor::run(f); + } + } +}; + +__device__ __forceinline__ void bf16x4(uint2 w, float (&f)[4]) { + f[0] = __uint_as_float(w.x << 16); + f[1] = __uint_as_float(w.x & 0xffff0000u); + f[2] = __uint_as_float(w.y << 16); + f[3] = __uint_as_float(w.y & 0xffff0000u); +} +/* OCP E4M3 (e4m3fn, bias 7, 0x7f/0xff NaN, no infinity) -- the KV cache's bytes at + * --kv-cache-dtype fp8 (docs/PLUGIN.md §10). Exact; subnormals kept. */ +__device__ __forceinline__ float fp8e4m3(unsigned b) { + const unsigned e = (b >> 3) & 15u, m = b & 7u; + float v = e ? __uint_as_float(((e + 120u) << 23) | (m << 20)) : (float)m * 0.001953125f; + if (e == 15u && m == 7u) v = __uint_as_float(0x7fc00000u); + return __uint_as_float(__float_as_uint(v) | ((b & 0x80u) << 24)); +} +__device__ __forceinline__ void fp8x4(unsigned w, float (&f)[4]) { +#if defined(__GFX12__) + /* v_cvt_pk_f32_fp8: RDNA4 converts OCP E4M3 in hardware, two bytes an instruction -- the same + * instruction libr4d reads its fp8 cache with. */ + const auto a = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, false); + const auto b = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, true); + f[0] = a[0]; f[1] = a[1]; f[2] = b[0]; f[3] = b[1]; +#else + f[0] = fp8e4m3(w & 0xffu); + f[1] = fp8e4m3((w >> 8) & 0xffu); + f[2] = fp8e4m3((w >> 16) & 0xffu); + f[3] = fp8e4m3(w >> 24); +#endif +} +/* f32 -> bf16, round to nearest even, NaN kept quiet (rad_plugin.h's rad_f32_to_bf16). */ +__device__ __forceinline__ unsigned bf16_rtne(float f) { + unsigned u = __float_as_uint(f); + if ((u & 0x7fffffffu) > 0x7f800000u) return (u >> 16) | 0x40u; + u += 0x7fffu + ((u >> 16) & 1u); + return u >> 16; +} +__device__ __forceinline__ unsigned pack2(float a, float b) { return bf16_rtne(a) | (bf16_rtne(b) << 16); } + +/* Four elements of one slot row, at element offset `e`, out of the LDS tile. */ +template +__device__ __forceinline__ void lds4(const unsigned char* row, int e, float (&f)[4]) { + if constexpr (KV8) fp8x4(*(const unsigned*)(row + e), f); + else bf16x4(*(const uint2*)(row + 2 * e), f); +} + +/* THE REDUCE-SCATTER. Each lane holds a partial dot for every key of the tile; after it, lane l + * holds key l's full sum. Each step keeps the half of the vector its lane bit selects and adds the + * partner's copy of that half: 16 + 8 + 4 + 2 + 1 = 31 shuffles for 32 keys, against 32 * 5 for 32 + * separate reductions. */ +template +__device__ __forceinline__ void reduce_scatter(float (&v)[N], int lane) { + if constexpr (H >= 1) { + const bool up = (lane & H) != 0; +#pragma unroll + for (int i = 0; i < H; ++i) { + /* VALUES, not lvalues: `up ? v[i + H] : v[i]` selects between two ADDRESSES, and an + * array addressed by a lane-dependent pointer is demoted to scratch memory. */ + const float lo = v[i], hi = v[i + H]; + const float keep = up ? hi : lo; + const float send = up ? lo : hi; + v[i] = keep + shfl_xor(send, H); + } + reduce_scatter(v, lane); + } +} + +/* ------------------------------------------------------------------ the launch's arguments */ +struct AttnArgs { + const uint16_t* q; long long q_rs, q_hs; /* elements */ + const unsigned char* kv; long long kv_sb, kv_sh; /* elements of the cache's dtype */ + const int* bt; long long bt_rs; + const int* seqused; + const int* cu; /* null: uniform q_len */ + const float* kdes; + const float* vdes; + uint16_t* out; long long o_rs, o_hs; + float* part; /* split-KV partials, or null */ + int* tinfo; /* [tile] = (first row, positions) */ + float qscale; /* softmax scale * log2(e) */ + int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split; +}; + +/* Tile `tile` of a ragged batch: the sequence it belongs to and which BQ-position slice of that + * sequence's query it is. Tiles are numbered sequence by sequence, ceil(q_len(s) / BQ) each, so the + * answer is a prefix sum over cu_seqlens -- done by the whole block, 256 sequences a pass. Every + * thread returns the same answer: it is read back out of LDS after a barrier. */ +template +__device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int* s_res, int& s_out, + int& lt_out) { + constexpr int NW = NT / 32; + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + if (tid == 0) { s_res[0] = -1; s_res[1] = 0; } + __syncthreads(); + int base = 0; + for (int c0 = 0; c0 < n_seq; c0 += NT) { + const int s = c0 + tid; + int nt = 0; + if (s < n_seq) { + const int ql = cu[s + 1] - cu[s]; + nt = ql > 0 ? (ql + BQ - 1) / BQ : 0; + } + int x = nt; + for (int d = 1; d < 32; d <<= 1) { + const int y = shfl_up(x, d); + if (lane >= d) x += y; + } + if (lane == 31) s_scan[wave] = x; + __syncthreads(); + int before = 0, total = 0; + for (int w = 0; w < NW; ++w) { + const int v = s_scan[w]; + before += (w < wave) ? v : 0; + total += v; + } + const int incl = base + before + x; + if (nt > 0 && tile >= incl - nt && tile < incl) { s_res[0] = s; s_res[1] = tile - (incl - nt); } + base += total; + __syncthreads(); + if (s_res[0] >= 0 || base > tile) break; + } + s_out = s_res[0]; + lt_out = s_res[1]; +} + +/* ------------------------------------------------------------------ the attention kernel */ +template +__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { + constexpr int R = Geo::R, BK = Geo::BK, RW = R / kWaves, BQ = R / GQA; + constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */ + constexpr int ESZ = KV8 ? 1 : 2; + constexpr int KEY_BYTES = 2 * HD * ESZ; /* one slot: K then V */ + constexpr int TILE_U4 = BK * KEY_BYTES / 16; + constexpr int NPT = TILE_U4 / kThreads; /* 16-byte loads a thread, per tile */ + constexpr int BLK_U4 = 16 * KEY_BYTES / 16; /* one paged block of one kv head */ + constexpr int NB = BK / 16; /* paged blocks a key tile spans */ + static_assert(R % kWaves == 0 && R % GQA == 0, "rows must split over waves and heads"); + static_assert(TILE_U4 % kThreads == 0 && BLK_U4 % kThreads == 0, "tile must split over threads"); + static_assert(BK == 32 || BK == 16, "the reduce-scatter is written for 16 or 32 keys"); + + __shared__ uint4 s_kv[TILE_U4]; + __shared__ int s_scan[kWaves]; + __shared__ int s_res[2]; + + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y, z = (int)blockIdx.z; + + /* ---- which sequence, and which slice of its query */ + int s = -1, lt = 0; + if (A.cu) { + find_tile(A.cu, A.n_seq, tile, s_scan, s_res, s, lt); + } else { + s = tile / A.tps; + lt = tile - s * A.tps; + if (s >= A.n_seq) s = -1; + } + int qlen = 0, tokb = 0, ctx = 0; + if (s >= 0) { + if (A.cu) { tokb = A.cu[s]; qlen = A.cu[s + 1] - tokb; } + else { tokb = s * A.q_len; qlen = A.q_len; } + ctx = A.seqused[s]; + } + const int pfirst = lt * BQ; + const int npos = s >= 0 ? imax(0, imin(BQ, qlen - pfirst)) : 0; + if (A.n_split > 1 && kh == 0 && z == 0 && tid == 0) { + A.tinfo[2 * tile] = tokb + pfirst; + A.tinfo[2 * tile + 1] = npos; + } + if (npos <= 0) return; /* uniform across the block */ + + const int tok0 = tokb + pfirst; + const int qbase = ctx - qlen + pfirst; /* absolute position of the tile's first query */ + const int plast = qbase + npos - 1; + const int causal = A.causal, window = A.window; + + /* ---- the tile's key range, and this split's share of it */ + int hi = causal ? plast + 1 : ctx; + if (!causal && window > 0) hi = imin(hi, plast + window); + hi = imin(imin(hi, ctx), A.max_blocks * 16); + const int lo = window > 0 ? imax(0, qbase - window + 1) : 0; + const int lo_a = lo & ~(BK - 1); + const int nkt = hi > lo_a ? (hi - lo_a + BK - 1) / BK : 0; + const int per = (nkt + A.n_split - 1) / A.n_split; + const int kt_lo = imin(nkt, z * per), kt_hi = imin(nkt, kt_lo + per); + + const float kds = A.kdes ? A.kdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float vds = A.vdes ? A.vdes[(long long)s * A.kv_heads + kh] : 1.0f; + + /* ---- this wave's query rows: row r is position r / GQA, head kh * GQA + r % GQA */ + float qf[RW][NC][4], o[RW][NC][4], m[RW], l[RW]; + int pos[RW]; + bool val[RW]; +#pragma unroll + for (int i = 0; i < RW; ++i) { + const int r = wave * RW + i, p = r / GQA, g = r - p * GQA; + val[i] = p < npos; + pos[i] = qbase + p; + m[i] = -__builtin_inff(); + l[i] = 0.0f; + const uint16_t* qp = A.q + (long long)(tok0 + p) * A.q_rs + (long long)(kh * GQA + g) * A.q_hs; + const float qs = A.qscale * kds; /* k_descale folds into the query */ +#pragma unroll + for (int c = 0; c < NC; ++c) { + float f[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + if (val[i]) bf16x4(*(const uint2*)(qp + c * 128 + lane * 4), f); +#pragma unroll + for (int e = 0; e < 4; ++e) { qf[i][c][e] = f[e] * qs; o[i][c][e] = 0.0f; } + } + } + + /* ---- the key tiles, prefetched one ahead through registers */ + uint4 pre[NPT]; + bool pre_ok[NB]; + auto fetch = [&](int kt) __attribute__((always_inline)) { + const int k0 = lo_a + kt * BK; + const unsigned char* src[NB]; +#pragma unroll + for (int b = 0; b < NB; ++b) { + const int lb = (k0 >> 4) + b; + int blk = -1; + if (lb < A.max_blocks && (lb << 4) < hi) blk = A.bt[(long long)s * A.bt_rs + lb]; + pre_ok[b] = blk >= 0; + /* never a null: a select against null makes the pointer FLAT rather than global, and + * every tile load a flat_load. A missing block points at the cache's base and its + * value is replaced by zeros below. */ + src[b] = A.kv + ((long long)(blk >= 0 ? blk : 0) * A.kv_sb + (long long)kh * A.kv_sh) * ESZ; + } +#pragma unroll + for (int i = 0; i < NPT; ++i) { + const int b = (i * kThreads) / BLK_U4; /* constant: BLK_U4 is a multiple of 256 */ + const int off = tid + i * kThreads - b * BLK_U4; + if (pre_ok[b]) pre[i] = ((const uint4*)src[b])[off]; + else pre[i] = make_uint4(0u, 0u, 0u, 0u); + } + }; + + const unsigned char* sb = (const unsigned char*)s_kv; + if (kt_lo < kt_hi) fetch(kt_lo); + for (int kt = kt_lo; kt < kt_hi; ++kt) { + __syncthreads(); /* the previous tile is consumed */ +#pragma unroll + for (int i = 0; i < NPT; ++i) s_kv[tid + i * kThreads] = pre[i]; + const bool ok0 = pre_ok[0], ok1 = pre_ok[NB - 1]; /* values: see reduce_scatter */ + __syncthreads(); + const int k0 = lo_a + kt * BK; + if (kt + 1 < kt_hi) fetch(kt + 1); + + const int jl = lane & (BK - 1); /* the key this lane scores */ + const int kk = k0 + jl; + const bool kok = (jl < 16 ? ok0 : ok1) && kk >= lo && kk < hi; + + auto row_step = [&](auto ic) __attribute__((always_inline)) { + constexpr int i = decltype(ic)::value; + if (!val[i]) return; /* uniform: one row, all lanes */ + float sc[BK]; +#pragma unroll + for (int j = 0; j < BK; ++j) { + const unsigned char* row = sb + j * KEY_BYTES; + float acc = 0.0f; +#pragma unroll + for (int c = 0; c < NC; ++c) { + float k[4]; + lds4(row, c * 128 + lane * 4, k); +#pragma unroll + for (int e = 0; e < 4; ++e) acc = __builtin_fmaf(qf[i][c][e], k[e], acc); + } + sc[j] = acc; + } + if constexpr (BK == 32) { + reduce_scatter<16, BK>(sc, lane); + } else { +#pragma unroll + for (int j = 0; j < BK; ++j) sc[j] += shfl_xor(sc[j], 16); + reduce_scatter<8, BK>(sc, lane); + } + const int pq = pos[i]; + bool vis = kok && (causal ? kk <= pq : true); + if (window > 0) vis = vis && (pq - kk < window) && (causal || kk - pq < window); + const float sv = vis ? sc[0] : -__builtin_inff(); + const float mn = __builtin_fmaxf(m[i], wave_max(sv)); + if (mn == -__builtin_inff()) return; /* nothing visible yet: uniform */ + const float corr = ex2(m[i] - mn); + const float p = vis ? ex2(sv - mn) : 0.0f; + l[i] = l[i] * corr + wave_sum((BK == 16 && lane >= 16) ? 0.0f : p); +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int e = 0; e < 4; ++e) o[i][c][e] *= corr; +#pragma unroll + for (int j = 0; j < BK; ++j) { + const float pj = readlane(p, j); /* uniform; a masked key's V is never read */ + if (pj != 0.0f) { + const unsigned char* row = sb + j * KEY_BYTES; +#pragma unroll + for (int c = 0; c < NC; ++c) { + float v[4]; + lds4(row, HD + c * 128 + lane * 4, v); +#pragma unroll + for (int e = 0; e < 4; ++e) o[i][c][e] = __builtin_fmaf(pj, v[e], o[i][c][e]); + } + } + } + m[i] = mn; + }; + StaticFor<0, RW>::run(row_step); + } + + /* ---- out: normalised bf16 rows, or this split's partials */ +#pragma unroll + for (int i = 0; i < RW; ++i) { + if (!val[i]) continue; + const int r = wave * RW + i, p = r / GQA, g = r - p * GQA; + if (A.n_split == 1) { + const float inv = l[i] > 0.0f ? vds / l[i] : 0.0f; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs; +#pragma unroll + for (int c = 0; c < NC; ++c) + *(uint2*)(op + c * 128 + lane * 4) = + make_uint2(pack2(o[i][c][0] * inv, o[i][c][1] * inv), + pack2(o[i][c][2] * inv, o[i][c][3] * inv)); + } else { + const long long slot = (((long long)tile * A.kv_heads + kh) * A.n_split + z) * R + r; + float* pp = A.part + slot * (HD + 4); + if (lane == 0) { pp[HD] = m[i]; pp[HD + 1] = l[i]; } + /* no key visible to this row in this split: the merge weighs it 0 and never reads its + * accumulator, so it is not written (uniform: m is the wave's) */ + if (m[i] == -__builtin_inff()) continue; +#pragma unroll + for (int c = 0; c < NC; ++c) + *(float4*)(pp + c * 128 + lane * 4) = + make_float4(o[i][c][0] * vds, o[i][c][1] * vds, o[i][c][2] * vds, o[i][c][3] * vds); + } + } +} + +/* ================================================================== the WMMA prefill kernel + * + * WHY A SECOND KERNEL. The kernel above is scalar FMAs: right for decode, where a step is a few + * rows and the cache read is the whole cost, and about 8 TFLOP/s a card on a long prefill, where + * the global layers' attention is quadratic in the prompt and 46% of a 48k-token prefill. RDNA4's + * matrix cores do a 16x16x16 bf16 product a WMMA instruction; this kernel feeds them. It is chosen + * at launch for prefill-shaped steps only (a sequence with >= kWmmaMinQ query rows) and computes + * the same function, predicate for predicate. + * + * THE LAYOUTS (RDNA4, wave32, v_wmma_f32_16x16x16_bf16 -- confirmed against llama.cpp's mma.cuh, + * which runs on the card): A[M][K] gives lane L row M = L % 16 and K = 8 * (L / 16) .. + 7; B[K][N] + * gives lane L column N = L % 16 and the same K; the f32 result gives lane L column N = L % 16 and + * rows M = 8 * (L / 16) .. + 7. So the kernel computes S TRANSPOSED: S^T = K * Q^T puts each + * lane's eight values in ONE query row (row L % 16, keys 8h .. 8h + 7), the row's other eight keys + * in lane L ^ 16 -- the softmax statistics are one shuffle -- and those eight values, as bf16, are + * exactly the B operand of O^T = V^T * P^T. O^T's lane L likewise holds only row L % 16, so the + * online-softmax rescale is a per-lane scalar. + * + * THE SPLIT. O^T for 16 rows of a 512-dim head is 256 f32 a lane -- the whole register file. So a + * wave owns 16 rows by a 128-dim slice of the head (kDQ): its Q^T (32 VGPRs) and O^T (64). The + * slices of one row group each compute S^T over their own dims; the partials meet in LDS and every + * slice sums them in the same order, so all of them see bit-identical scores and take identical + * softmax steps. 16 waves: h512 is 4 row groups of 4 slices (64 rows), h256 8 of 2 (128 rows). + * + * THE TILE is one paged block, 16 keys. K goes to LDS as it is ([key][dim] bf16, a 16-byte pad a row + * so the A-fragment reads hit 32 different banks); V goes TRANSPOSED ([dim][key], rows of 48 + * bytes), since the PV product reduces over keys and an operand's eight K-values must be + * contiguous. The transposed write is two keys' dims packed a dword, the dword index rotated per + * lane group so a wave's 32 writes land in 32 banks. An fp8 cache is widened on the way in -- exact, + * e4m3 has 3 mantissa bits. Keys outside the tile's range or in a missing block are written as + * zeros: a probability of 0 times a NaN in a recycled slot is still NaN. + * + * P AND V IN f16, Q AND K IN bf16. The probabilities are rounded for the matrix product, and bf16's + * 8 bits leave 2^-9 of |v| in every output -- measured in the emulator against f64 at up to 0.25% + * of the V range, four times the scalar kernel's error. f16 runs at the same rate with 11 bits. V's + * bf16 values are exact in f16 between 2^-14 and 65504 (clamped beyond, NaN kept); an fp8 cache's + * are exact outright. The denominator sums the probabilities as rounded, so a row is a true + * weighted mean of V: a dominant key keeps weight 1 exactly. + */ +typedef short g4k_v8s __attribute__((ext_vector_type(8))); /* 8 bf16, as the builtin takes them */ +typedef float g4k_v8f __attribute__((ext_vector_type(8))); +typedef _Float16 g4k_v8h __attribute__((ext_vector_type(8))); + +constexpr int kWThreads = 512; +constexpr int kWWaves = kWThreads / 32; +constexpr int kDQ = 128; /* dims of a wave's slice of the head */ +constexpr int kWmmaMinQ = 64; /* a launch whose longest query is shorter stays scalar */ + +template struct WGeo { + static constexpr int NS = HD / kDQ; /* slices: waves sharing one 16-row group */ + static constexpr int RG = kWWaves / NS; /* row groups a workgroup */ + static constexpr int R = RG * 16; /* rows a workgroup */ + static constexpr int KS = HD * 2 + 16; /* bytes a key row of the K tile */ + static constexpr int VS = 48; /* bytes a dim row of the V^T tile: 16 keys + pad */ +}; + +__device__ __forceinline__ g4k_v8f wmma_bf16(g4k_v8s a, g4k_v8s b, g4k_v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); +} +__device__ __forceinline__ g4k_v8f wmma_f16(g4k_v8h a, g4k_v8h b, g4k_v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +} +/* f32 -> f16 bits, round to nearest even; a finite value past f16's range saturates, NaN stays */ +__device__ __forceinline__ unsigned f16_bits(float f) { + if (f == f) f = __builtin_fminf(__builtin_fmaxf(f, -65504.0f), 65504.0f); + return (unsigned)__builtin_bit_cast(unsigned short, (_Float16)f); +} +__device__ __forceinline__ void fp8x16_f16(const uint4 w, unsigned (&h)[16]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + float f[4]; + fp8x4(in[q], f); +#pragma unroll + for (int e = 0; e < 4; ++e) h[q * 4 + e] = f16_bits(f[e]); + } +} +__device__ __forceinline__ void bf16x8_f16(const uint4 w, unsigned (&h)[8]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + h[2 * q] = f16_bits(__uint_as_float(in[q] << 16)); + h[2 * q + 1] = f16_bits(__uint_as_float(in[q] & 0xffff0000u)); + } +} +/* fp8 e4m3 -> bf16 bits (the K tile), exact: the f32 a byte widens to has nothing below bit 16 */ +__device__ __forceinline__ void fp8x16_bf16(const uint4 w, unsigned (&h)[16]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + float f[4]; + fp8x4(in[q], f); +#pragma unroll + for (int e = 0; e < 4; ++e) h[q * 4 + e] = __float_as_uint(f[e]) >> 16; + } +} + +template +__global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { + using G = WGeo; + constexpr int NS = G::NS, R = G::R, BQ = R / GQA, KS = G::KS, VS = G::VS; + constexpr int ESZ = KV8 ? 1 : 2; + constexpr int SLOT = 2 * HD * ESZ; /* bytes of one key's slot: K then V */ + constexpr int CW = 16 / ESZ; /* cache elements one 16-byte load carries */ + constexpr int NCH = HD / CW; /* such chunks a head */ + constexpr int NKI = 16 * NCH; /* K items a tile: (key, chunk) */ + constexpr int NVI = 8 * NCH; /* V items a tile: (key pair, chunk) */ + constexpr int KPT = (NKI + kWThreads - 1) / kWThreads; + constexpr int VPT = (NVI + kWThreads - 1) / kWThreads; + static_assert(R % GQA == 0 && NS * G::RG == kWWaves, "rows must split over heads and waves"); + static_assert(KS % 16 == 0 && VS % 16 == 0, "16-byte LDS rows"); + + __shared__ uint4 s_k[16 * KS / 16]; + __shared__ uint4 s_vt[HD * VS / 16]; + __shared__ float4 s_x[kWWaves * 32 * 2]; + __shared__ int s_scan[kWWaves]; + __shared__ int s_res[2]; + + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int rg = wave / NS, sl = wave - rg * NS; + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y; + + /* ---- which sequence, and which slice of its query: as the scalar kernel, at this BQ */ + int s = -1, lt = 0; + if (A.cu) { + find_tile(A.cu, A.n_seq, tile, s_scan, s_res, s, lt); + } else { + s = tile / A.tps; + lt = tile - s * A.tps; + if (s >= A.n_seq) s = -1; + } + int qlen = 0, tokb = 0, ctx = 0; + if (s >= 0) { + if (A.cu) { tokb = A.cu[s]; qlen = A.cu[s + 1] - tokb; } + else { tokb = s * A.q_len; qlen = A.q_len; } + ctx = A.seqused[s]; + } + const int pfirst = lt * BQ; + const int npos = s >= 0 ? imax(0, imin(BQ, qlen - pfirst)) : 0; + if (npos <= 0) return; /* uniform across the block */ + + const int tok0 = tokb + pfirst; + const int qbase = ctx - qlen + pfirst; + const int plast = qbase + npos - 1; + const int causal = A.causal, window = A.window; + int hi = causal ? plast + 1 : ctx; + if (!causal && window > 0) hi = imin(hi, plast + window); + hi = imin(imin(hi, ctx), A.max_blocks * 16); + const int lo = window > 0 ? imax(0, qbase - window + 1) : 0; + const int lo_a = lo & ~15; + const int nkt = hi > lo_a ? (hi - lo_a + 15) / 16 : 0; + + const float kds = A.kdes ? A.kdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float vds = A.vdes ? A.vdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float sscale = A.qscale * kds; /* log2-domain softmax scale, k_descale in */ + + /* ---- this lane's query row: column n of every S^T and O^T tile */ + const int n = lane & 15, h = lane >> 4; + const int r = rg * 16 + n, p = r / GQA, g = r - p * GQA; + const bool rval = p < npos; + const int pos = qbase + p; + + g4k_v8s qf[kDQ / 16]; + { + const uint16_t* qp = A.q + (long long)(tok0 + (rval ? p : 0)) * A.q_rs + + (long long)(kh * GQA + g) * A.q_hs + sl * kDQ + 8 * h; +#pragma unroll + for (int kc = 0; kc < kDQ / 16; ++kc) { + const uint4 w = rval ? *(const uint4*)(qp + kc * 16) : make_uint4(0u, 0u, 0u, 0u); + qf[kc] = __builtin_bit_cast(g4k_v8s, w); + } + } + g4k_v8f oacc[kDQ / 16]; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) +#pragma unroll + for (int e = 0; e < 8; ++e) oacc[mc][e] = 0.0f; + float m = -__builtin_inff(), l = 0.0f; + + /* ---- the key tiles, one paged block each, prefetched one ahead through registers */ + uint4 pk[KPT], pv[VPT][2]; + bool pre_ok = false; + auto fetch = [&](int kt) __attribute__((always_inline)) { + const int k0 = lo_a + kt * 16, lb = k0 >> 4; + int blk = -1; + if (lb < A.max_blocks && k0 < hi) blk = A.bt[(long long)s * A.bt_rs + lb]; + pre_ok = blk >= 0; + /* never a null: see the scalar kernel's fetch */ + const unsigned char* base = + A.kv + ((long long)(blk >= 0 ? blk : 0) * A.kv_sb + (long long)kh * A.kv_sh) * ESZ; +#pragma unroll + for (int j = 0; j < KPT; ++j) { + const int idx = tid + j * kWThreads; + pk[j] = make_uint4(0u, 0u, 0u, 0u); + if (pre_ok && idx < NKI) { + const int key = idx / NCH, ch = idx - key * NCH; + pk[j] = *(const uint4*)(base + key * SLOT + ch * 16); + } + } +#pragma unroll + for (int j = 0; j < VPT; ++j) { + const int idx = tid + j * kWThreads; + pv[j][0] = pv[j][1] = make_uint4(0u, 0u, 0u, 0u); + if (pre_ok && idx < NVI) { + const int kp = idx & 7, ch = idx >> 3; + const unsigned char* v0 = base + (2 * kp) * SLOT + HD * ESZ + ch * 16; + pv[j][0] = *(const uint4*)v0; + pv[j][1] = *(const uint4*)(v0 + SLOT); + } + } + }; + + unsigned char* kb = (unsigned char*)s_k; + unsigned char* vb = (unsigned char*)s_vt; + if (nkt > 0) fetch(0); + for (int kt = 0; kt < nkt; ++kt) { + const int k0 = lo_a + kt * 16; + const bool tok = pre_ok; /* this tile's block is present */ + __syncthreads(); /* the previous tile's LDS is consumed */ + + /* ---- K: [key][dim] as bf16 */ +#pragma unroll + for (int j = 0; j < KPT; ++j) { + const int idx = tid + j * kWThreads; + if (idx < NKI) { + const int key = idx / NCH, ch = idx - key * NCH; + const int kk = k0 + key; + const bool keep = tok && kk >= lo && kk < hi; + const uint4 w = keep ? pk[j] : make_uint4(0u, 0u, 0u, 0u); + if constexpr (KV8) { + unsigned hb[16]; + fp8x16_bf16(w, hb); + uint4* dst = (uint4*)(kb + key * KS + ch * 32); + dst[0] = make_uint4(hb[0] | hb[1] << 16, hb[2] | hb[3] << 16, hb[4] | hb[5] << 16, hb[6] | hb[7] << 16); + dst[1] = make_uint4(hb[8] | hb[9] << 16, hb[10] | hb[11] << 16, hb[12] | hb[13] << 16, hb[14] | hb[15] << 16); + } else { + *(uint4*)(kb + key * KS + ch * 16) = w; + } + } + } + /* ---- V: [dim][key] as f16, two keys a dword; the row order rotated by 2 per 8-lane + * group, so the four groups of a wave write four different rows mod 8 -- 32 banks */ +#pragma unroll + for (int j = 0; j < VPT; ++j) { + const int idx = tid + j * kWThreads; + if (idx < NVI) { + const int kp = idx & 7, ch = idx >> 3; + const int ka = k0 + 2 * kp, kb1 = ka + 1; + const uint4 wa = (tok && ka >= lo && ka < hi) ? pv[j][0] : make_uint4(0u, 0u, 0u, 0u); + const uint4 wb = (tok && kb1 >= lo && kb1 < hi) ? pv[j][1] : make_uint4(0u, 0u, 0u, 0u); + unsigned d[CW]; /* f16 pairs: key 2kp low, 2kp + 1 high */ + if constexpr (KV8) { + unsigned ha[16], hb2[16]; + fp8x16_f16(wa, ha); + fp8x16_f16(wb, hb2); +#pragma unroll + for (int e = 0; e < CW; ++e) d[e] = ha[e] | hb2[e] << 16; + } else { + unsigned ha[8], hb2[8]; + bf16x8_f16(wa, ha); + bf16x8_f16(wb, hb2); +#pragma unroll + for (int e = 0; e < CW; ++e) d[e] = ha[e] | hb2[e] << 16; + } + const int rot = 2 * ((lane >> 3) & 3); + unsigned* col = (unsigned*)(vb + (ch * CW) * VS) + kp; +#pragma unroll + for (int t = 0; t < CW; ++t) { + /* element (t + rot) % CW, chosen by value: rot is per lane */ + const unsigned v0 = d[t], v2 = d[(t + 2) % CW], v4 = d[(t + 4) % CW], v6 = d[(t + 6) % CW]; + const unsigned v = rot == 0 ? v0 : rot == 2 ? v2 : rot == 4 ? v4 : v6; + const int e = (t + rot) % CW; + col[e * (VS / 4)] = v; + } + } + } + __syncthreads(); + if (kt + 1 < nkt) fetch(kt + 1); + + /* ---- S^T partial over this wave's slice: A = K rows (key n), B = Q^T (row n) */ + g4k_v8f sacc; +#pragma unroll + for (int e = 0; e < 8; ++e) sacc[e] = 0.0f; + { + /* one accumulator: a second one hides the chain's latency but costs 12 VGPRs, and at + * 187 two 16-wave workgroups share a WGP (8 waves a SIMD, 1536 VGPRs) where at 200 + * one does -- the other waves hide the latency better */ + const unsigned char* ka = kb + n * KS + (sl * kDQ + 8 * h) * 2; +#pragma unroll + for (int kc = 0; kc < kDQ / 16; ++kc) + sacc = wmma_bf16(__builtin_bit_cast(g4k_v8s, *(const uint4*)(ka + kc * 32)), qf[kc], sacc); + } + /* ---- the slices' partials meet: every slice sums them in slice order */ + s_x[(wave * 2 + 0) * 32 + lane] = make_float4(sacc[0], sacc[1], sacc[2], sacc[3]); + s_x[(wave * 2 + 1) * 32 + lane] = make_float4(sacc[4], sacc[5], sacc[6], sacc[7]); + __syncthreads(); + float tot[8]; +#pragma unroll + for (int j = 0; j < NS; ++j) { + float v[8]; + if (j == sl) { /* uniform: the wave's own, as written */ +#pragma unroll + for (int e = 0; e < 8; ++e) v[e] = sacc[e]; + } else { + const float4 a = s_x[((rg * NS + j) * 2 + 0) * 32 + lane]; + const float4 b = s_x[((rg * NS + j) * 2 + 1) * 32 + lane]; + v[0] = a.x; v[1] = a.y; v[2] = a.z; v[3] = a.w; + v[4] = b.x; v[5] = b.y; v[6] = b.z; v[7] = b.w; + } +#pragma unroll + for (int e = 0; e < 8; ++e) tot[e] = j == 0 ? v[e] : tot[e] + v[e]; + } + + /* ---- online softmax, row n: eight keys here, eight in lane ^ 16 */ + float sv[8], mx = -__builtin_inff(); +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int kk = k0 + 8 * h + e; + bool vis = rval && tok && kk >= lo && kk < hi; + if (causal) vis = vis && kk <= pos; + if (window > 0) vis = vis && (pos - kk < window) && (causal || kk - pos < window); + sv[e] = vis ? tot[e] * sscale : -__builtin_inff(); + mx = __builtin_fmaxf(mx, sv[e]); + } + mx = __builtin_fmaxf(mx, shfl_xor(mx, 16)); + const float mn = __builtin_fmaxf(m, mx); + const float corr = mn == -__builtin_inff() ? 1.0f : ex2(m - mn); + /* P in f16, and the denominator summed from P as rounded (see the head of this kernel) */ + float ps = 0.0f; + g4k_v8h pf; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const float pe = sv[e] == -__builtin_inff() ? 0.0f : ex2(sv[e] - mn); + pf[e] = (_Float16)pe; /* in [0, 1]: no saturation to worry about */ + ps += (float)pf[e]; + } + l = l * corr + ps; + m = mn; + + /* ---- O^T += V^T * P^T in f16: A = V^T rows (dim n of the chunk), keys 8h .. 8h + 7 */ + const unsigned char* va = vb + (sl * kDQ + n) * VS + h * 16; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) { + oacc[mc] *= corr; + oacc[mc] = wmma_f16(__builtin_bit_cast(g4k_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]); + } + } + + /* ---- out: the row's denominator is its two lanes' partial sums */ + const float lt2 = l + shfl_xor(l, 16); + if (rval) { + const float inv = lt2 > 0.0f ? vds / lt2 : 0.0f; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs + + sl * kDQ + 8 * h; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) + *(uint4*)(op + mc * 16) = + make_uint4(pack2(oacc[mc][0] * inv, oacc[mc][1] * inv), pack2(oacc[mc][2] * inv, oacc[mc][3] * inv), + pack2(oacc[mc][4] * inv, oacc[mc][5] * inv), pack2(oacc[mc][6] * inv, oacc[mc][7] * inv)); + } +} + +/* ------------------------------------------------------------------ the split-KV merge + * + * ONE WAVE A ROW, THE SPLITS ACROSS ITS LANES. Lane z reads split z's (max, sum) and lane z + 32 + * split z + 32's -- kMaxSplit is 64 -- so the row's max and denominator are one wave reduction + * each; then one sweep over the splits that saw a key, four at a time, every lane accumulating + * its 4 * NC dims. The first version walked the splits three times over, + * serially, in one thread block per tile: at the 64 splits a decode step of a full-attention layer + * gets, that was 750 us a call, a quarter of the step's device time. */ +template +__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { + constexpr int R = Geo::R, NC = HD / 128; + static_assert(kMaxSplit <= 64, "two splits a lane"); + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y; + const int lane = lane_id(), wave = (int)(threadIdx.x >> 5); + const int tok0 = A.tinfo[2 * tile], npos = A.tinfo[2 * tile + 1]; + const int ns = A.n_split; + const float ninf = -__builtin_inff(); + for (int r = wave; r < npos * GQA; r += kWaves) { + const int p = r / GQA, g = r - p * GQA; + const long long base = ((long long)tile * A.kv_heads + kh) * ns * R + r; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs; + float m0 = ninf, m1 = ninf, l0 = 0.0f, l1 = 0.0f; + if (lane < ns) { + const float* pp = A.part + (base + (long long)lane * R) * (HD + 4); + m0 = pp[HD]; l0 = pp[HD + 1]; + } + if (lane + 32 < ns) { + const float* pp = A.part + (base + (long long)(lane + 32) * R) * (HD + 4); + m1 = pp[HD]; l1 = pp[HD + 1]; + } + const float mt = wave_max(__builtin_fmaxf(m0, m1)); + if (mt == ninf) { /* no key visible to the row: a zero row */ +#pragma unroll + for (int c = 0; c < NC; ++c) *(uint2*)(op + c * 128 + lane * 4) = make_uint2(0u, 0u); + continue; + } + const float w0 = ex2(m0 - mt), w1 = ex2(m1 - mt); /* an empty split: ex2(-inf) = 0 */ + const float lt = wave_sum(__builtin_fmaf(l0, w0, l1 * w1)); + const float inv = lt > 0.0f ? 1.0f / lt : 0.0f; + float acc[NC][4]; +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[c][e] = 0.0f; + /* The splits that carry weight, as a 64-bit set every lane holds the same copy of, taken + * four at a time so 4 * NC loads are in flight before the first FMA waits on one. A short + * group repeats its first split at weight 0: the index is a written one, so the product is + * 0 * finite. An empty split's accumulator was never written and is never read. */ + uint64_t live = (uint64_t)__builtin_amdgcn_ballot_w32(w0 != 0.0f) | + ((uint64_t)__builtin_amdgcn_ballot_w32(w1 != 0.0f) << 32); + while (live) { + int zi[4]; + float wj[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const bool have = live != 0; + zi[j] = have ? __builtin_ctzll(live) : zi[0]; + live &= have ? live - 1 : live; + wj[j] = readlane(zi[j] < 32 ? w0 : w1, zi[j] & 31); + if (!have) wj[j] = 0.0f; + } + float4 v[4][NC]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float* pp = A.part + (base + (long long)zi[j] * R) * (HD + 4); +#pragma unroll + for (int c = 0; c < NC; ++c) v[j][c] = *(const float4*)(pp + c * 128 + lane * 4); + } +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int c = 0; c < NC; ++c) { + acc[c][0] = __builtin_fmaf(wj[j], v[j][c].x, acc[c][0]); + acc[c][1] = __builtin_fmaf(wj[j], v[j][c].y, acc[c][1]); + acc[c][2] = __builtin_fmaf(wj[j], v[j][c].z, acc[c][2]); + acc[c][3] = __builtin_fmaf(wj[j], v[j][c].w, acc[c][3]); + } + } +#pragma unroll + for (int c = 0; c < NC; ++c) + *(uint2*)(op + c * 128 + lane * 4) = + make_uint2(pack2(acc[c][0] * inv, acc[c][1] * inv), pack2(acc[c][2] * inv, acc[c][3] * inv)); + } +} + +/* ------------------------------------------------------------------ host: the launch adapter */ + +/* q and out as [rows, heads, head_dim] at whatever rank they arrived in: rank 3 (or more, leading + * axes dense), or rank 2 [rows, heads * head_dim] with its own row pitch -- a column slice of a + * fused projection. The last axis must be dense. */ +static bool head_view(const RadTensor* t, int64_t heads, int64_t hd, int64_t* rows, int64_t* rs, + int64_t* hs) { + if (t->rank >= 3) { + const uint32_t k = t->rank; + if (t->shape[k - 1] != hd || t->shape[k - 2] != heads || t->stride[k - 1] != 1) return false; + int64_t n = 1; + for (uint32_t i = 0; i + 2 < k; ++i) n *= t->shape[i]; + for (uint32_t i = 0; i + 3 < k; ++i) + if (t->shape[i] > 1 && t->stride[i] != t->stride[i + 1] * t->shape[i + 1]) return false; + *rows = n; *rs = t->stride[k - 3]; *hs = t->stride[k - 2]; + return true; + } + if (t->rank == 2) { + if (t->shape[1] != heads * hd || t->stride[1] != 1) return false; + *rows = t->shape[0]; *rs = t->stride[0]; *hs = hd; + return true; + } + if (t->rank == 1) { + if (t->shape[0] % (heads * hd)) return false; + *rows = t->shape[0] / (heads * hd); *rs = heads * hd; *hs = hd; + return true; + } + return false; +} + +template +static constexpr int64_t part_bytes() { + return (int64_t)kPartBudget * Geo::R * (HD + 4) * (int64_t)sizeof(float); +} +template +static constexpr int64_t scratch_need() { + return part_bytes() + (int64_t)kTinfoMax * 2 * (int64_t)sizeof(int); +} + +/* RADIANCE_G4K_WMMA=0 in the environment keeps every launch on the scalar kernel: an A/B switch, + * and a way out if the matrix path misbehaves on a card. Read once. */ +static bool wmma_enabled() { + static const bool on = [] { + const char* v = getenv("RADIANCE_G4K_WMMA"); + return !(v && v[0] == '0'); + }(); + return on; +} + +template +static int launch_attn(const RadArgs* a, RadStream stream) { + constexpr int R = Geo::R, BK = Geo::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2; + if (!a || a->n_t < 8) return RAD_E_INVAL; + const RadTensor* q = rad_arg_in(a, 0); + const RadTensor* kv = rad_arg_in(a, 1); + const RadTensor* bt = rad_arg_in(a, 2); + const RadTensor* su = rad_arg_in(a, 3); + const RadTensor* kd = rad_arg_in(a, 4); + const RadTensor* vd = rad_arg_in(a, 5); + const RadTensor* cu = rad_arg_in(a, 6); + const RadTensor* o = rad_arg_in(a, 7); + if (!q || !kv || !bt || !su || !o) return RAD_E_INVAL; + + if (rad_args_geti_or(a, "head_dim", HD) != HD || rad_args_geti_or(a, "gqa", GQA) != GQA || + rad_args_geti_or(a, "block_size", 16) != 16) + return RAD_E_SHAPE; + const long long causal = rad_args_geti_or(a, "causal", 1); + const long long window = rad_args_geti_or(a, "window", 0); + if ((causal != 0 && causal != 1) || window < 0 || window > (1ll << 30)) return RAD_E_SHAPE; + + if (q->dtype != RAD_BF16 || o->dtype != RAD_BF16) return RAD_E_DTYPE; + if (kv->dtype != (uint32_t)(KV8 ? RAD_F8E4M3 : RAD_BF16)) return RAD_E_DTYPE; + if (bt->dtype != RAD_I32 || su->dtype != RAD_I32 || (cu && cu->dtype != RAD_I32)) return RAD_E_DTYPE; + if ((kd && kd->dtype != RAD_F32) || (vd && vd->dtype != RAD_F32)) return RAD_E_DTYPE; + + /* the cache: [n_blocks, kv_heads, 16, 2 * head_dim], slots dense */ + if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * HD) return RAD_E_SHAPE; + if (kv->stride[3] != 1 || kv->stride[2] != 2 * HD) return RAD_E_STRIDE; + const int64_t kvh = kv->shape[1]; + if (kvh <= 0 || kvh > 65535) return RAD_E_SHAPE; + const int64_t qh = kvh * GQA; + + int64_t rows = 0, q_rs = 0, q_hs = 0, orows = 0, o_rs = 0, o_hs = 0; + if (!head_view(q, qh, HD, &rows, &q_rs, &q_hs) || !head_view(o, qh, HD, &orows, &o_rs, &o_hs)) + return RAD_E_SHAPE; + if (orows < rows) return RAD_E_SHAPE; + const int64_t n_seq = rad_tensor_numel(su); + if (rows == 0) return RAD_OK; + if (n_seq <= 0 || n_seq > (1 << 24)) return RAD_E_SHAPE; + + /* the block table: [n_seq, max_blocks] with a row pitch, or flat */ + int64_t max_blocks = 0, bt_rs = 0; + if (bt->rank >= 2) { + if (bt->stride[bt->rank - 1] != 1) return RAD_E_STRIDE; + max_blocks = bt->shape[bt->rank - 1]; + bt_rs = bt->stride[bt->rank - 2]; + if (rad_tensor_numel(bt) / max_blocks < n_seq) return RAD_E_SHAPE; + } else { + max_blocks = rad_tensor_numel(bt) / n_seq; + bt_rs = max_blocks; + } + if (max_blocks <= 0 || max_blocks > (1 << 26)) return RAD_E_SHAPE; + if ((kd && rad_tensor_numel(kd) < n_seq * kvh) || (vd && rad_tensor_numel(vd) < n_seq * kvh)) + return RAD_E_SHAPE; + + /* 8-byte query/output chunks, 16-byte cache loads */ + if (!rad_ptr_aligned(q->data, 8) || !rad_ptr_aligned(o->data, 8) || (q_rs | q_hs | o_rs | o_hs) % 4) + return RAD_E_ALIGN; + if (!rad_ptr_aligned(kv->data, 16) || (kv->stride[0] * ESZ) % 16 || (kv->stride[1] * ESZ) % 16) + return RAD_E_ALIGN; + + /* the tiles: uniform, or an upper bound over a ragged batch (empty tiles exit at once) */ + int64_t nt = 0, tps = 0, qlen_u = 0; + if (!cu) { + if (rows % n_seq) return RAD_E_SHAPE; + qlen_u = rows / n_seq; + tps = (qlen_u + BQ - 1) / BQ; + nt = n_seq * tps; + } else { + if (rad_tensor_numel(cu) != n_seq + 1) return RAD_E_SHAPE; + int64_t qmax = rad_args_geti_or(a, "q_len", rows); + if (qmax <= 0 || qmax > rows) qmax = rows; + const int64_t b1 = (rows + n_seq * (BQ - 1)) / BQ; + const int64_t b2 = n_seq * ((qmax + BQ - 1) / BQ); + nt = b1 < b2 ? b1 : b2; + } + if (nt <= 0) return RAD_OK; + if (nt > 0x7fffffff) return RAD_E_SHAPE; + + /* THE WMMA PATH, for a prefill-shaped step: the longest query at least kWmmaMinQ rows and the + * mean at least half that -- a decode or verify batch, a few rows a sequence however many + * sequences, keeps the scalar kernel and its split-KV below. 16-byte query and output rows. + * RADIANCE_G4K_WMMA=0 in the server's environment turns it off. */ + { + int64_t qmax_w = qlen_u; + if (cu) { + qmax_w = rad_args_geti_or(a, "q_len", rows); + if (qmax_w <= 0 || qmax_w > rows) qmax_w = rows; + } + const bool shaped = qmax_w >= kWmmaMinQ && rows >= n_seq * (kWmmaMinQ / 2); + const bool aligned = rad_ptr_aligned(q->data, 16) && rad_ptr_aligned(o->data, 16) && + (q_rs | q_hs | o_rs | o_hs) % 8 == 0; + if (shaped && aligned && wmma_enabled()) { + constexpr int BQW = WGeo::R / GQA; + int64_t ntw = 0, tpsw = 0; + if (!cu) { + tpsw = (qlen_u + BQW - 1) / BQW; + ntw = n_seq * tpsw; + } else { + const int64_t b1 = (rows + n_seq * (BQW - 1)) / BQW; + const int64_t b2 = n_seq * ((qmax_w + BQW - 1) / BQW); + ntw = b1 < b2 ? b1 : b2; + } + if (ntw <= 0) return RAD_OK; + if (ntw > 0x7fffffff) return RAD_E_SHAPE; + AttnArgs W{}; + W.q = (const uint16_t*)q->data; W.q_rs = q_rs; W.q_hs = q_hs; + W.kv = (const unsigned char*)kv->data; W.kv_sb = kv->stride[0]; W.kv_sh = kv->stride[1]; + W.bt = (const int*)bt->data; W.bt_rs = bt_rs; + W.seqused = (const int*)su->data; + W.cu = cu ? (const int*)cu->data : nullptr; + W.kdes = kd ? (const float*)kd->data : nullptr; + W.vdes = vd ? (const float*)vd->data : nullptr; + W.out = (uint16_t*)o->data; W.o_rs = o_rs; W.o_hs = o_hs; + const double wscale = rad_args_getf_or(a, "scale", 1.0 / __builtin_sqrt((double)HD)); + W.qscale = (float)(wscale * 1.4426950408889634); + W.max_blocks = (int)max_blocks; + W.n_seq = (int)n_seq; + W.q_len = (int)qlen_u; + W.tps = (int)tpsw; + W.kv_heads = (int)kvh; + W.causal = (int)causal; + W.window = (int)window; + W.n_split = 1; + G4K_LAUNCH(G4K_KNAME(attn_wmma_kernel), dim3((unsigned)ntw, (unsigned)kvh, 1u), + dim3(kWThreads), (hipStream_t)stream, W); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; + } + } + + /* SPLIT-KV: only where (tile, kv head) pairs are too few to fill the card */ + int64_t ns = 1; + const int64_t pairs = nt * kvh; + if (pairs < kTinfoMax) { + ns = kPartBudget / pairs; + if (ns > kMaxSplit) ns = kMaxSplit; + const int64_t span = window > 0 ? window + BQ + : rad_args_geti_or(a, "max_ctx", max_blocks * 16); + const int64_t nkt = (span + BK - 1) / BK + 1; + if (ns > nkt / 2) ns = nkt / 2; + if (ns < 1) ns = 1; + if (ns > 1 && (!a->scratch || a->scratch_bytes < scratch_need() || + !rad_ptr_aligned(a->scratch, 16))) + ns = 1; /* never wrong, only slower: the unsplit kernel writes the rows itself */ + } + + AttnArgs A{}; + A.q = (const uint16_t*)q->data; A.q_rs = q_rs; A.q_hs = q_hs; + A.kv = (const unsigned char*)kv->data; A.kv_sb = kv->stride[0]; A.kv_sh = kv->stride[1]; + A.bt = (const int*)bt->data; A.bt_rs = bt_rs; + A.seqused = (const int*)su->data; + A.cu = cu ? (const int*)cu->data : nullptr; + A.kdes = kd ? (const float*)kd->data : nullptr; + A.vdes = vd ? (const float*)vd->data : nullptr; + A.out = (uint16_t*)o->data; A.o_rs = o_rs; A.o_hs = o_hs; + A.part = ns > 1 ? (float*)a->scratch : nullptr; + A.tinfo = ns > 1 ? (int*)((char*)a->scratch + part_bytes()) : nullptr; + const double scale = rad_args_getf_or(a, "scale", 1.0 / __builtin_sqrt((double)HD)); + A.qscale = (float)(scale * 1.4426950408889634); + A.max_blocks = (int)max_blocks; + A.n_seq = (int)n_seq; + A.q_len = (int)qlen_u; + A.tps = (int)tps; + A.kv_heads = (int)kvh; + A.causal = (int)causal; + A.window = (int)window; + A.n_split = (int)ns; + + hipStream_t s = (hipStream_t)stream; + G4K_LAUNCH(G4K_KNAME(attn_kernel), dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), + dim3(kThreads), s, A); + if (ns > 1) + G4K_LAUNCH(G4K_KNAME(merge_kernel), dim3((unsigned)nt, (unsigned)kvh), dim3(kThreads), + s, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* namespace g4k */ + +/* ------------------------------------------------------------------ the exported entry points */ +extern "C" { + +#define G4K_ATTN_DEF(HD, G) \ + int g4k_attn_h##HD##_gqa##G##_bf16kv(const RadArgs* a, RadStream s) { \ + return g4k::launch_attn(a, s); \ + } \ + int g4k_attn_h##HD##_gqa##G##_fp8kv(const RadArgs* a, RadStream s) { \ + return g4k::launch_attn(a, s); \ + } +G4K_ATTN_DEF(256, 1) G4K_ATTN_DEF(256, 2) G4K_ATTN_DEF(256, 4) G4K_ATTN_DEF(256, 8) +G4K_ATTN_DEF(512, 1) G4K_ATTN_DEF(512, 2) G4K_ATTN_DEF(512, 4) G4K_ATTN_DEF(512, 8) +#undef G4K_ATTN_DEF + +/* Called at declare with the band's bound and no tensors: the split-KV partials are capped at + * kPartBudget (tile, head, split) triples whatever the batch, so the answer is a constant. */ +int64_t g4k_attn_h256_scratch(const RadArgs*) { return g4k::scratch_need<256>(); } +int64_t g4k_attn_h512_scratch(const RadArgs*) { return g4k::scratch_need<512>(); } + +} /* extern "C" */ diff --git a/gemma4k/g4k_launch.h b/gemma4k/g4k_launch.h new file mode 100644 index 00000000..44d8bddd --- /dev/null +++ b/gemma4k/g4k_launch.h @@ -0,0 +1,14 @@ +/* g4k_launch.h -- the one spelling of a kernel launch in gemma4k's device units. + * + * A template kernel's name carries commas, so it goes through G4K_KNAME the way HIP_KERNEL_NAME + * exists for hipLaunchKernelGGL. G4K_LAUNCH is overridable so the same sources can be driven by a + * host-side SIMT emulator in a test -- the kernels are ordinary C++ once the HIP names are + * supplied. A build never defines it, and gets the triple-chevron launch, which the engine answers + * through hipLaunchKernel on its own queues (docs/PLUGIN.md §5). */ +#ifndef G4K_LAUNCH_H +#define G4K_LAUNCH_H +#define G4K_KNAME(...) __VA_ARGS__ +#ifndef G4K_LAUNCH +#define G4K_LAUNCH(kernel, grid, block, stream, ...) kernel<<>>(__VA_ARGS__) +#endif +#endif diff --git a/gemma4k/g4k_norm.hip b/gemma4k/g4k_norm.hip new file mode 100644 index 00000000..dea63fd4 --- /dev/null +++ b/gemma4k/g4k_norm.hip @@ -0,0 +1,252 @@ +/* g4k_norm.hip -- Gemma 4's sandwich-norm joins, each one kernel instead of a chain of small ones. + * + * A decode step of the 26B-A4B launches ~250 rmsnorms and ~90 adds a step, each a few hundred + * bytes of work behind a full launch: --profile-ops measured 2.0 ms and 0.85 ms of a 16.6 ms step. + * Two places in every layer are pure chains of them: + * + * norm_add_norm the attention's join: t = norm(a) * w_a; x += t; y = norm(x) * w_y + * (post_attention_layernorm, the residual add, pre_feedforward_layernorm) + * join_add_scale the feed-forward's: d' = norm(d) * w_d; r' = norm(r) * w_r; + * j = norm(d' + r') * w_j; x = (x + j) * s + * (post_feedforward_layernorm_1 and _2, the arms' sum, post_feedforward_layernorm, + * the residual add, layer_scalar) + * + * THE SAME FUNCTION AS THE CHAIN, ROUNDING FOR ROUNDING. Every value the chain stores as bf16 is + * rounded to bf16 here at the same point, and every element is computed with libr4d's own + * expression: a norm is bf16((v * rsqrtf(mean(v^2) + eps)) * g), an add bf16(u + v), a scale + * bf16(x * s). The one thing that can differ is the ORDER the sum of squares is added in -- libr4d + * picks its block width from a measured table -- which moves the f32 norm factor by an ulp at most + * and, rarely, a bf16 output by one ulp. The arch plugin asks for these first and falls back to + * the chain where nothing serves them (gemma4.cpp). + * + * One 256-thread block a row: a decode step is a handful of rows, so the row is latency-bound and + * a block's three reductions beat seven launches. Values a later stage reuses stay in registers + * (kMaxPer a thread, so n <= 256 * kMaxPer; the row table says so). + */ +#include + +#include + +#include "g4k.h" +#include "g4k_launch.h" +#include "rad_plugin.h" + +namespace g4kn { + +constexpr int kThreads = 256; +constexpr int kWaves = kThreads / 32; +constexpr int kMaxPer = 24; /* elements a thread holds: n <= 6144 */ + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); } +/* round to nearest even, as libr4d's f32_to_bf16 */ +__device__ __forceinline__ uint16_t f2bf(float f) { + const unsigned u = __float_as_uint(f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +__device__ __forceinline__ float rbf(float f) { return bf2f(f2bf(f)); } +__device__ __forceinline__ int lane_id() { return (int)(threadIdx.x & 31u); } +__device__ __forceinline__ float shfl_xor(float v, int m) { + return __int_as_float(__builtin_amdgcn_ds_bpermute((lane_id() ^ m) << 2, __float_as_int(v))); +} +/* the block's sum, every thread the same value: a wave butterfly, then the waves in order */ +__device__ __forceinline__ float block_sum(float v, float* lds) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v += shfl_xor(v, d); + const int lane = lane_id(), wave = (int)(threadIdx.x >> 5); + __syncthreads(); /* lds is free: the last read of it is done */ + if (lane == 0) lds[wave] = v; + __syncthreads(); + float s = 0.0f; +#pragma unroll + for (int w = 0; w < kWaves; ++w) s += lds[w]; + return s; +} +__device__ __forceinline__ float norm_factor(float ss, int n, float eps) { + return rsqrtf(ss / (float)n + eps); +} + +struct NormArgs { + const uint16_t* a; long long a_ld; /* norm_add_norm: the block output */ + const uint16_t* d; long long d_ld; /* join_add_scale: the dense partial */ + const uint16_t* r; long long r_ld; /* the routed partial */ + uint16_t* x; long long x_ld; /* the residual stream, read and written */ + uint16_t* y; long long y_ld; /* norm_add_norm: the next norm's output */ + const float* w0; /* w_a, or w_d */ + const float* w1; /* w_y, or w_r */ + const float* w2; /* w_j */ + const uint16_t* s; /* the layer scalar, bf16, one element */ + int n; + float eps; +}; + +/* t = norm(a) * w_a; x += t; y = norm(x) * w_y */ +__global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { + __shared__ float lds[kWaves]; + const int tid = (int)threadIdx.x, n = A.n; + const long long m = (long long)blockIdx.x; + const uint16_t* ar = A.a + m * A.a_ld; + uint16_t* xr = A.x + m * A.x_ld; + uint16_t* yr = A.y + m * A.y_ld; + + float av[kMaxPer], xv[kMaxPer]; + float ss = 0.0f; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + av[k] = i < n ? bf2f(ar[i]) : 0.0f; + ss += av[k] * av[k]; + } + const float sa = norm_factor(block_sum(ss, lds), n, A.eps); + ss = 0.0f; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float t = rbf((av[k] * sa) * A.w0[i]); + xv[k] = rbf(bf2f(xr[i]) + t); + xr[i] = f2bf(xv[k]); + } else { + xv[k] = 0.0f; + } + ss += xv[k] * xv[k]; + } + const float sx = norm_factor(block_sum(ss, lds), n, A.eps); +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) yr[i] = f2bf((xv[k] * sx) * A.w1[i]); + } +} + +/* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s */ +__global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { + __shared__ float lds[kWaves]; + const int tid = (int)threadIdx.x, n = A.n; + const long long m = (long long)blockIdx.x; + const uint16_t* dr = A.d + m * A.d_ld; + const uint16_t* rr = A.r + m * A.r_ld; + uint16_t* xr = A.x + m * A.x_ld; + + float dv[kMaxPer], rv[kMaxPer]; + float sd2 = 0.0f, sr2 = 0.0f; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + dv[k] = i < n ? bf2f(dr[i]) : 0.0f; + rv[k] = i < n ? bf2f(rr[i]) : 0.0f; + sd2 += dv[k] * dv[k]; + sr2 += rv[k] * rv[k]; + } + const float sd = norm_factor(block_sum(sd2, lds), n, A.eps); + const float sr = norm_factor(block_sum(sr2, lds), n, A.eps); + /* the join, kept in dv */ + float ss = 0.0f; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float u = rbf((dv[k] * sd) * A.w0[i]); + const float v = rbf((rv[k] * sr) * A.w1[i]); + dv[k] = rbf(u + v); + } else { + dv[k] = 0.0f; + } + ss += dv[k] * dv[k]; + } + const float sj = norm_factor(block_sum(ss, lds), n, A.eps); + const float sc = bf2f(*A.s); +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float j = rbf((dv[k] * sj) * A.w2[i]); + const float x1 = rbf(bf2f(xr[i]) + j); + xr[i] = f2bf(x1 * sc); + } + } +} + +/* ------------------------------------------------------------------ host: the launch adapters */ + +/* [rows..., n] with a dense last axis: its row count and pitch, or false */ +static bool rows_of(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != RAD_BF16 || t->rank < 1) return false; + if (rad_tensor_lastdim(t) != n || (t->stride[t->rank - 1] != 1)) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return *ld >= n || *rows <= 1; +} +static bool gain(const RadTensor* w, int64_t n) { + return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n && + (w->rank == 0 || w->stride[w->rank - 1] == 1); +} + +static int params(const RadArgs* a, int64_t* n, float* eps) { + *n = rad_args_geti_or(a, "n", 0); + *eps = (float)rad_args_getf_or(a, "eps", 1e-6); + if (*n <= 0 || *n > (int64_t)kThreads * kMaxPer) return RAD_E_SHAPE; + return RAD_OK; +} + +} /* namespace g4kn */ + +extern "C" { + +/* operands: a, w_a, x (inout), w_y, y */ +int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream stream) { + using namespace g4kn; + if (!a || a->n_t < 5) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), + *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); + if (!A_ || !X || !Y) return RAD_E_INVAL; + if (!gain(Wa, n) || !gain(Wy, n)) return RAD_E_DTYPE; + int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0; + if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly)) + return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (ra < M || ry < M || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.a = (const uint16_t*)A_->data; P.a_ld = la; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.y = (uint16_t*)Y->data; P.y_ld = ly; + P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; + P.n = (int)n; P.eps = eps; + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +/* operands: d, w_d, r, w_r, w_j, x (inout), s */ +int g4k_join_add_scale_bf16(const RadArgs* a, RadStream stream) { + using namespace g4kn; + if (!a || a->n_t < 7) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2), + *Wr = rad_arg_in(a, 3), *Wj = rad_arg_in(a, 4), *X = rad_arg_in(a, 5), + *Sc = rad_arg_in(a, 6); + if (!D || !R || !X || !Sc) return RAD_E_INVAL; + if (!gain(Wd, n) || !gain(Wr, n) || !gain(Wj, n)) return RAD_E_DTYPE; + if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; + int64_t rd = 0, ld = 0, rr = 0, lr = 0, rx = 0, lx = 0; + if (!rows_of(D, n, &rd, &ld) || !rows_of(R, n, &rr, &lr) || !rows_of(X, n, &rx, &lx)) + return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (rd < M || rr < M || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.d = (const uint16_t*)D->data; P.d_ld = ld; + P.r = (const uint16_t*)R->data; P.r_ld = lr; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.w0 = (const float*)Wd->data; P.w1 = (const float*)Wr->data; P.w2 = (const float*)Wj->data; + P.s = (const uint16_t*)Sc->data; + P.n = (int)n; P.eps = eps; + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* extern "C" */ diff --git a/gemma4k/g4k_pick.hip b/gemma4k/g4k_pick.hip new file mode 100644 index 00000000..fff46f3d --- /dev/null +++ b/gemma4k/g4k_pick.hip @@ -0,0 +1,105 @@ +/* g4k_pick.hip -- pair_argmax: the global argmax of a row of gathered (id, value) pairs, written as + * ONE CONTIGUOUS COLUMN of token ids. + * + * WHY THIS OP EXISTS. A vocab-sharded draft head finds each rank's best candidates with `row_topk` + * and moves them with `all_gather`. The gather moves whole 16-byte words a row, and one (int32 id, + * f32 value) pair is 8 bytes, so a rank contributes at least R = 2 (rad_block_mtp_hc.h states the + * same bound). `row_topk_merge` then returns R = 2 columns a row, and a BLOCK drafter's proposal + * is `steps` contiguous ids a sequence -- column 0 of an [S, 2] plane is not that, and nothing in + * libr4d copies a strided i32 column. This reduces the gathered row to its top-1 and writes it + * where the proposal reads it. + * + * It is row_topk_merge at R = 1 with a strided output, rule for rule: the largest value wins, a tie + * goes to the LOWER id, and a pair whose id is negative (a slot a shard could not fill) is skipped. + * A row with no valid pair writes id -1 and value -inf. One wave a row, eight rows a workgroup. + */ +#include + +#include + +#include "g4k.h" +#include "g4k_launch.h" +#include "rad_plugin.h" + +namespace g4k { + +struct PickArgs { + const float* pairs; long long p_rs; /* [M, n, 2]: int32 id bits, then f32 value */ + int* tok; long long t_rs; + float* val; long long v_rs; /* optional */ + long long rows; + int n; +}; + +__device__ __forceinline__ int pk_lane() { return (int)(threadIdx.x & 31u); } +__device__ __forceinline__ int pk_xor_i(int v, int m) { + return __builtin_amdgcn_ds_bpermute((pk_lane() ^ m) << 2, v); +} +__device__ __forceinline__ float pk_xor_f(float v, int m) { + return __int_as_float(pk_xor_i(__float_as_int(v), m)); +} +/* (v, id) beats (bv, bid)? Larger value, then lower id; an invalid id (< 0) never wins. */ +__device__ __forceinline__ bool pk_better(float v, int id, float bv, int bid) { + if (id < 0) return false; + if (bid < 0) return true; + return v > bv || (v == bv && id < bid); +} + +__global__ __launch_bounds__(256) void pick_kernel(PickArgs A) { + const long long r = (long long)blockIdx.x * 8 + (threadIdx.x >> 5); + if (r >= A.rows) return; /* uniform across the wave */ + const int lane = pk_lane(); + const float* row = A.pairs + r * A.p_rs; + float bv = -__builtin_inff(); + int bid = -1; + for (int j = lane; j < A.n; j += 32) { + const int id = __float_as_int(row[2 * j]); + const float v = row[2 * j + 1]; + if (pk_better(v, id, bv, bid)) { bv = v; bid = id; } + } +#pragma unroll + for (int m = 16; m >= 1; m >>= 1) { + const float ov = pk_xor_f(bv, m); + const int oid = pk_xor_i(bid, m); + if (pk_better(ov, oid, bv, bid)) { bv = ov; bid = oid; } + } + if (lane == 0) { + A.tok[r * A.t_rs] = bid; + if (A.val) A.val[r * A.v_rs] = bv; + } +} + +} /* namespace g4k */ + +/* pairs as [M, n, 2] (rank 3) or [M, 2n] (rank 2), last axes dense; the outputs one element a row + * at their own row pitch. */ +extern "C" int g4k_pair_argmax_f32(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const RadTensor* p = rad_arg_in(a, 0); + const RadTensor* t = rad_arg_in(a, 1); + const RadTensor* v = rad_arg_in(a, 2); + if (!p || !t) return RAD_E_INVAL; + if (p->dtype != RAD_F32 || t->dtype != RAD_I32 || (v && v->dtype != RAD_F32)) return RAD_E_DTYPE; + const long long n = rad_args_geti_or(a, "n", 0); + if (n <= 0 || p->rank < 2) return RAD_E_SHAPE; + if (p->rank == 3) { + if (p->shape[1] < n || p->shape[2] != 2 || p->stride[2] != 1 || p->stride[1] != 2) return RAD_E_SHAPE; + } else if (p->rank == 2) { + if (p->shape[1] < 2 * n || p->stride[1] != 1) return RAD_E_SHAPE; + } else { + return RAD_E_SHAPE; + } + const int64_t rows = p->shape[0]; + if (rows == 0) return RAD_OK; + if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE; + g4k::PickArgs A{}; + A.pairs = (const float*)p->data; A.p_rs = p->stride[0]; + A.tok = (int*)t->data; A.t_rs = t->rank >= 2 ? t->stride[0] : 1; + A.val = v ? (float*)v->data : nullptr; + A.v_rs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0; + A.rows = rows; + A.n = (int)n; + G4K_LAUNCH(G4K_KNAME(g4k::pick_kernel), dim3((unsigned)((rows + 7) / 8)), dim3(256), + (hipStream_t)stream, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} diff --git a/gemma4k/g4k_rows.cpp b/gemma4k/g4k_rows.cpp new file mode 100644 index 00000000..7376d9e6 --- /dev/null +++ b/gemma4k/g4k_rows.cpp @@ -0,0 +1,436 @@ +/* g4k_rows.cpp -- gemma4k's row table, the op schemas it defines, and the host arms of those ops. + * + * gemma4k is the kernel library for Gemma 4's text model beyond what libr4d serves it with: + * + * attn_paged at head_dim 256 and 512, gqa 1/2/4/8, ANY window, causal or not, bf16 or fp8 cache. + * Gemma 4's sliding layers are h256/gqa2 with a 1024-token window and its full layers h512 at + * gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8). + * pair_argmax: the top-1 of a row of all-gathered (id, value) pairs, one i32 a row -- the + * vocab-sharded DFlash head's merge, which needs R >= 2 on the wire (16-byte gather rows) and a + * contiguous proposal out (g4k_pick.hip says why). libref declares it too, and is its oracle. + * norm_add_norm and join_add_scale, ops this library DEFINES: Gemma 4's two sandwich-norm joins, + * each one kernel in place of a chain of rmsnorm / add / mul_weight launches, rounding where the + * chain rounds (g4k_norm.hip). The arch plugin asks for them and falls back to the chain. + * + * Put it AHEAD of libr4d for Gemma 4 (`--kernels gemma4k,libr4d,...`). The hierarchy is absolute, + * and libr4d has rows at h256/gqa2 and h512/gqa8 too -- written for the dense 31B, which has no + * drafter, and not measured on the 26B-A4B or under a DFlash verify. These rows are the ones every + * Gemma 4 number in this tree was measured with. Every other row here is the only one in the tree + * for its geometry, so the order changes nothing else: libr4d keeps the drafter's h128/gqa4 + * attention, say. (Gemma's final logit softcap is libr4d's and libavx's `logit_softcap`; this + * library has no row for it.) + * + * Pure host code: no HIP header. The entry points it names are in g4k_attn.hip, g4k_pick.hip and + * g4k_norm.hip. + */ +#include "g4k.h" +#include "rad_plugin.h" + +#include +#include +#include + +#ifndef G4K_BUILD_TARGET +#define G4K_BUILD_TARGET "gfx12" +#endif + +#define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0])) +#define NOTUNE nullptr, 0, nullptr +#define C_EQ(k, v) { (k), RAD_C_EQ, (long long)(v), nullptr } +#define C_GE(k, v) { (k), RAD_C_GE, (long long)(v), nullptr } +#define C_LE(k, v) { (k), RAD_C_LE, (long long)(v), nullptr } +#define C_IN(k, s) { (k), RAD_C_IN, 0, (s) } + +namespace { + +/* ==================================================================== the ops this library declares + * + * pair_argmax is libref's schema restated field for field (the first declarer in a hierarchy fixes + * it, and libref is in every hierarchy). The two joins are this library's own: libref has no row + * for them ON PURPOSE, because a reference row would resolve them wherever gemma4k is not loaded, + * and the architecture's fallback to the rmsnorm / add / mul_weight chain -- which libr4d and + * libavx serve -- would never be taken. docs/OPS.md carries all three rows, which is what the + * ops_doc test holds them to. */ +static const RadParamSpec pPick[] = { + { "M", RAD_P_INT, RAD_REQUIRED, 0 }, + { "n", RAD_P_INT, RAD_REQUIRED, 0 }, + { "dtype", RAD_P_STR, RAD_REQUIRED, 0 }, +}; +static const RadOperandSpec oPick[] = { + { "pairs", RAD_OPD_IN, 0 }, + { "idx", RAD_OPD_OUT, 0 }, + { "val", RAD_OPD_OUT, 1 }, +}; +static const RadParamSpec pJoin[] = { + { "M", RAD_P_INT, RAD_REQUIRED, 0 }, + { "n", RAD_P_INT, RAD_REQUIRED, 0 }, + { "eps", RAD_P_F64, RAD_REQUIRED, 0 }, + { "dtype", RAD_P_STR, RAD_REQUIRED, 0 }, +}; +static const RadOperandSpec oNan[] = { + { "a", RAD_OPD_IN, 0 }, + { "w_a", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "w_y", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec oJas[] = { + { "d", RAD_OPD_IN, 0 }, + { "w_d", RAD_OPD_WEIGHT, 0 }, + { "r", RAD_OPD_IN, 0 }, + { "w_r", RAD_OPD_WEIGHT, 0 }, + { "w_j", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "s", RAD_OPD_WEIGHT, 0 }, +}; +static const RadOpSchema kSchemas[] = { + { "pair_argmax", ROW(pPick), ROW(oPick), + "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first " + "f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties to the lower " + "id, a negative id skipped, -1 and -inf where nothing is valid. row_topk_merge at R = 1, " + "written one element a row at the output's own pitch." }, + { "norm_add_norm", ROW(pJoin), ROW(oNan), + "t = rmsnorm(a) * w_a; x = x + t; y = rmsnorm(x) * w_y, over [M, n] rows; every value the " + "unfused rmsnorm, add, rmsnorm chain stores is rounded to the activation dtype at the same " + "point. A post-norm, the residual add and the next pre-norm (Gemma's sandwich)." }, + { "join_add_scale", ROW(pJoin), ROW(oJas), + "x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s, over [M, n] rows, s one " + "element; rounding where the unfused chain rounds. Two arms' post-norms, their sum, its norm, " + "the residual add and a per-layer scalar (Gemma 4's feed-forward join)." }, +}; + +/* ==================================================================== operand descriptions + * + * So rad-kbench can call these kernels cold and check them against libref (docs/PLUGIN.md §9). + * attn_paged's is libr4d's (r4d_shapes.cpp) restated: ONE sequence whose context is its query, or + * `ctx` deep when a sweep sets it. */ +RadOpdDesc opd(uint32_t dt, int64_t d0, int64_t d1 = 0, int64_t d2 = 0, int64_t d3 = 0) { + RadOpdDesc d{}; + d.dtype = dt; + d.fill = RAD_FILL_NORMAL; + d.idx_const = -1; + const int64_t e[4] = { d0, d1, d2, d3 }; + for (int i = 0; i < 4 && e[i] != 0; ++i) d.shape[d.rank++] = e[i]; + return d; +} +RadOpdDesc opd_idx(int64_t d0, int64_t d1, int64_t idx_max, int64_t konst = -1) { + RadOpdDesc d = opd((uint32_t)RAD_I32, d0, d1); + d.fill = RAD_FILL_INDEX; + d.idx_max = idx_max; + d.idx_const = konst; + return d; +} +RadOpdDesc opd_none() { + RadOpdDesc d{}; + d.idx_const = -1; + d.flags = RAD_OPD_F_ABSENT; + return d; +} +int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) { + if (!out || !list) return RAD_E_INVAL; + for (int i = 0; i < n; ++i) { + if (list[i].flags & RAD_OPD_F_ABSENT) continue; + if (list[i].rank == 0) return RAD_E_UNSUPPORTED; + for (uint32_t d = 0; d < list[i].rank; ++d) + if (list[i].shape[d] <= 0) return RAD_E_UNSUPPORTED; + } + if (operand < 0 || operand >= n) return RAD_E_SHAPE; + *out = list[operand]; + return RAD_OK; +} +#define PICK(l) return pick(out, operand, (l), (int)(sizeof(l) / sizeof((l)[0]))) +int64_t pi(const RadParam* p, int n_p, const char* k, int64_t dflt = 0) { + return (int64_t)rad_param_getdim(p, n_p, k, (long long)dflt); +} +uint32_t dt_act(const RadParam* p, int n_p, const char* k) { + const uint32_t d = rad_param_getdt(p, n_p, k); + return d == RAD_DT_INVALID ? (uint32_t)RAD_BF16 : d; +} + +int shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t q_len = pi(p, n_p, "q_len"), hd = pi(p, n_p, "head_dim"); + const int64_t gqa = pi(p, n_p, "gqa"), bs = pi(p, n_p, "block_size", 16), nh = pi(p, n_p, "n_head"); + if (q_len <= 0 || hd <= 0 || gqa <= 0 || bs <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED; + int64_t ctx = pi(p, n_p, "ctx", 0); + if (ctx < q_len) ctx = q_len; + const int64_t nblk = (ctx + bs - 1) / bs; + const uint32_t Q = dt_act(p, n_p, "q_dtype"), KV = dt_act(p, n_p, "kv_dtype"); + const RadOpdDesc l[] = { + opd(Q, q_len, nh, hd), + opd(KV, nblk, nh / gqa, bs, 2 * hd), + opd_idx(1, nblk, nblk), + opd_idx(1, 0, 0, ctx), + opd_none(), + opd_none(), + opd_none(), + opd(Q, q_len, nh, hd), + }; + PICK(l); +} + +/* pair_argmax as libref describes it (ref_shapes.cpp): the gathered plane is f32, so the value + * lane draws proper floats and the id lane their bit patterns -- negative ones pads, positive ones + * legal ids -- and ties do not occur. */ +int shape_pick(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd((uint32_t)RAD_F32, M, n, 2), + opd((uint32_t)RAD_I32, M), + opd((uint32_t)RAD_F32, M), + }; + PICK(l); +} + +/* The host arm of pair_argmax, the device kernel's rules in plain C++. Not libref's row: that one + * is a reference, which the engine refuses to serve, and this op has no chain to fall back to. */ +int pick_host(const RadArgs* a, RadStream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const RadTensor* p = rad_arg_in(a, 0); + const RadTensor* t = rad_arg_in(a, 1); + const RadTensor* v = rad_arg_in(a, 2); + if (!p || !t) return RAD_E_INVAL; + if (p->dtype != RAD_F32 || t->dtype != RAD_I32 || (v && v->dtype != RAD_F32)) return RAD_E_DTYPE; + const long long n = rad_args_geti_or(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + if (p->rank == 3) { + if (p->shape[1] < n || p->shape[2] != 2 || p->stride[2] != 1 || p->stride[1] != 2) return RAD_E_SHAPE; + } else if (p->rank == 2) { + if (p->shape[1] < 2 * n || p->stride[1] != 1) return RAD_E_SHAPE; + } else { + return RAD_E_SHAPE; + } + const int64_t rows = p->shape[0]; + if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE; + const int64_t prs = p->stride[0], trs = t->rank >= 2 ? t->stride[0] : 1; + const int64_t vrs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0; + for (int64_t r = 0; r < rows; ++r) { + const float* row = (const float*)p->data + r * prs; + int32_t bid = -1; + float bv = -INFINITY; + for (long long j = 0; j < n; ++j) { + int32_t id; + std::memcpy(&id, &row[2 * j], 4); + const float val = row[2 * j + 1]; + if (id < 0) continue; + if (bid < 0 || val > bv || (val == bv && id < bid)) { bid = id; bv = val; } + } + ((int32_t*)t->data)[r * trs] = bid; + if (v) ((float*)v->data)[r * vrs] = bv; + } + return RAD_OK; +} + +/* ==================================================================== the host arms of the joins + * + * The device kernels' arithmetic in plain C++: each value the unfused chain stores is rounded to + * bf16 where it stores it. Summed in index order, so a ULP from the device's block order. */ +static float hb2f(uint16_t h) { const uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; } +static uint16_t hf2b(float f) { + uint32_t u; std::memcpy(&u, &f, 4); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +static float hrbf(float f) { return hb2f(hf2b(f)); } +static float hnorm(const float* v, int64_t n, double eps) { + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) ss += v[i] * v[i]; + return 1.0f / std::sqrt(ss / (float)n + (float)eps); +} +static bool hrows(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != RAD_BF16 || t->rank < 1 || rad_tensor_lastdim(t) != n) return false; + if (t->stride[t->rank - 1] != 1) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return true; +} +static bool hgain(const RadTensor* w, int64_t n) { + return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n; +} + +int norm_add_norm_host(const RadArgs* a, RadStream) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + const int64_t n = rad_args_geti_or(a, "n", 0); + const double eps = rad_args_getf_or(a, "eps", 1e-6); + const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), + *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); + if (n <= 0 || !A_ || !X || !Y) return RAD_E_INVAL; + if (!hgain(Wa, n) || !hgain(Wy, n)) return RAD_E_DTYPE; + int64_t ra, la, rx, lx, ry, ly; + if (!hrows(A_, n, &ra, &la) || !hrows(X, n, &rx, &lx) || !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE; + if (ra < rx || ry < rx) return RAD_E_SHAPE; + const float *wa = (const float*)Wa->data, *wy = (const float*)Wy->data; + std::vector v((size_t)n), xv((size_t)n); + for (int64_t m = 0; m < rx; ++m) { + const uint16_t* ar = (const uint16_t*)A_->data + m * la; + uint16_t* xr = (uint16_t*)X->data + m * lx; + uint16_t* yr = (uint16_t*)Y->data + m * ly; + for (int64_t i = 0; i < n; ++i) v[(size_t)i] = hb2f(ar[i]); + const float sa = hnorm(v.data(), n, eps); + for (int64_t i = 0; i < n; ++i) { + const float t = hrbf((v[(size_t)i] * sa) * wa[i]); + xv[(size_t)i] = hrbf(hb2f(xr[i]) + t); + xr[i] = hf2b(xv[(size_t)i]); + } + const float sx = hnorm(xv.data(), n, eps); + for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((xv[(size_t)i] * sx) * wy[i]); + } + return RAD_OK; +} + +int join_add_scale_host(const RadArgs* a, RadStream) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + const int64_t n = rad_args_geti_or(a, "n", 0); + const double eps = rad_args_getf_or(a, "eps", 1e-6); + const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2), + *Wr = rad_arg_in(a, 3), *Wj = rad_arg_in(a, 4), *X = rad_arg_in(a, 5), + *Sc = rad_arg_in(a, 6); + if (n <= 0 || !D || !R || !X || !Sc) return RAD_E_INVAL; + if (!hgain(Wd, n) || !hgain(Wr, n) || !hgain(Wj, n)) return RAD_E_DTYPE; + if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; + int64_t rd, ld, rr, lr, rx, lx; + if (!hrows(D, n, &rd, &ld) || !hrows(R, n, &rr, &lr) || !hrows(X, n, &rx, &lx)) return RAD_E_SHAPE; + if (rd < rx || rr < rx) return RAD_E_SHAPE; + const float *wd = (const float*)Wd->data, *wr = (const float*)Wr->data, *wj = (const float*)Wj->data; + const float sc = hb2f(*(const uint16_t*)Sc->data); + std::vector dv((size_t)n), rv((size_t)n); + for (int64_t m = 0; m < rx; ++m) { + const uint16_t* dr = (const uint16_t*)D->data + m * ld; + const uint16_t* rrw = (const uint16_t*)R->data + m * lr; + uint16_t* xr = (uint16_t*)X->data + m * lx; + for (int64_t i = 0; i < n; ++i) { dv[(size_t)i] = hb2f(dr[i]); rv[(size_t)i] = hb2f(rrw[i]); } + const float sd = hnorm(dv.data(), n, eps), sr = hnorm(rv.data(), n, eps); + for (int64_t i = 0; i < n; ++i) + dv[(size_t)i] = hrbf(hrbf((dv[(size_t)i] * sd) * wd[i]) + hrbf((rv[(size_t)i] * sr) * wr[i])); + const float sj = hnorm(dv.data(), n, eps); + for (int64_t i = 0; i < n; ++i) { + const float x1 = hrbf(hb2f(xr[i]) + hrbf((dv[(size_t)i] * sj) * wj[i])); + xr[i] = hf2b(x1 * sc); + } + } + return RAD_OK; +} + +/* ==================================================================== constraints + * + * The attention rows serve their (head_dim, gqa) at ANY q_len -- one kernel does decode, verify and + * prefill, splitting the key range when there are too few tiles to fill the card -- so `q_len` + * carries no constraint and cuts no band. `causal` and `window` are runtime fields of the kernel. + * block_size is the kernel's (RAD_DERIVED): 16. + * + * TWO ROWS HERE OVERLAP libr4d's ON PURPOSE: h256/gqa2 (any window) and h512/gqa8, Gemma 4's own + * geometries, which this library serves ahead of libr4d (see the top of this file). Nothing else + * overlaps, so putting this library first cannot take one of libr4d's other geometries: libr4d + * serves h256 at gqa 4/6/8/12 with window 0, so the h256 gqa4 and gqa8 rows below take a window + * only (C_GE 1), and gqa 1 and h512 at gqa 1/2/4, which libr4d does not compile, take anything. */ +#define G4K_ATTN_C(NAME, HD, G, KV, WMIN) \ + static const RadConstraint NAME[] = { \ + C_EQ("head_dim", HD), C_EQ("gqa", G), C_EQ("block_size", 16), C_GE("causal", 0), \ + C_GE("window", WMIN), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", KV), \ + }; +G4K_ATTN_C(cH256x1B, 256, 1, "bf16", 0) G4K_ATTN_C(cH256x1F, 256, 1, "fp8_e4m3", 0) +G4K_ATTN_C(cH256x2B, 256, 2, "bf16", 0) G4K_ATTN_C(cH256x2F, 256, 2, "fp8_e4m3", 0) +G4K_ATTN_C(cH256x4B, 256, 4, "bf16", 1) G4K_ATTN_C(cH256x4F, 256, 4, "fp8_e4m3", 1) +G4K_ATTN_C(cH256x8B, 256, 8, "bf16", 1) G4K_ATTN_C(cH256x8F, 256, 8, "fp8_e4m3", 1) +G4K_ATTN_C(cH512x1B, 512, 1, "bf16", 0) G4K_ATTN_C(cH512x1F, 512, 1, "fp8_e4m3", 0) +G4K_ATTN_C(cH512x2B, 512, 2, "bf16", 0) G4K_ATTN_C(cH512x2F, 512, 2, "fp8_e4m3", 0) +G4K_ATTN_C(cH512x4B, 512, 4, "bf16", 0) G4K_ATTN_C(cH512x4F, 512, 4, "fp8_e4m3", 0) +G4K_ATTN_C(cH512x8B, 512, 8, "bf16", 0) G4K_ATTN_C(cH512x8F, 512, 8, "fp8_e4m3", 0) +#undef G4K_ATTN_C + +/* the device kernels hold 24 elements a thread over a 256-thread block */ +static const RadConstraint cJoin[] = { C_GE("n", 1), C_LE("n", 6144), C_IN("dtype", "bf16") }; +static const RadConstraint cJoinHost[] = { C_GE("n", 1), C_IN("dtype", "bf16") }; +static const RadConstraint cPick[] = { C_GE("n", 1), C_IN("dtype", "f32 fp32") }; + +/* ==================================================================== the rows */ +#define G4K_ATTN_ROW(HD, G, KVN, C, KVDOC) \ + { "attn_paged_h" #HD "_gqa" #G "_" #KVN, "attn_paged", "attn", \ + "paged attention, any window, causal or not; split-KV with a merge where tiles are few", \ + "head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \ + "bf16 query, " KVDOC " kv cache, bf16 out, f32 partials", \ + RAD_DOMAIN_DEVICE, 10, ROW(C), NOTUNE, \ + nullptr, nullptr, g4k_attn_h##HD##_gqa##G##_##KVN, g4k_attn_h##HD##_scratch, nullptr, \ + nullptr, shape_attn_paged, nullptr, nullptr, nullptr }, +#define G4K_ATTN_PAIR(HD, G) \ + G4K_ATTN_ROW(HD, G, bf16kv, cH##HD##x##G##B, "bf16") \ + G4K_ATTN_ROW(HD, G, fp8kv, cH##HD##x##G##F, "fp8-e4m3 (per-(seq,head) descales)") + +static const RadKernelInfo kKernels[] = { + G4K_ATTN_PAIR(256, 1) G4K_ATTN_PAIR(256, 2) G4K_ATTN_PAIR(256, 4) G4K_ATTN_PAIR(256, 8) + G4K_ATTN_PAIR(512, 1) G4K_ATTN_PAIR(512, 2) G4K_ATTN_PAIR(512, 4) G4K_ATTN_PAIR(512, 8) + + /* Described as libref describes it, so rad-kbench runs both arms against the oracle. */ + { "pair_argmax_f32", "pair_argmax", "select", + "the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped", + "any M and n; one wave a row; the outputs one element a row at their own pitch", + "f32 pairs (int32 id bits, f32 value), i32 idx, f32 val", + RAD_DOMAIN_DEVICE, 10, ROW(cPick), NOTUNE, + nullptr, nullptr, g4k_pair_argmax_f32, nullptr, nullptr, nullptr, shape_pick, + nullptr, nullptr, nullptr }, + /* NO opd_shape: libref has no row for these (see the schemas), so there is no oracle to run + * them against. The host arms state the arithmetic, and tests/g4k_emu checks the device + * kernels against them and against the unfused chain, bit for bit. */ + { "norm_add_norm_bf16", "norm_add_norm", "norm", + "post-norm, residual add, next pre-norm: one block a row, rounding where the chain rounds", + "n <= 6144, any M, row pitches honoured", "bf16 activations, f32 gains", + RAD_DOMAIN_DEVICE, 10, ROW(cJoin), NOTUNE, + nullptr, nullptr, g4k_norm_add_norm_bf16, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "norm_add_norm_bf16_host", "norm_add_norm", "norm", + "post-norm, residual add, next pre-norm, rounding where the chain rounds", "any [M, n]", + "bf16 activations, f32 gains", + RAD_DOMAIN_HOST, 10, ROW(cJoinHost), NOTUNE, + nullptr, nullptr, norm_add_norm_host, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "join_add_scale_bf16", "join_add_scale", "norm", + "two arms' post-norms, sum, norm, residual add, layer scalar: one block a row", + "n <= 6144, any M, row pitches honoured", "bf16 activations, f32 gains, bf16 scalar", + RAD_DOMAIN_DEVICE, 10, ROW(cJoin), NOTUNE, + nullptr, nullptr, g4k_join_add_scale_bf16, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "join_add_scale_bf16_host", "join_add_scale", "norm", + "two arms' post-norms, sum, norm, residual add, layer scalar", "any [M, n]", + "bf16 activations, f32 gains, bf16 scalar", + RAD_DOMAIN_HOST, 10, ROW(cJoinHost), NOTUNE, + nullptr, nullptr, join_add_scale_host, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "pair_argmax_f32_host", "pair_argmax", "select", + "the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped", + "any M and n", "f32 pairs (int32 id bits, f32 value), i32 idx, f32 val", + RAD_DOMAIN_HOST, 10, ROW(cPick), NOTUNE, + nullptr, nullptr, pick_host, nullptr, nullptr, nullptr, shape_pick, + nullptr, nullptr, nullptr }, +}; +#undef G4K_ATTN_PAIR +#undef G4K_ATTN_ROW + +} /* namespace */ + +extern "C" { + +uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } + +const RadPluginInfo* rad_plugin_info(void) { + static const RadPluginInfo i = { + RAD_PLUGIN_KERNEL, "gemma4k", "0.1.0", + "Gemma 4 text: paged attention at head_dim 256/512 (gqa 1/2/4/8, any window), the " + "sharded draft head's pair_argmax, and the sandwich-norm joins", + G4K_BUILD_TARGET, + }; + return &i; +} + +int rad_kernel_schema_count(void) { return (int)(sizeof(kSchemas) / sizeof(kSchemas[0])); } +const RadOpSchema* rad_kernel_schema_at(int i) { + return (i >= 0 && i < rad_kernel_schema_count()) ? &kSchemas[i] : nullptr; +} +int rad_kernel_count(void) { return (int)(sizeof(kKernels) / sizeof(kKernels[0])); } +const RadKernelInfo* rad_kernel_at(int i) { + return (i >= 0 && i < rad_kernel_count()) ? &kKernels[i] : nullptr; +} + +/* Every kernel here reads and writes its operands and its scratch, and nothing else: no state + * between launches, no allocation of its own (rad_abi.h, rad_kernel_concurrent). */ +int rad_kernel_concurrent(int) { return 1; } + +} /* extern "C" */ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2e959c40..4ad783d2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -200,6 +200,11 @@ set(RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libref.so) if(RAD_HIP_FOUND AND TARGET libr4d) list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libr4d.so) endif() +# gemma4k declares two ops no other library does (the sandwich joins), so without it their rows +# would be "unchecked" on every machine. +if(RAD_HIP_FOUND AND TARGET gemma4k) + list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/gemma4k.so) +endif() add_test(NAME ops_doc COMMAND ${CMAKE_SOURCE_DIR}/tools/ops_doc_check.sh ${CMAKE_SOURCE_DIR}/docs/OPS.md $