radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+104 -134
View File
@@ -1,23 +1,20 @@
// r4d_qk_norm_rope_gate.hip -- r4d_qk_norm_rope_gate: the whole gated-attention QKV preamble in one
// pass: split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE, and the gate copy.
//
// WHY. vLLM already has this fusion -- `fused_qk_rmsnorm_rope_gate` -- and gates it on
// `current_platform.is_cuda()`. The kernel behind it is plain Triton with nothing CUDA-specific in
// it, so the gate looks like conservatism, but it is not: on gfx1201 that kernel does not compile.
// Triton's AMD backend fails in `TritonAMDGPUCanonicalizePointers` on its pointer arithmetic. So
// ROCm runs the unfused branch -- a split, two GemmaRMSNorms, a RoPE and a gate chunk, which
// inductor lands as FOUR kernels per attention layer, 16 layers, 64 dispatches a decode step for
// ~6.3 us of work that is four passes over the same 14 KB.
// vLLM's equivalent fusion, `fused_qk_rmsnorm_rope_gate`, is gated on `is_cuda()`, and its Triton
// kernel does not compile on gfx1201 (Triton's AMD backend fails in
// `TritonAMDGPUCanonicalizePointers`). The unfused ROCm path is four kernels per attention layer
// (split, two GemmaRMSNorms, RoPE and gate chunk): 64 dispatches a decode step over 16 layers for
// ~6.3 us of work.
//
// WHAT IT IS BIT-FOR-BIT. The reference path stores the normed value to memory as bf16 and then
// RoPEs what it reads back, so the norm output is ROUNDED TO bf16 BEFORE the rotation. Skipping
// that round trip is more accurate and would be wrong: it is a different function. The `.to(
// INPUT_DTYPE).to(tl.float32)` in vLLM's own kernel is there for the same reason.
// Bit-identity: the reference stores the normed value as bf16 and RoPEs what it reads back, so the
// norm output is rounded to bf16 before the rotation. Skipping the round trip would be more
// accurate and a different function; vLLM's kernel has `.to(INPUT_DTYPE).to(tl.float32)` for the
// same reason.
//
// `wadd` IS ADDED TO EVERY GAIN. Qwen3NextRMSNorm is GemmaRMSNorm: `x_hat * (1 + w)` over a
// zero-centred gamma, formed in fp32. vLLM's fused kernel takes `weight.float() + 1.0` from the
// caller; this takes the bf16 weight and the offset, and adds it after the load, inside the fp32
// arithmetic -- identical, and it does not need a per-layer fp32 copy of the gain.
// `wadd` is added to every gain: Qwen3NextRMSNorm is GemmaRMSNorm, `x_hat * (1 + w)` over a
// zero-centred gamma in fp32. This takes the stored gain and the offset and adds them in fp32 after
// the load, which matches vLLM's `weight.float() + 1.0` without a per-layer fp32 copy.
//
#include "r4d.h"
#include "r4d_args.h"
@@ -28,33 +25,24 @@
#include <cstdint>
#include <cmath>
// ONE BLOCK PER (TOKEN, HEAD) AND ONE ELEMENT PER LANE, WHICH IS NOT A LAYOUT CHOICE -- IT IS THE
// BIT-EQUALITY REQUIREMENT.
// One block per (token, head) and one element per lane, required for bit-equality.
//
// The tempting layout gives each lane EIGHT CONSECUTIVE elements and reduces one wave per head: no
// LDS, no barrier, and the rotary partner one `__shfl_xor` away, because element i and i + rot/2
// sit in lanes (rot/2)/VPL apart. It is elegant and it is a DIFFERENT FUNCTION.
// `r4d_rmsnorm_bf16` states the rule that kills it: "the width decides which columns a thread
// folds into the sum of squares. Two kernels that disagree about it disagree in the last bits of
// the norm." A ULP in the mean square is a ULP in the normed value, a ROTATED element is a
// difference of two products, and where those nearly cancel the ULP comes out as a few percent --
// enough to move the engine's text within a few dozen steps, which forces the fusion off.
// Eight consecutive elements per lane with one wave per head (no LDS, rotary partner one shuffle
// away) computes a different function. r4d_rmsnorm_bf16's width decides which columns a thread
// folds into the sum of squares, and a last-bit difference in the norm becomes a few percent where
// a rotated element's two products nearly cancel, enough to change the engine's text within a few
// dozen steps.
//
// The reference's fold is reproducible exactly, and it is simpler than it looks. `rmsnorm_bf16`
// runs `for (i = threadIdx.x; i < n; i += THR)`, and `r4d_act_threads` never returns fewer than 256
// threads while every head_dim compiled here is at most 256 -- so the reference ALWAYS folds
// exactly one element per thread, whatever width it picks. The widths above the head dim contribute
// zeros, and adding 0.0f to an f32 accumulator is exact, so `block_sum` over 8 wave partials and
// over 32 of them are the same number. One element a lane, 256 threads, `block_sum` in ascending
// wave order: that is the whole of it.
// The reference's fold is easy to reproduce: `rmsnorm_bf16` runs
// `for (i = threadIdx.x; i < n; i += THR)`, `r4d_act_threads` never returns fewer than 256 threads,
// and every head_dim here is at most 256, so it always folds exactly one element per thread. Lanes
// past the head add exact zeros, so `block_sum` over 8 or 32 wave partials gives the same number.
// Hence one element a lane, 256 threads, `block_sum` in ascending wave order.
//
// WHAT IT COSTS: the rotary partner is `rot/2` lanes away, which at rot 64 is a different WAVE, so
// no shuffle reaches it. The partner is RE-DERIVED rather than exchanged through LDS and a
// barrier -- the lane loads the partner's input element and norms it itself, which is one L1-hot
// read and the same `inv` the block already agreed on. No shared memory beyond block_sum's eight
// floats, and no barrier the reduction did not already need.
/* THE PAGED CACHE the KV form writes: kv_store's operands and parameters, in one argument so the
* launch stays inside the emitter's parameter budget. The descales are read by the E4M3 form only. */
// Cost: at rot 64 the rotary partner is in another wave. The lane re-derives it instead of an LDS
// exchange: it loads the partner's input (an L1-hot read) and norms it with the block's `inv`.
/* The paged cache the KV form writes: kv_store's operands and parameters in one argument, to stay
* inside the emitter's parameter budget. Only the E4M3 form reads the descales. */
struct QkKvStore {
const __hip_bfloat16* v;
const int32_t* slot;
@@ -66,17 +54,16 @@ struct QkKvStore {
/* The cache forms KV selects. */
enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2 };
/* KV folds kv_store in: a k head's block, holding its token's rotated k one element a lane, also
* writes that element and the head's v element into the cache at the token's slot -- as E4M3 with
* kv_store_fp8's arithmetic element for element, or as the bf16 kv_store_bf16 copies (see the store
* at the end). */
/* KV folds kv_store in: a k head's block, holding the token's rotated k one element per lane, also
* writes that element and the head's v element into the cache at the token's slot, as E4M3 with
* kv_store_fp8's arithmetic or as bf16 like kv_store_bf16 (see the store at the end). */
template <int HD, int KV = QK_KV_NONE>
__global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K,
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO,
__hip_bfloat16* __restrict__ GO,
const void* __restrict__ WQ, const void* __restrict__ WK,
const void* __restrict__ CS, const void* __restrict__ POS,
const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows,
int nq, int nkv, int rot, float eps, float wadd,
int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) {
constexpr int THR = 256;
@@ -89,36 +76,34 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
const int lh = isk ? h - nq : h;
const __hip_bfloat16* in = isk ? (K + (size_t)tok * k_pitch + (size_t)lh * HD)
: (QG + (size_t)tok * qg_pitch + (size_t)lh * 2 * HD);
// THE GAIN IS f32 IN THIS MODEL AND bf16 IN vLLM's, and both are the dtype the unfused rmsnorm
// beside it would have read -- so the width is a property of the operand, not of the kernel.
// The gain is f32 in this engine's plugins and bf16 in vLLM's; its width follows the operand.
const void* w = isk ? WK : WQ;
__hip_bfloat16* out = isk ? (KO + ((size_t)tok * nkv + lh) * HD)
: (QO + ((size_t)tok * nq + lh) * HD);
const float* csf = (const float*)CS;
const __hip_bfloat16* csb = (const __hip_bfloat16*)CS;
// `gain` is spelled once so the two sites that need it -- this lane's element and, in the rotary
// range, its partner's -- cannot pick different widths.
// Spelled once so this lane's element and its rotary partner cannot use different widths.
auto gain = [&](int i) -> float {
return w_f32 ? ((const float*)w)[i] : __bfloat162float(((const __hip_bfloat16*)w)[i]);
};
// ROUNDED TO bf16 BEFORE THE ROTATION, which is the whole bit-identity argument at the top of
// this file: the reference stores the norm and RoPEs what it reads back.
// Rounded to bf16 before the rotation; see the bit-identity note at the top of this file.
auto normed = [&](float v, float g, float inv) -> float {
return __bfloat162float(__float2bfloat16(v * inv * (g + wadd)));
};
// EVERYTHING THE ROTATION READS IS LOADED HERE, ahead of the reduction, so it is in flight while
// the sum of squares goes round: this lane's element and gain, its partner's, and its cos and
// sin. None of it depends on the norm. The indices are clamped rather than the loads guarded --
// a lane past the head reads its last element, a lane past the rotary range its own element and
// column 0 of the table (rot >= 2, so the table has one) -- and the values are used only where
// the guards below say.
// Everything the rotation reads is loaded before the reduction, so it is in flight during the
// sum of squares: this lane's element and gain, its partner's, and its cos and sin. Indices are
// clamped instead of guarding the loads (a lane past the head reads its last element; a lane past
// the rotary range reads its own element and table column 0, which exists since rot >= 2), and
// the values are used only where the guards below allow.
const int tc = t < HD ? t : HD - 1;
const bool rl = t < rot, first = t < half;
const int pt = rl ? (first ? t + half : t - half) : tc;
const int ci = rl ? (first ? t : t - half) : 0;
const size_t co = (size_t)p * rot;
// The table row is clamped: a padded row (negative) or a position past the table's height has no
// row rope_table wrote, and must not read outside the plane.
const size_t co = (size_t)(p < 0 ? 0 : (p < cs_rows ? p : cs_rows - 1)) * rot;
const float vt = __bfloat162float(in[tc]), gt = gain(tc);
const float vp = __bfloat162float(in[pt]), gp = gain(pt);
const float c = cs_f32 ? csf[co + ci] : __bfloat162float(csb[co + ci]);
@@ -127,9 +112,8 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
float ss = 0.0f;
if (t < HD) ss = vt * vt;
// rmsnorm_bf16's block_sum, transcribed: the wave butterfly, then the wave partials summed in
// ASCENDING index order. Both halves matter -- an accumulation over the same values in a
// different order breaks the bit-equality argument above. The barrier orders the partials in LDS
// and nothing else, so the loads above stay in flight across it.
// ascending order. Any other order breaks the bit-equality above. The barrier orders only the LDS
// partials, so the loads above stay in flight across it.
ss = r4d_wave_sum(ss);
if ((t & 31) == 0) lds[t >> 5] = ss;
lds_barrier();
@@ -146,28 +130,23 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
res = first ? (res * c - xp * s) : (xp * s + res * c);
}
}
// EVERY LANE HAS READ ITS INPUT BEFORE ANY LANE WRITES IT BACK. `k` is rotated IN PLACE by the
// engine -- one buffer for the operand and the result -- and under the one-element-a-lane layout
// a lane's partner element is a MEMORY READ rather than a shuffle, so without this barrier the
// partner may already have been overwritten. A shuffle-based layout does not need the barrier,
// which is exactly why it is easy to leave out here: the failure is a 1% scatter of elements
// that reads like a rounding difference and is not one. r4d_selftest's byte-equality row catches
// it.
// Every lane must read its input before any lane writes back: the engine rotates `k` in place,
// and a lane's partner is a memory read, so without this barrier it may already be overwritten.
// The failure is a ~1% scatter of wrong elements that looks like rounding; r4d_selftest's
// byte-equality row catches it.
__syncthreads();
if (t < HD) {
out[t] = __float2bfloat16(res);
// `gate_out` is OPTIONAL in the schema, and a caller that already reads the gate straight out
// of the interleaved projection -- which the fp8 block does, through gate_quant_fp8 -- passes
// none rather than paying for a copy it will not read.
// `gate_out` is optional: a caller that reads the gate straight from the interleaved projection
// (the fp8 block, via gate_quant_fp8) passes none.
if (!isk && GO) GO[((size_t)tok * nq + lh) * HD + t] = in[HD + t];
}
// THE CACHE WRITE kv_store WOULD MAKE NEXT, from the same bytes it would read: the rotated k as
// the bf16 just stored and the v row as the projection left it. The E4M3 form scales each by the
// inverse descale, clamps (v_cvt_pk_fp8_f32 answers out-of-range with NaN) and converts; the pair
// conversion there rounds each element on its own, so one element a lane is the same byte. The
// bf16 form stores the two values as they are, which is all kv_store_bf16 does. The layout is
// [n_blocks, kv_heads, block_size, 2*head_dim], k then v, in the cache's element; a negative or
// out-of-range slot stores nothing.
// The cache write kv_store would make next, from the same bytes: the rotated k as just stored
// and the v row as the projection left it. The E4M3 form scales by the inverse descale, clamps
// (v_cvt_pk_fp8_f32 returns NaN out of range) and converts each element on its own, so one
// element a lane gives the same byte. The bf16 form stores the values as kv_store_bf16 does.
// Layout [n_blocks, kv_heads, block_size, 2*head_dim], k then v; a negative or out-of-range slot
// stores nothing.
if constexpr (KV != QK_KV_NONE) {
if (isk && t < HD) {
const int32_t sl = kvs.slot[tok];
@@ -198,31 +177,28 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
}
}
// ============================================================ the cos/sin table
//
// The fused kernel above reads a PRECOMPUTED table instead of theta, and this fills it. One launch
// a step serves every attention layer, against one rope launch a layer -- which is the whole point:
// at head_dim 256 the rotation is ~7 us of dispatch for ~1 us of work, sixteen times over.
// The fused kernel reads a precomputed table instead of theta, and this fills it: one launch per
// step for every attention layer, instead of a rope launch per layer (~7 us of dispatch for ~1 us
// of work at head_dim 256).
//
// IT IS WRITTEN AT THE POSITION'S OWN ROW, so the table has a row per position the model can name
// and only the rows a step actually touches are filled. A decode step touches at most a few dozen
// of them, so this moves kilobytes and not the six megabytes a whole table would. Rows nothing
// Each position is written at its own row, so the table has a row per nameable position and only
// the rows a step touches are filled (kilobytes at decode, not the whole ~6 MB table). Rows nothing
// addresses are never read.
//
// THE ARITHMETIC IS r4d_model_bf16.hip's rope_kernel, LINE FOR LINE, and that is what makes the
// fusion bit-for-bit rather than merely close: `1.0f / powf(theta, 2i/den)`, where `den` is the
// ladder's width (`rot` for `rotary`, `head_dim` for `head`), the position divided by `rscale`
// in f32, `sincosf`, and the products consumed in f32 by the caller. Changing any of those here
// silently changes the model's output -- a different rope is a different model.
// The arithmetic is r4d_model_bf16.hip's rope_kernel line for line, which makes the fusion
// bit-identical: `1.0f / powf(theta, 2i/den)` with `den` the ladder's width (`rot` for `rotary`,
// `head_dim` for `head`), the position divided by `rscale` in f32, `sincosf`, and the products
// consumed in f32 by the caller. Changing any of it changes the model's output.
__global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, int den, float theta,
float rscale, int cs_f32, int pos_i64, RadYarn yarn) {
const int m = blockIdx.x;
const long pp = pos_i64 ? ((const long*)POS)[m] : (long)((const int*)POS)[m];
// A padded row addresses no table row, and a position at or past the table's height writes
// nothing: its row would land in whatever buffer the arena placed after the plane. libref and
// libavx skip the same rows.
// nothing (it would land in whatever the arena placed after the plane). libref and libavx skip
// the same rows.
if (pp < 0 || pp >= rows) return;
const int half = rot >> 1;
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
@@ -243,13 +219,13 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
}
// The two launches, as the plugin ABI's RadLaunchFn. See the note at the head of
// r4d_quant_act_i8.hip for why the flattened argument list and the throws are gone.
// r4d_quant_act_i8.hip on the argument list and status return.
enum { QK_QGATE = 0, QK_K, QK_COSSIN, QK_POS, QK_WQ, QK_WK, QK_QOUT, QK_KOUT, QK_GOUT,
QK_V, QK_SLOT, QK_CACHE };
/* The body of both forms; KVF is the kv_store fold and `kvs` its cache, already checked. */
template <int KVF>
static int qk_body(const RadArgs* args, const R4dSink& sk, const QkKvStore& kvs) {
static int qk_body(const RadArgs* args, RadStream stream, const QkKvStore& kvs) {
const RadTensor* qg = r4d_opt(args, QK_QGATE);
const RadTensor* k = r4d_opt(args, QK_K);
const RadTensor* cs = r4d_opt(args, QK_COSSIN);
@@ -259,12 +235,10 @@ static int qk_body(const RadArgs* args, const R4dSink& sk, const QkKvStore& kvs)
const RadTensor* qo = r4d_opt(args, QK_QOUT);
const RadTensor* ko = r4d_opt(args, QK_KOUT);
const RadTensor* go = r4d_opt(args, QK_GOUT);
// THE K-ONLY FORM. `n_head` 0 means the caller has no [q|gate] projection to split -- its heads
// are already one plain `head_dim` run each -- so `q_gate`, `q_w` and `q_out` are absent and
// every head is served off `k`. The KERNEL NEEDS NOTHING for this: `isk` is `h >= nq`, so at
// nq 0 every block takes the k path and the three absent operands are never dereferenced
// (`r4d_p` and `r4d_wp` already return null for an absent tensor, so the launch needs no case
// of its own).
// The k-only form: `n_head` 0 means there is no [q|gate] projection to split (each head is a
// plain `head_dim` run), so `q_gate`, `q_w` and `q_out` are absent and every head is served off
// `k`. The kernel needs nothing for it: `isk` is `h >= nq`, so at nq 0 every block takes the k
// path and the absent operands (null via r4d_p / r4d_wp) are never dereferenced.
if (!k || !cs || !po || !wk || !ko) return R4D_NO(RAD_E_INVAL);
if (!r4d_contig(cs) || !r4d_contig(po) || !r4d_contig(wk)) return R4D_NO(RAD_E_STRIDE);
if (!r4d_contig(ko)) return R4D_NO(RAD_E_STRIDE);
@@ -282,32 +256,33 @@ static int qk_body(const RadArgs* args, const R4dSink& sk, const QkKvStore& kvs)
const long long k_pitch = r4d_row_pitch(k);
if (qg_pitch < 0 || k_pitch < 0) return R4D_NO(RAD_E_STRIDE);
// The row count is the OPERAND'S, and which operand carries it is what the form decides.
// The row count is the operand's; which operand carries it depends on the form.
const long long M = qg ? qg->shape[0] : k->shape[0];
if (M < 1) return R4D_NO(RAD_E_SHAPE);
if (hd != 64 && hd != 128 && hd != 256) return R4D_NO(RAD_E_SHAPE); // the compiled set
if (rot < 2 || (rot & 1) || rot > hd) return R4D_NO(RAD_E_SHAPE);
const long long cs_rows = r4d_numel(cs) / rot;
if (cs_rows < 1 || r4d_numel(cs) % rot) return R4D_NO(RAD_E_SHAPE);
const float eps = (float)r4d_getf(args, "eps", 1e-6);
const float wadd = (float)r4d_getf(args, "wadd", 0.0);
// The two width flags are read off the OPERANDS rather than declared twice: a cos/sin table
// built in f32 and a positions vector in int64 are what the tensor SAYS they are.
// The width flags come from the operands: a cos/sin table in f32 and positions in int64 are what
// the tensors say they are.
const int cs_f32 = (cs->dtype == RAD_F32) ? 1 : 0;
const int pos_i64 = (po->dtype == RAD_I64) ? 1 : 0;
// THE NORM GAIN'S WIDTH IS THE OPERAND'S TOO, and it is f32 in every architecture plugin here
// where vLLM's is bf16. The two gains must agree, because one flag serves both.
// The norm gain's width is the operand's too (f32 in every architecture plugin here, bf16 in
// vLLM). One flag serves both gains, so they must agree.
if (wq && wq->dtype != wk->dtype) return R4D_NO(RAD_E_DTYPE);
if (wk->dtype != RAD_F32 && wk->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
const int w_f32 = (wk->dtype == RAD_F32) ? 1 : 0;
const int nh = (int)(nq + nkv);
// One block a (token, head), 256 threads, one element a lane. The width is FIXED at 256 and not
// fitted to the head count: it is what makes the sum of squares agree with r4d_rmsnorm_bf16, and
// the kernel says at length why.
#define R4D_QKG_L(H) emit_rc = R4D_EMIT(sk, (r4d_qk_norm_rope_gate_kernel<H, KVF>), \
// One block per (token, head), 256 threads, one element per lane. The width is fixed at 256, not
// fitted to the head count, so the sum of squares matches r4d_rmsnorm_bf16 (see the kernel).
#define R4D_QKG_L(H) emit_rc = R4D_EMIT(stream, (r4d_qk_norm_rope_gate_kernel<H, KVF>), \
dim3((int)M, nh), dim3(256), 0, (const __hip_bfloat16*)r4d_p(qg), \
(const __hip_bfloat16*)r4d_p(k), (__hip_bfloat16*)r4d_wp(qo), (__hip_bfloat16*)r4d_wp(ko), \
(__hip_bfloat16*)r4d_wp(go), r4d_p(wq), r4d_p(wk), r4d_p(cs), r4d_p(po), \
(__hip_bfloat16*)r4d_wp(go), r4d_p(wq), r4d_p(wk), r4d_p(cs), r4d_p(po), (long)cs_rows, \
(int)nq, (int)nkv, (int)rot, eps, wadd, (int)qg_pitch, (int)k_pitch, cs_f32, pos_i64, w_f32, \
kvs)
int emit_rc = RAD_OK;
@@ -320,17 +295,15 @@ static int qk_body(const RadArgs* args, const R4dSink& sk, const QkKvStore& kvs)
return emit_rc;
}
static int rad_qk_norm_rope_gate_body(const RadArgs* args, const R4dSink& sk) {
return qk_body<QK_KV_NONE>(args, sk, QkKvStore{});
extern "C" int r4d_rad_qk_norm_rope_gate(const RadArgs* args, RadStream stream) {
return qk_body<QK_KV_NONE>(args, stream, QkKvStore{});
}
R4D_ENTRY(r4d_rad_qk_norm_rope_gate, rad_qk_norm_rope_gate_body)
/* THE PROLOGUE WITH THE KV STORE FOLDED IN: qk_norm_rope_gate's operands, then kv_store's `v`,
* `slot_mapping` and `kv_cache`, and kv_store's parameters. The cache is E4M3 or bf16, whichever
* `kv_dtype` names and the tensor is, checked the way kv_store checks it, and one slot a row of
* the prologue. The k kv_store would read is the prologue's own output, so it is not an operand of
* its own. */
static int rad_qk_norm_rope_gate_kv_store_body(const RadArgs* args, const R4dSink& sk) {
/* The prologue with the KV store folded in: qk_norm_rope_gate's operands, then kv_store's `v`,
* `slot_mapping` and `kv_cache`, and its parameters. The cache is E4M3 or bf16 as `kv_dtype`
* names, checked as kv_store checks it, one slot per prologue row. The k kv_store would read is the
* prologue's own output, so it is not a separate operand. */
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream stream) {
const RadTensor* k = r4d_opt(args, QK_K);
const RadTensor* qg = r4d_opt(args, QK_QGATE);
const RadTensor* v = r4d_opt(args, QK_V);
@@ -369,20 +342,17 @@ static int rad_qk_norm_rope_gate_kv_store_body(const RadArgs* args, const R4dSin
kvs.n_blocks = (int)kv->shape[0];
kvs.k_inv = 1.0f / (float)ks;
kvs.v_inv = 1.0f / (float)vs;
return kv->dtype == RAD_BF16 ? qk_body<QK_KV_BF16>(args, sk, kvs)
: qk_body<QK_KV_FP8>(args, sk, kvs);
return kv->dtype == RAD_BF16 ? qk_body<QK_KV_BF16>(args, stream, kvs)
: qk_body<QK_KV_FP8>(args, stream, kvs);
}
R4D_ENTRY(r4d_rad_qk_norm_rope_gate_kv_store, rad_qk_norm_rope_gate_kv_store_body)
// The cos/sin plane the fused prologue above reads. One launch a step against `rope`'s one a
// layer, and the reason the fusion is reachable at all: `qk_norm_rope_gate` takes a table and not
// a theta, and until this row existed nothing in the tree could build one.
// The cos/sin plane the fused prologue reads: one launch a step, against `rope`'s one per layer.
// `qk_norm_rope_gate` takes a table, not a theta, so this row is what makes it usable.
//
// ONLY THE ROWS `positions` NAMES ARE WRITTEN, at each position's own row of a [rows, rot] plane
// whose height is the operand's. A decode step names a few dozen, so this moves kilobytes where a
// whole-table fill would move six megabytes; a row nothing addresses keeps whatever it held, which
// is correct because nothing reads it.
static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) {
// Only the rows `positions` names are written, each at its own row of a [rows, rot] plane whose
// height is the operand's. A row nothing addresses keeps its contents, which is correct because
// nothing reads it.
extern "C" int r4d_rad_rope_table(const RadArgs* args, RadStream stream) {
const RadTensor* po = r4d_opt(args, 0);
const RadTensor* cs = r4d_opt(args, 1);
if (!po || !cs) return R4D_NO(RAD_E_INVAL);
@@ -390,8 +360,8 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) {
if (cs->dtype != RAD_F32 && cs->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (po->dtype != RAD_I32 && po->dtype != RAD_I64) return R4D_NO(RAD_E_DTYPE);
// The row count is the OPERAND'S: `M` is declared as a band ceiling and this is called with a
// step's rows, not the band's.
// The row count is the operand's: `M` is declared as a band ceiling, but the call carries a
// step's rows.
const long long M = r4d_numel(po);
const long long rot = r4d_geti_or(args, "rot", 0);
if (M < 1 || rot < 2 || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
@@ -406,16 +376,16 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) {
if (!std::strcmp(lad, "head")) {
if (head_dim <= 0) return R4D_NO(RAD_E_SHAPE);
den = head_dim;
} else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head"))
} else if (std::strcmp(lad, "rotary")) {
return R4D_NO(RAD_E_UNSUPPORTED);
}
}
const float theta = (float)r4d_getf(args, "theta", 10000.0);
const float rscale = (float)r4d_getf(args, "scale", 1.0);
const RadYarn yarn = rad_yarn_args(args);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return R4D_NO(RAD_E_INVAL);
return R4D_EMIT(sk, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0,
return R4D_EMIT(stream, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0,
r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, (int)den, theta,
rscale, cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn);
}
R4D_ENTRY(r4d_rad_rope_table, rad_rope_table_body)