This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/gemma4k/g4k_pick.hip
T
AshlynandClaude Opus 5.5 833173cc04 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 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00

106 lines
4.4 KiB
Plaintext

/* 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 <hip/hip_runtime.h>
#include <cstdint>
#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;
}