radiance 2.1.0

New models. Recursive Flint (39.8B, about 2.5B active) by everplays (#422): `arch/flint`, as an
IQ8R container with rotated int8 experts or a four-bit one, with a sink-aware WMMA prefill
attention and the fused attention prologue at `rotary_dim` 0. Meta Muse Glimmer 30B by
launch80_assets (#423): bf16, an int4 trunk or IQ8R, its windowed vision tower, its DFlash
drafter, the ATEM tool dialect and context extension. Ling-3.0-tiny by RikshaDriver (#441):
served from its GGUF releases or as IQ8R on `bailing_hybrid`, with six more libr3d kernels. Block
FP8, MXFP4 and NVFP4 conversions of the three are not served. IQ8R containers of all three
(round to nearest, no calibration) are on Hugging Face under StillDeadcode: flint-iq8r,
muse-glimmer-30b-iq8r-dflash and ling-3.0-tiny-iq8r. They were checked for sane answers on two
R9700; nothing was benchmarked, and Muse Glimmer's pictures, video and tool calls were not tried.

Speech. Breeze-TTS-2 clones a voice from a reference recording and its transcript, with an
optional delivery direction, by farcryjohn (#436). The published Breeze container needs
converting again with the updated recipe before it can.

Tools. A model entry with `diagnose: DIR` runs a fixed workload on the engine instead of serving
and writes a report: step times, tokens a step, draft acceptance, TTFT and prefill rates by
category, concurrency and prompt length, and with `diagnose-baseline` a token-for-token comparison
against an earlier report (docs/DIAGNOSE.md), by Code000 (#418).

Scheduler. `mixed-step-target-ms` holds a mixed prefill and decode step to a service time, off by
default, by tnhnyzc (#413). `scheduler.stuck-exit` (60s by default, 0 never) ends the process when
the device has advanced nothing for that long, so a restart policy brings a hung server back
(#409, #415, #428).

Fixed. Draft trees with the int8 KV cache, which stopped Gemma 4 31B with DFlash2 on its first
request (#454, diagnosed by aelfwyne). The expert loan held at zero by a few leftover cache blocks
after long sessions (#455, diagnosed by thekk1). The mapped tier's pages kept in the page cache
across a load and a restore, by C_Tamas (#421). Replayed tool calls with blank arguments, and
arguments that are not JSON refused naming the call, by dschmitz (#444). The dashboard's card
temperature reads the junction sensor, by dschmitz (#453). The VRAM shortfall report says what the
KL mode needs, by baKon (#448). The out-of-tree plugin test builds its plugins in parallel and
takes its toolchain from the tree.

Plugin ABI 40: out-of-tree plugins need to be rebuilt.

Thanks to @everplays, @launch80_assets, @RikshaDriver, @farcryjohn, @Code000, @tnhnyzc, @C_Tamas, @dschmitz, @baKon, @aelfwyne and @thekk1.
This commit is contained in:
Deadcode committed 2026-11-15 16:00:05 +01:00
1 parent ddcb9c69bb
commit 2a2b756371
166 files changed
+20749 -327

No files matched your search

+16
View File
@@ -78,6 +78,11 @@ set(R3D_UNITS
# split-KV) and the prefill leg (a 16-token query tile staged in LDS), over a bf16 or an E4M3
# cache. The walk is shared; the tile is what a workgroup stages once and every wave consumes.
"r3d_attn_paged_h128|"
# Absorbed MLA: the per-head projections (absorb/expand through the shared latent weight).
"r3d_mla_project|"
# Dense causal latent attention over a paged [latent | rope] cache: a wave a (row, head), the
# score one wave sum, split history with an f32 partial merge, the optional head gate.
"r3d_mla_attn_paged|"
# The sampler's spine: the row's top-R in one scan, and the stages that turn the candidate plane
# the top-R produces into one token -- argmax, temp, top-k, the draw, and the four narrowings.
"r3d_sample_f32|"
@@ -124,10 +129,21 @@ set(R3D_UNITS
"r3d_gdn_gated_rmsnorm_h128|"
"r3d_gdn_gated_norm_had_quant_i8|"
"r3d_gdn_conv_w4_h128|"
# GLM's per-channel KDA recurrence over the paged f32 state cache, with the speculative
# candidate snapshots (the state in registers, no LDS).
"r3d_kda_update|"
# PLE's dilated depthwise convolution (taps `dilation` apart), its silu and the residual add:
# one thread a channel walking a 32-token tile, with the conv window's write-back fused in.
"r3d_ple_conv|"
# Mixture of experts: each routing weight times its expert's own scale, in place.
"r3d_expert_scale_bf16|"
# The router: softmax over the expert logits, the top_k by value, renormalised if `norm`.
"r3d_moe_router_topk_bf16|"
# The router's F32 projection: a bf16 activation against an f32 weight, f32 out.
"r3d_gemm_nt_f32|"
# The group-limited sigmoid router (Ling-3.0's noaux_tc): the groups ranked by their two best
# p + bias, selection over the kept groups' experts, one wave a row.
"r3d_router_group_topk|"
# The routed slots' stable counting sort (the small form, one workgroup).
"r3d_moe_scatter|"
# Fold the expert outputs back to the token (the gather, and the inverse-table form).
+189
View File
@@ -0,0 +1,189 @@
/* r3d_gemm_nt_f32.hip -- gemm_nt_f32: the router's and the index gate's F32 projection.
x [M][K] bf16, w [N][K] f32 -> y [M][N] f32, y = x @ w^T
Routing logits and index-head gates stay F32 projections even in a BF16 checkpoint (libref's
ref_gemm_nt_f32), so nothing narrows: the accumulation is f32, the weight is read as f32 and the
store writes f32. N is tiny -- a checkpoint's expert count, a handful of gate columns, at most
512 -- against a hidden width K, so the op streams the weight plane and is bandwidth-bound, not
compute-bound. There is no matrix tile here and RDNA3's wave matrix could not take it: the wave
matrix is f16 and i8 only (r3d_common.h), an f32 weight has no fragment form. Plain f32 FMAs,
one output element a lane-grid, is the arithmetic and the idiomatic libr3d shape for a GEMV-like
projection.
---- the lane map --------------------------------------------------------------------------
One wave computes R rows by C columns, so each loaded weight serves R rows and each input C
columns. Every output has the same arithmetic: lane l folds k = l, l+32, ... ascending with fmaf,
then the xor butterfly over 16, 8, 4, 2, 1. libr3d runs that butterfly with wave_sum (DPP16 and
v_permlanex16, r3d_common.h), which is the same exchange in the same order as the __shfl_xor
loop libr4d uses, so a wave's sum is bit-for-bit the sum libr4d's wave forms and the row's host
arithmetic in r4d_selftest --perff32 write out. Every form below is byte-identical to every
other: the wave count, the tile and the steps in flight change how the bytes are fetched, never
how they add. Tail rows and columns read a clamped valid address and are never stored.
A lane loads U steps of k before their FMAs. At a decode pass's few rows a wave streams its
weight row with no other work to hide the load behind, and one step in flight leaves the router
at a fraction of the card's bandwidth; the deep forms buy that latency back with registers.
---- what the launcher checks ---------------------------------------------------------------
The three operands present, x bf16, w f32 and y f32 (RAD_E_DTYPE), 1 <= N <= 512 and
1 <= K <= 16384, x, w and y rank 2 with x [M][K], w [N][K] and y [M][N] for x's own M
(RAD_E_SHAPE), every row k-contiguous with a pitch of at least the row's width (the same
RAD_E_SHAPE, as in libr4d), and M within the row-count grid, 1..65535. Nothing is staged in
LDS, so RDNA3's 64 KiB a workgroup is not in play; the check below is written against the cap
so a staged form added later cannot skip it.
---- RDNA4 -> RDNA3 -------------------------------------------------------------------------
The tiling (R rows, C columns, U steps of k in flight), the four forms and the rule that picks
one are libr4d's (r4d_glm.hip, gemm_nt_f32_tile_kernel), transcribed: the arithmetic is
identical, so the choice between forms is speed only. The block stays four waves of 32 and the
grid x * 4 * C columns by y * R rows. The reduction is wave_sum, not __shfl_xor: on gfx11 a
shuffle is a ds_bpermute plus an LDS wait, and five of them per accumulator dominates a wave's
tail. R3D_WAVES(8) states the occupancy against gfx11's 1024 VGPRs a SIMD at wave32: the
U = 16 form carries 2 * 16 * 2 = 64 registers of loads in flight plus R * C accumulators, inside
the 128 eight waves a SIMD allows. The form rule's thresholds are gfx1201's measurements as
libr4d quotes them; they are kept as the starting point, and a tune on a gfx11 part is free to
move them, because every form computes the same bytes.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 128; // four waves a block, as in libr4d
constexpr uint32_t kWaves = kThreads / kWave;
constexpr uint32_t kWavesPerSimd = 8; // 1024 VGPRs a SIMD / 8 = 128 a wave
/* The geometry the shim admits, from the row's constraint table. */
constexpr long long kNMax = 512, kKMax = 16384, kMMax = 65535;
/* Dynamic LDS a launch asks for. Every form keeps its tile in registers, so the launch's shared
* byte count is 0 and the cap below is the exemplar's, for the launcher to enforce. */
constexpr size_t kStageBytes = 0;
template <int R, int C, int U>
__global__ void __launch_bounds__(kThreads) R3D_WAVES(kWavesPerSimd)
gemm_nt_f32_tile_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, long yp,
int m, int n, int k) {
const int lane = (int)(threadIdx.x & (kWave - 1)), wave = (int)(threadIdx.x / kWave);
const int c0 = (int)(blockIdx.x * kWaves + (unsigned)wave) * C, r0 = (int)blockIdx.y * R;
if (c0 >= n) return;
const uint16_t* xr[R];
const float* wc[C];
#pragma unroll
for (int q = 0; q < R; ++q) xr[q] = x + (long)(r0 + q < m ? r0 + q : m - 1) * xp;
#pragma unroll
for (int c = 0; c < C; ++c) wc[c] = w + (long)(c0 + c < n ? c0 + c : n - 1) * wp;
float sum[R][C];
#pragma unroll
for (int q = 0; q < R; ++q)
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = 0;
int j = lane;
for (; j + 32 * (U - 1) < k; j += 32 * U) {
float weight[U][C];
uint32_t in[U][R];
#pragma unroll
for (int u = 0; u < U; ++u)
#pragma unroll
for (int c = 0; c < C; ++c) weight[u][c] = ldg_f32(wc[c] + j + 32 * u);
#pragma unroll
for (int u = 0; u < U; ++u)
#pragma unroll
for (int q = 0; q < R; ++q) in[u][q] = ldg_u16(xr[q] + j + 32 * u);
#pragma unroll
for (int u = 0; u < U; ++u)
#pragma unroll
for (int q = 0; q < R; ++q) {
const float v = bf16_to_f32((uint16_t)in[u][q]);
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, weight[u][c], sum[q][c]);
}
}
for (; j < k; j += 32) {
#pragma unroll
for (int q = 0; q < R; ++q) {
const float v = bf16_to_f32((uint16_t)ldg_u16(xr[q] + j));
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, ldg_f32(wc[c] + j), sum[q][c]);
}
}
#pragma unroll
for (int q = 0; q < R; ++q)
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = wave_sum(sum[q][c]);
if (lane) return;
#pragma unroll
for (int q = 0; q < R; ++q)
if (r0 + q < m)
#pragma unroll
for (int c = 0; c < C; ++c)
if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c];
}
/* One tile form at the grid it owns: x * 4 * C columns, y * R rows, no LDS. */
template <int R, int C, int U = 1>
int gemm_f32_tile(RadStream s, const void* x, const void* w, void* y, long xp, long wp, long yp,
long m, long n, long k) {
const dim3 grid((unsigned)((n + (long)kWaves * C - 1) / ((long)kWaves * C)),
(unsigned)((m + R - 1) / R)), blk(kThreads);
R3D_KLAUNCH(R3D_KNAME((gemm_nt_f32_tile_kernel<R, C, U>)), grid, blk, (hipStream_t)s,
(const uint16_t*)x, (const float*)w, (float*)y, xp, wp, yp, (int)m, (int)n, (int)k);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
/* The tile form, rows x columns a wave and steps of k in flight, by M; all forms are
* byte-identical, so the choice is speed only. Measured on gfx1201 (r4d_selftest --perff32, cold)
* at N 4/32/36/288, K 4096: 16x4 gains 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36;
* 8x4 holds at every width. Below 64 rows the steps of k in flight decide: 2x2 with 16 steps is 2
* to 2.5 times as fast as one step at N 288 up to 16 rows, and about 3 times at N 32 at every
* count below 64; at N 288 from 17 rows 8x1 with 8 steps is faster. A projection of a few columns
* has too few waves for wide tiles at any M. The thresholds are libr4d's, kept as the starting
* point for gfx11: the forms compute the same bytes, so a tune here moves them, not the kernel. */
int gemm_f32_body(const RadArgs* a, RadStream s) {
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor *xt = &a->t[0], *wt = &a->t[1], *yt = &a->t[2];
const long long n = r3d_geti_or(a, "N", 0), k = r3d_geti_or(a, "K", 0);
if (xt->dtype != RAD_BF16 || wt->dtype != RAD_F32 || yt->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
if (!r3d_p(xt) || !r3d_p(wt) || !r3d_wp(yt)) return R3D_NO(RAD_E_INVAL);
if (n < 1 || n > kNMax || k < 1 || k > kKMax || xt->rank != 2 || wt->rank != 2 ||
yt->rank != 2 || xt->shape[0] < 1 || xt->shape[0] > kMMax || xt->shape[1] != k ||
wt->shape[0] != n || wt->shape[1] != k || yt->shape[0] != xt->shape[0] ||
yt->shape[1] != n || xt->stride[1] != 1 || wt->stride[1] != 1 || yt->stride[1] != 1 ||
xt->stride[0] < k || wt->stride[0] < k || yt->stride[0] < n)
return R3D_NO(RAD_E_SHAPE);
/* Nothing is staged: a wave's whole tile is its register grid, so RDNA3's 64 KiB a workgroup
* is not in play. The cap is asserted where the exemplar's launcher checks it, so a staged
* form added to this unit cannot skip it. */
static_assert(kStageBytes <= 60 * 1024, "a workgroup's stage must fit RDNA3's 64 KiB of LDS");
const long m = (long)xt->shape[0]; // the step's rows, not the band's bound
const void* px = r3d_p(xt);
const void* pw = r3d_p(wt);
void* py = r3d_wp(yt);
const long xp = (long)xt->stride[0], wp = (long)wt->stride[0], yp = (long)yt->stride[0];
if (n <= 8) return gemm_f32_tile<4, 1>(s, px, pw, py, xp, wp, yp, m, n, k);
if (m <= 16 || (m < 64 && n < 128)) return gemm_f32_tile<2, 2, 16>(s, px, pw, py, xp, wp, yp, m, n, k);
if (m < 64) return gemm_f32_tile<8, 1, 8>(s, px, pw, py, xp, wp, yp, m, n, k);
return gemm_f32_tile<8, 4>(s, px, pw, py, xp, wp, yp, m, n, k);
}
} // namespace
/* ============================================================== the plugin ABI entry point
*
* gemm_nt_f32's operand list is [a, b, y] and its parameters M, N, K, dtype (libref's pGemm /
* oGemm, libr4d's pGemmNt / oGemmNt). The row count comes from the operand: the band's `M` is an
* upper bound, and `N` and `K` are read as the shim's extents, exactly as libr4d's shim reads them. */
extern "C" int r3d_rad_gemm_nt_f32(const RadArgs* a, RadStream s)
{
return gemm_f32_body(a, s);
}
+441
View File
@@ -0,0 +1,441 @@
/* r3d_kda_update.hip -- kda_update: GLM's per-channel KDA recurrence over a paged f32 state cache,
* including the speculative candidate snapshots.
*
* The convolution's outputs come straight in (q, k, v, a, b); the gates are decoded here and the
* delta-rule step runs per token against one [128, 128] f32 state per head:
*
* decay = exp(lower_bound / (1 + e^-(A_log[head] * (a + dt_bias)))) beta = sigmoid(b)
* q, k l2-normalised (q's root scaled by `scale`, both by `l2_eps`)
* S *= decay u = beta * (v - S k) S += u k^T o = S q
*
* `mode` "prefill" runs the same recurrence over a sequence's tokens and commits only its final
* state; "verify" writes a state slot per candidate token, since which candidate survives is not
* known while this runs. `state_form` "anchor" is the rollback pair: the state is read at the
* anchor's slot, every candidate's factors are recorded into a scratch slot, and a second launch
* replays the accepted prefix of that record into the committed slot. The replay is a separate
* dispatch because every old factor read must finish before the next window overwrites them.
*
* q, k, a, o [tokens, heads, 128] bf16, accepted as [tokens, heads*128] too
* b [tokens, heads] bf16 (width 1, the same two forms)
* A_log [heads] f32, dt_bias [heads*128] f32
* state [slots, heads, 128, 128] f32 in/out, at the cache's own strides (a mamba page is
* padded to the attention page size, so a shape-derived stride reads every slot but
* the first at the wrong offset)
* state_idx [seqs, width] i32, width >= 2 for `anchor` (column width/2 is the scratch slot)
* cu [seqs+1] i32, absolute token offsets
* num_accepted, has_init [seqs] i32, optional
*
* The launcher checks what libr4d's checks: 13 operands, heads 1..65535 with head_k = head_v =
* 128, the five bf16 inputs in one of the two headed forms at the token count, the state a rank-4
* f32 cache of at least one slot whose strides cover it, cu rank-1 i32 of 2..65536 entries,
* state_idx rank-2 i32 with a row per sequence, A_log and dt_bias rank-1 f32 of at least heads and
* heads*128, the two optional i32 vectors one entry per sequence, mode in {prefill, verify} and
* state_form in {per_candidate, anchor} (anything else RAD_E_INVAL), anchor with a two-column
* state_idx, lower_bound finite and negative, l2_eps finite and positive, scale finite.
*
* RDNA4 -> RDNA3 (from libr4d/r4d_kda.hip, geometry unchanged). gfx1102 has the same wave32 and
* the same 64 KiB LDS as gfx1201, and this kernel tiles nothing in LDS: one wave owns four value
* rows and keeps each row's 128 state elements in four registers a lane, so a workgroup stages
* nothing and the 60 KiB bound the launcher states is vacuous by construction (a state tile moved
* into LDS is 64 KiB, one head's whole state, and would not fit a workgroup's budget). The
* reductions are libr3d's wave_sum, the same XOR butterflies in the same order as r4d_wave_sum, so
* the l2 sums, the predictions and the outputs are bit-identical; a bf16 operand widens through
* bf16_to_f32, the same shift into the high half as libr4d's bf16w_lo. Nothing here is fp8: the
* state, the recorded factors and the decay are f32, and the recurrence is bandwidth-bound, so the
* plain vectorised f32 ALU is the correct tool -- no WMMA (gfx11's is f16/i8 only) and no fp8
* matrix instruction, which gfx11 lacks. libr4d's typed R4D_EMIT dispatch becomes R3D_KLAUNCH plus
* hipGetLastError, returning RAD_E_DEVICE for a launch the driver refused, as R4D_EMIT does.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <climits>
#include <cmath>
#include <cstring>
namespace {
/* Four waves a workgroup, as in libr4d: the rows kernel grids (128 / (waves * R), heads,
* sequences) and the replay kernel, one value row a wave, (128 / waves, heads, sequences). */
constexpr uint32_t kThreads = 128;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr int kRows = 4; /* value rows a wave owns: 32 % 4 == 0 */
constexpr int kDim = 128; /* head_k and head_v, the row's compiled-in law */
/* The workgroup's dynamic stage. A wave keeps its state in registers, so there is none; the bound
* is stated because RDNA3 gives a workgroup 64 KiB of LDS and a future tile of the state (one
* head is 128*128*4 = 64 KiB) has to be checked against it here, not at the launch. */
constexpr size_t kLdsBytes = 0;
static_assert(kLdsBytes <= 60 * 1024, "a workgroup's stage must fit RDNA3's 64 KiB LDS");
struct KdaMeta {
int row[5], head[5];
long os0, os1, ss0, ss1, ss2;
long is0, is1, cs0, as0, hs0;
int tokens, slots, width, verify, anchor;
float lower, eps, scale;
};
struct KdaJob : KdaMeta {
const uint16_t* input[5];
const float *alog, *bias;
float* state;
uint16_t* out;
const int *idx, *cu, *accepted, *init;
};
/* A bf16 as ldg_u16 leaves it, widened: the code is the register's low half, so widening is a
* shift (libr4d's bf16w_lo). */
__device__ __forceinline__ float bf_lo(uint32_t w) { return bf16_to_f32((uint16_t)w); }
__device__ long factor_offset(long base, int logical, long pitch) {
return base + (logical / 128) * pitch + (logical % 128);
}
/* Separate dispatch: all old factor reads finish before the next window overwrites them. */
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void kda_replay_kernel(
float* state, const int* idx, const int* cu, const int* accepted, const int* init, KdaMeta m) {
const int lane = threadIdx.x & (kWave - 1), e = blockIdx.x * kWaves + (threadIdx.x / kWave),
head = blockIdx.y, seq = blockIdx.z;
/* A sequence without tokens this step leaves its slots as they are. */
if (cu[(long)seq * m.cs0] == cu[(long)(seq + 1) * m.cs0]) return;
const int anchor = idx[(long)seq * m.is0],
scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1];
if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch)
return;
const long fb = (long)scratch * m.ss0 + (long)head * m.ss1;
const long sb = (long)anchor * m.ss0 + (long)head * m.ss1 + (long)e * m.ss2;
if (init && !init[(long)seq * m.hs0]) {
#pragma unroll
for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = 0;
return;
}
const float count = state[fb];
const int na = accepted ? accepted[(long)seq * m.as0] : 1;
if (!(count >= 0 && count <= 32) || count != floorf(count) || na < 1 || na > 32 ||
(count > 0 && na > count))
return;
float s[4];
#pragma unroll
for (int d = 0; d < 4; ++d) s[d] = state[sb + lane + d * 32];
for (int t = 0; t < (count > 0 ? na : 0); ++t) {
const int f = 1 + t * 385;
float k[4], prediction = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int c = lane + d * 32;
k[d] = state[factor_offset(fb, f + c, m.ss2)];
s[d] *= state[factor_offset(fb, f + 256 + c, m.ss2)];
prediction += s[d] * k[d];
}
const float delta =
state[factor_offset(fb, f + 384, m.ss2)] *
(state[factor_offset(fb, f + 128 + e, m.ss2)] - wave_sum(prediction));
#pragma unroll
for (int d = 0; d < 4; ++d) s[d] += delta * k[d];
}
#pragma unroll
for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d];
}
/* R value rows a wave: the loads, norms and decay exponentials, which do not depend on the state,
* are formed once for R rows, and the rows' reductions interleave. The next token's operands are
* loaded while this one is reduced. */
template <int R>
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void kda_rows_kernel(
const uint16_t* q, const uint16_t* k, const uint16_t* v, const uint16_t* g,
const uint16_t* beta, const float* alog, const float* bias, float* state_ptr, uint16_t* out,
const int* idx, const int* cu, const int* accepted_ptr, const int* init, KdaMeta meta) {
static_assert(32 % R == 0, "the 128 value rows split evenly over the waves");
KdaJob j{};
static_cast<KdaMeta&>(j) = meta;
j.input[0] = q;
j.input[1] = k;
j.input[2] = v;
j.input[3] = g;
j.input[4] = beta;
j.alog = alog;
j.bias = bias;
j.state = state_ptr;
j.out = out;
j.idx = idx;
j.cu = cu;
j.accepted = accepted_ptr;
j.init = init;
const int lane = threadIdx.x & (kWave - 1),
e0 = (blockIdx.x * kWaves + (threadIdx.x / kWave)) * R;
const int head = blockIdx.y, seq = blockIdx.z;
const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0];
const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1;
if (begin < 0 || end <= begin || end > j.tokens || accepted < 1 ||
accepted > (j.anchor ? 32 : j.width) ||
(j.verify && end - begin > (j.anchor ? 32 : j.width)))
return;
const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1];
if (read >= j.slots) return;
uint16_t* const out_row = j.out + (long)head * j.os1 + e0;
if (read < 0) {
if (lane < R)
for (int t = begin; t < end; ++t) out_row[(long)t * j.os0 + lane] = 0;
return;
}
const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0;
const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0;
if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return;
const long fb = (long)scratch * j.ss0 + (long)head * j.ss1;
const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2;
float state[R][4];
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int d = 0; d < 4; ++d)
state[r][d] = initialized ? j.state[initial + r * j.ss2 + lane + 32 * d] : 0;
const float gain = expf(j.alog[head]);
float shift[4];
#pragma unroll
for (int d = 0; d < 4; ++d) shift[d] = j.bias[head * 128 + lane + 32 * d];
const uint16_t* const qb = j.input[0] + (long)head * j.head[0] + lane;
const uint16_t* const kb = j.input[1] + (long)head * j.head[1] + lane;
const uint16_t* const vb = j.input[2] + (long)head * j.head[2] + e0;
const uint16_t* const gb = j.input[3] + (long)head * j.head[3] + lane;
const uint16_t* const bb = j.input[4] + (long)head * j.head[4];
struct Token {
uint32_t q[4], k[4], g[4], beta, value[R];
};
auto fetch = [&](int t, Token& o) {
#pragma unroll
for (int d = 0; d < 4; ++d) {
o.q[d] = ldg_u16(qb + (long)t * j.row[0] + 32 * d);
o.k[d] = ldg_u16(kb + (long)t * j.row[1] + 32 * d);
o.g[d] = ldg_u16(gb + (long)t * j.row[3] + 32 * d);
}
o.beta = ldg_u16(bb + (long)t * j.row[4]);
#pragma unroll
for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r);
};
Token cur;
if (begin < end) fetch(begin, cur);
for (int t = begin; t < end; ++t) {
Token next;
/* The last token loads itself again rather than a row past `end`. */
fetch(t + 1 < end ? t + 1 : t, next);
float qv[4], kv[4], decay[4], sq = 0, sk = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
qv[d] = bf_lo(cur.q[d]);
kv[d] = bf_lo(cur.k[d]);
sq += qv[d] * qv[d];
sk += kv[d] * kv[d];
const float raw = bf_lo(cur.g[d]);
decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + shift[d]))));
}
const float qi = j.scale * rsqrtf(wave_sum(sq) + j.eps),
ki = rsqrtf(wave_sum(sk) + j.eps);
const float b = 1.0f / (1.0f + expf(-bf_lo(cur.beta)));
float predicted[R];
#pragma unroll
for (int r = 0; r < R; ++r) predicted[r] = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
qv[d] *= qi;
kv[d] *= ki;
#pragma unroll
for (int r = 0; r < R; ++r) {
state[r][d] *= decay[d];
predicted[r] += state[r][d] * kv[d];
}
}
float value[R];
#pragma unroll
for (int r = 0; r < R; ++r) {
predicted[r] = wave_sum(predicted[r]);
value[r] = bf_lo(cur.value[r]);
}
if (j.anchor && j.verify) {
const int f = 1 + (t - begin) * 385;
if (e0 == 0) {
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int c = lane + 32 * d;
j.state[factor_offset(fb, f + c, j.ss2)] = kv[d];
j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d];
}
if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = b;
}
if (!lane) {
#pragma unroll
for (int r = 0; r < R; ++r)
j.state[factor_offset(fb, f + 128 + e0 + r, j.ss2)] = value[r];
}
}
float result[R];
#pragma unroll
for (int r = 0; r < R; ++r) {
const float delta = b * (value[r] - predicted[r]);
result[r] = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
state[r][d] += delta * kv[d];
result[r] += state[r][d] * qv[d];
}
}
float mine = 0;
#pragma unroll
for (int r = 0; r < R; ++r) {
result[r] = wave_sum(result[r]);
if (lane == r) mine = result[r];
}
if (lane < R) out_row[(long)t * j.os0 + lane] = f32_to_bf16(mine);
if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) {
const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1];
if (write >= 0 && write < j.slots) {
const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2;
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int d = 0; d < 4; ++d)
j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d];
}
}
cur = next;
}
if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f;
}
/* A bf16 operand shaped [tokens, heads, dim] or the fused [tokens, heads*dim], read at its own row
* and head pitches. libr4d's `headed`, with an unbound descriptor (null data) refused the same way
* a missing operand is: as a shape the shim does not accept. */
template <class Pitch>
bool headed(const RadTensor* t, long tokens, long heads, long dim, Pitch* row, Pitch* head) {
if (!t || !t->data || t->dtype != RAD_BF16 || t->shape[0] != tokens ||
t->stride[0] > INT_MAX || (t->rank == 3 && t->stride[1] > INT_MAX))
return false;
if (t->rank == 3 && t->shape[1] == heads && t->shape[2] == dim && t->stride[2] == 1 &&
t->stride[1] >= dim && t->stride[0] >= heads * t->stride[1]) {
*row = t->stride[0];
*head = t->stride[1];
return true;
}
if (t->rank == 2 && t->shape[1] == heads * dim && t->stride[1] == 1 &&
t->stride[0] >= heads * dim) {
*row = t->stride[0];
*head = dim;
return true;
}
return false;
}
bool vector(const RadTensor* t, uint32_t dt, long n) {
return t && t->data && t->dtype == dt && t->rank == 1 && t->shape[0] >= n && t->stride[0] == 1;
}
int body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 13) return R3D_NO(RAD_E_INVAL);
const long H = r3d_geti_or(a, "heads", 0);
if (H < 1 || H > 65535 || r3d_geti_or(a, "head_k", 0) != kDim ||
r3d_geti_or(a, "head_v", 0) != kDim)
return R3D_NO(RAD_E_SHAPE);
KdaJob j{};
const RadTensor *state = r3d_opt(a, 7), *idx = r3d_opt(a, 8), *cu = r3d_opt(a, 9);
const long tokens = r3d_dim(r3d_opt(a, 0), 0);
/* The three null guards below stand where libr4d tests `!state.data`, `!cu.data` and
* `!idx.data`: an unbound operand is refused as the shape it is not, the same code. */
if (tokens < 1 || tokens > INT_MAX || !state || state->rank != 4 || state->dtype != RAD_F32 ||
!state->data || state->shape[0] < 1 || state->shape[0] > INT_MAX ||
state->shape[1] != H || state->shape[2] != kDim || state->shape[3] != kDim ||
state->stride[3] != 1 || state->stride[2] < kDim ||
state->stride[1] < kDim * state->stride[2] || state->stride[0] < H * state->stride[1] ||
!cu || cu->rank != 1 || cu->dtype != RAD_I32 || !cu->data || cu->shape[0] < 2 ||
cu->shape[0] > 65536 || cu->stride[0] < 1 || !idx || idx->rank != 2 ||
idx->dtype != RAD_I32 ||
!idx->data || idx->shape[0] < cu->shape[0] - 1 || idx->shape[1] < 1 ||
idx->shape[1] > INT_MAX || idx->stride[1] < 1 ||
idx->stride[0] < idx->shape[1] * idx->stride[1])
return R3D_NO(RAD_E_SHAPE);
for (int i = 0; i < 5; ++i) {
if (!headed(r3d_opt(a, i), tokens, H, i == 4 ? 1 : kDim, &j.row[i], &j.head[i]))
return R3D_NO(RAD_E_SHAPE);
j.input[i] = (const uint16_t*)r3d_p(r3d_opt(a, i));
}
const RadTensor* o = r3d_opt(a, 12);
if (!headed(o, tokens, H, kDim, &j.os0, &j.os1) || !vector(r3d_opt(a, 5), RAD_F32, H) ||
!vector(r3d_opt(a, 6), RAD_F32, H * kDim))
return R3D_NO(RAD_E_SHAPE);
const RadTensor *accepted = r3d_opt(a, 10), *init = r3d_opt(a, 11);
if ((accepted && !vector(accepted, RAD_I32, cu->shape[0] - 1)) ||
(init && !vector(init, RAD_I32, cu->shape[0] - 1)))
return R3D_NO(RAD_E_SHAPE);
const char* mode = r3d_gets(a, "mode");
if (!mode || (std::strcmp(mode, "verify") && std::strcmp(mode, "prefill")))
return R3D_NO(RAD_E_INVAL);
j.verify = !std::strcmp(mode, "verify");
const char* form = r3d_gets(a, "state_form");
j.anchor = form && !std::strcmp(form, "anchor");
if (form && !j.anchor && std::strcmp(form, "per_candidate")) return R3D_NO(RAD_E_INVAL);
if (j.anchor && idx->shape[1] < 2) return R3D_NO(RAD_E_SHAPE);
j.lower = (float)r3d_getf(a, "lower_bound", 0);
j.eps = (float)r3d_getf(a, "l2_eps", 0);
j.scale = (float)r3d_getf(a, "scale", 1);
if (!std::isfinite(j.lower) || j.lower >= 0 || !std::isfinite(j.eps) || j.eps <= 0 ||
!std::isfinite(j.scale))
return R3D_NO(RAD_E_SHAPE);
j.tokens = (int)tokens;
j.slots = (int)state->shape[0];
j.width = (int)idx->shape[1];
j.alog = (const float*)r3d_p(r3d_opt(a, 5));
j.bias = (const float*)r3d_p(r3d_opt(a, 6));
j.state = (float*)r3d_wp(state);
j.out = (uint16_t*)r3d_wp(o);
j.ss0 = state->stride[0];
j.ss1 = state->stride[1];
j.ss2 = state->stride[2];
j.idx = (const int*)idx->data;
j.is0 = idx->stride[0];
j.is1 = idx->stride[1];
j.cu = (const int*)cu->data;
j.cs0 = cu->stride[0];
if (accepted) {
j.accepted = (const int*)accepted->data;
j.as0 = accepted->stride[0];
}
if (init) {
j.init = (const int*)init->data;
j.hs0 = init->stride[0];
}
const unsigned seqs = (unsigned)(cu->shape[0] - 1);
const hipStream_t st = (hipStream_t)stream;
if (j.anchor && j.verify) {
/* One value row a wave, a workgroup's four waves covering four rows: 128 / 4 = 32
* workgroups, as libr4d grids the replay. Clear the error flag before the chevron and read
* it after: hipGetLastError reports the first error since it was last cleared, so an
* uncleared read blames this launch for an earlier one. */
(void)hipGetLastError();
R3D_KLAUNCH(kda_replay_kernel, dim3(kDim / kWaves, (unsigned)H, seqs), dim3(kThreads), st,
j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
const hipError_t re = hipGetLastError();
if (re != hipSuccess) {
if (r3d_trace_on())
std::fprintf(stderr, "[r3d] kda_update: %s on the replay: grid (%u, %u, %u)\n",
hipGetErrorName(re), (unsigned)(kDim / kWaves), (unsigned)H, seqs);
return R3D_NO(RAD_E_DEVICE);
}
}
/* The 128 value rows split over the workgroup's waves, R rows a wave: 128 / (4 waves * 4 rows)
* = 8 workgroups a (head, sequence), as libr4d grids it. */
(void)hipGetLastError();
R3D_KLAUNCH(R3D_KNAME((kda_rows_kernel<kRows>)),
dim3(kDim / (kWaves * kRows), (unsigned)H, seqs), dim3(kThreads), st, j.input[0],
j.input[1], j.input[2], j.input[3], j.input[4], j.alog, j.bias, j.state, j.out,
j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
const hipError_t ke = hipGetLastError();
if (ke != hipSuccess) {
if (r3d_trace_on())
std::fprintf(stderr, "[r3d] kda_update: %s on the rows launch: grid (%u, %u, %u) %d\n",
hipGetErrorName(ke), kDim / (kWaves * kRows), (unsigned)H, seqs, kRows);
return R3D_NO(RAD_E_DEVICE);
}
return RAD_OK;
}
} // namespace
extern "C" {
int r3d_rad_kda_update(const RadArgs* a, RadStream s) { return body(a, s); }
} // extern "C"
+278
View File
@@ -0,0 +1,278 @@
/* r3d_mla_attn_paged.hip -- mla_attn_paged: dense causal latent attention over a paged cache
* whose token row is the normed latent followed by the rotated key part (Ling-3.0's MLA).
*
* out[r, head, :] = softmax_j( scale * ( q[r, head, :] . kv[j, :512]
* + q_rope[r, head, :] . kv[j, 512:576] ) ) . kv[j, :512]
*
* over one page table per sequence, in libref's reading: sequence s owns query rows
* [cu[s], cu[s+1]), its context after this step is seqused[s], and row i of it sits at position
* seqused[s] - qlen + i and sees keys 0..position. A negative page (an unmapped block) hides its
* tokens, as attn_paged reads the table. The value is the latent; the rotary part scores only.
* With `gate`, out = bf16( bf16(out) * bf16(sigmoid(gate[r, head])) ).
*
* A wave is a (query row, head). Lane l holds latent columns 16l..16l+15 and rotary columns
* 2l, 2l+1, so a score is one wave sum: the lane's latent pair of the 512-wide dot plus its rope
* pair, wave_sum, then scale. The running softmax is online (a rescaling max/den update per
* token), exactly the libr4d kernel's: a row's bytes do not depend on the batch it is in.
*
* A short batch splits its history over the z axis, one (value[512], max, den) f32 partial per
* (row, head, split) in the scratch arena, and merge_paged joins the partials against the global
* maximum before the single narrowing. The split count is a function of the head count alone
* (paged_splits), not of the launch's rows, for the same reason the libr4d kernel states it: a
* speculative verify scores the k + 1 rows of a sequence in one launch, and greedy output equals
* the run without speculation only if each row gives the single-row decode at its position bit
* for bit.
*
* Operands: q [M, heads, 512] bf16, q_rope [M, heads, 64] bf16, kv [pages, 1, bs, >= 576] bf16,
* block_table [seqs, blocks] i32, seqused [seqs] i32, cu_seqlens [seqs + 1] i32, gate [M, >=
* heads] bf16 (optional), out [M, heads, 512] bf16. A 2-D [M, heads*width] plane is viewed as
* 3-D, as libr4d.
*
* The launcher (r3d_rad_mla_attn_paged) checks: the dtypes above; latent_dim 512, rope_dim 64;
* heads 1..64; block_size 1..256; scale finite and positive; M 1..65535; the shapes, strides and
* pitches as libr4d's (last axes contiguous, row pitches at least the dense ones, the table at
* least as wide as seqused's rows, cu [seqs + 1] contiguous); RAD_E_INVAL, RAD_E_DTYPE,
* RAD_E_SHAPE. A scratch arena too small for the split lowers the split, down to 1, which needs
* none -- the band is never refused for lack of scratch.
*
* RDNA4 -> RDNA3: the kernel is a bandwidth-bound GEMV shape, so it runs plain vectorised f32
* with the library's bf16 codecs -- no WMMA (RDNA3's wave matrix is f16/i8 only) and no fp8. The
* wave sum is wave_sum, the same butterfly order as libr4d's, so a row's bytes are
* bit-identical to the libr4d kernel. The aligned 16-byte latent loads keep their alignment
* guard: a misaligned 16-byte load returns garbage on this hardware, and the scalar path takes
* the misaligned row.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
#include <cmath>
#include <climits>
#include <cstring>
namespace {
constexpr int D = 512; /* the latent width */
constexpr int RD = 64; /* the rotary width */
constexpr int PART = D + 2; /* a partial: value[512], max, den */
/* The rows the scratch serves at full split: a verify at depth 31. */
constexpr long kPagedRows = 32;
struct PagedMeta {
long qr, qh, rr, rh, kp, kt, bp, bc, orr, oh, gr;
int rows, heads, seqs, blocks, bs, pages, splits;
float scale;
};
int paged_splits(long heads) { return (int)std::min(16l, (256 + heads - 1) / heads); }
int64_t paged_scratch_bytes(long rows, long heads) {
return std::min(rows, kPagedRows) * heads * paged_splits(heads) * PART * 4;
}
/* Which sequence owns dense query row `r`, walking the descriptor once per wave. */
__device__ __forceinline__ int paged_seq(const int* cu, int seqs, int r) {
int s = 0;
while (s + 1 < seqs && cu[s + 1] <= r) ++s;
return s;
}
/* Sixteen bf16 elements as f32: two 16-byte loads when the row is aligned, element-wise when it
* is not (a misaligned 16-byte load returns garbage on this hardware). The 16-byte staging goes
* through r3d_u32x4, the ext_vector_type the library keeps in registers (r3d_common.h). */
__device__ __forceinline__ void load_latent(const uint16_t* p, float (&v)[16]) {
if (!((uintptr_t)p & 15)) {
const r3d_u32x4 a =
*(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)p;
const r3d_u32x4 b =
*(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)(p + 8);
const uint32_t packed[8] = { a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w };
#pragma unroll
for (int j = 0; j < 16; ++j)
v[j] = bf16_to_f32((uint16_t)(packed[j / 2] >> (16 * (j & 1))));
} else {
#pragma unroll
for (int j = 0; j < 16; ++j) v[j] = bf16_to_f32((uint16_t)ldg_u16(p + j));
}
}
/* The narrowed output, with the optional head gate: bf16(bf16(out) * bf16(sigmoid(logit))). */
__device__ __forceinline__ void paged_store(uint16_t* out, const uint16_t* gate, const PagedMeta& m,
int r, int head, int lane, const float (&value)[16],
float den) {
float g = 1.0f;
if (gate)
g = bf16_to_f32(f32_to_bf16(1.0f / (1.0f + expf(-bf16_to_f32((uint16_t)ldg_u16(
gate + (long)r * m.gr + head))))));
#pragma unroll
for (int j = 0; j < 16; ++j) {
float v = den > 0 ? value[j] / den : 0;
if (gate) v = bf16_to_f32(f32_to_bf16(v)) * g;
out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] = f32_to_bf16(v);
}
}
__global__ __launch_bounds__(128) R3D_WAVES(4)
void attend_paged(const uint16_t* __restrict__ q, const uint16_t* __restrict__ qrot,
const uint16_t* __restrict__ kv, const int* __restrict__ bt,
const int* __restrict__ used, const int* __restrict__ cu,
const uint16_t* __restrict__ gate, uint16_t* __restrict__ out,
float* __restrict__ scratch, PagedMeta m) {
const int lane = (int)threadIdx.x & 31, head = (int)blockIdx.y * 4 + ((int)threadIdx.x >> 5),
r = (int)blockIdx.x, split = (int)blockIdx.z;
if (head >= m.heads) return;
const int s = paged_seq(cu, m.seqs, r);
const int qlen = cu[s + 1] - cu[s], i = r - cu[s];
const int live = std::min(std::max(used[s] - qlen + i + 1, 0), m.blocks * m.bs);
const int begin = (int)((long)live * split / m.splits),
end = (int)((long)live * (split + 1) / m.splits);
float query[16], value[16] = {};
load_latent(q + (long)r * m.qr + (long)head * m.qh + lane * 16, query);
const uint16_t* const qp = qrot + (long)r * m.rr + (long)head * m.rh + lane * 2;
const float rq0 = bf16_to_f32((uint16_t)ldg_u16(qp)),
rq1 = bf16_to_f32((uint16_t)ldg_u16(qp + 1));
float max_score = -INFINITY, den = 0;
for (int token = begin; token < end; ++token) {
const int page = bt[(long)s * m.bp + (token / m.bs) * m.bc];
if (page < 0 || page >= m.pages) continue;
const uint16_t* const row = kv + (long)page * m.kp + (token % m.bs) * m.kt;
float key[16];
load_latent(row + lane * 16, key);
float score = rq0 * bf16_to_f32((uint16_t)ldg_u16(row + D + lane * 2)) +
rq1 * bf16_to_f32((uint16_t)ldg_u16(row + D + lane * 2 + 1));
#pragma unroll
for (int j = 0; j < 16; ++j) score += query[j] * key[j];
score = wave_sum(score) * m.scale;
const bool higher = score > max_score;
const float weight = expf(higher ? max_score - score : score - max_score);
if (higher) {
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] = value[j] * weight + key[j];
den = den * weight + 1;
max_score = score;
} else {
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] += key[j] * weight;
den += weight;
}
}
if (m.splits == 1) {
paged_store(out, gate, m, r, head, lane, value, den);
} else {
float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART;
#pragma unroll
for (int j = 0; j < 16; ++j) dst[lane * 16 + j] = value[j];
if (!lane) {
dst[D] = max_score;
dst[D + 1] = den;
}
}
}
__global__ __launch_bounds__(128) R3D_WAVES(4)
void merge_paged(const float* __restrict__ scratch, const uint16_t* __restrict__ gate,
uint16_t* __restrict__ out, PagedMeta m) {
const int lane = (int)threadIdx.x & 31, head = (int)blockIdx.y * 4 + ((int)threadIdx.x >> 5),
r = (int)blockIdx.x;
if (head >= m.heads) return;
const float* src = scratch + ((long)r * m.heads + head) * m.splits * PART;
float max_score = -INFINITY;
for (int s = 0; s < m.splits; ++s)
if (src[s * PART + D + 1] > 0) max_score = fmaxf(max_score, src[s * PART + D]);
float value[16] = {}, den = 0;
for (int s = 0; s < m.splits; ++s) {
const float part_den = src[s * PART + D + 1];
if (!(part_den > 0)) continue;
const float w = expf(src[s * PART + D] - max_score);
den += part_den * w;
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] += src[s * PART + lane * 16 + j] * w;
}
paged_store(out, gate, m, r, head, lane, value, den);
}
int paged_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 8) return R3D_NO(RAD_E_INVAL);
RadTensor q = a->t[0], qr = a->t[1], o = a->t[7];
const RadTensor& kv = a->t[2], &bt = a->t[3], &su = a->t[4], &cu = a->t[5];
const RadTensor* gate = r3d_opt(a, 6);
const long heads = r3d_geti_or(a, "heads", 0), bs = r3d_geti_or(a, "block_size", 0);
const float scale = (float)r3d_getf(a, "scale", 0);
auto heads_view = [&](RadTensor& t, long width) {
if (heads > 0 && t.rank == 2 && t.shape[1] == heads * width) {
t.rank = 3;
t.shape[1] = heads;
t.shape[2] = width;
t.stride[2] = t.stride[1];
t.stride[1] *= width;
}
};
heads_view(q, D);
heads_view(qr, RD);
heads_view(o, D);
if (q.dtype != RAD_BF16 || qr.dtype != RAD_BF16 || kv.dtype != RAD_BF16 ||
o.dtype != RAD_BF16 || bt.dtype != RAD_I32 || su.dtype != RAD_I32 || cu.dtype != RAD_I32 ||
(gate && gate->dtype != RAD_BF16))
return R3D_NO(RAD_E_DTYPE);
if (!q.data || !qr.data || !kv.data || !bt.data || !su.data || !cu.data || !o.data)
return R3D_NO(RAD_E_INVAL);
if (r3d_geti_or(a, "latent_dim", 0) != D || r3d_geti_or(a, "rope_dim", 0) != RD || heads < 1 ||
heads > 64 || bs < 1 || bs > 256 || !std::isfinite(scale) || scale <= 0 || q.rank != 3 ||
q.shape[0] < 1 || q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D ||
q.stride[2] != 1 || q.stride[1] < D || q.stride[0] < heads * q.stride[1] || qr.rank != 3 ||
qr.shape[0] != q.shape[0] || qr.shape[1] != heads || qr.shape[2] != RD ||
qr.stride[2] != 1 || qr.stride[1] < RD || qr.stride[0] < heads * qr.stride[1] ||
kv.rank != 4 || kv.shape[0] < 1 || kv.shape[0] > INT_MAX || kv.shape[1] != 1 ||
kv.shape[2] != bs || kv.shape[3] < D + RD || kv.stride[3] != 1 || kv.stride[2] < D + RD ||
kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 || bt.shape[1] < 1 ||
bt.shape[1] > INT_MAX / bs || bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] ||
su.rank != 1 || su.shape[0] < 1 || bt.shape[0] < su.shape[0] || !r3d_contig(&su) ||
!r3d_contig(&cu) || r3d_numel(&cu) != su.shape[0] + 1 || o.rank != 3 ||
o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 ||
o.stride[1] < D || o.stride[0] < heads * o.stride[1] ||
(gate && (gate->rank != 2 || gate->shape[0] != q.shape[0] || gate->shape[1] < heads ||
gate->stride[1] != 1)))
return R3D_NO(RAD_E_SHAPE);
/* The split comes from the head count alone (paged_splits). Only a batch whose partials the
* scratch cannot hold takes fewer, as many as fit. */
const long rows = q.shape[0], slots = a->scratch ? (long)(a->scratch_bytes / (PART * 4)) : 0;
int splits = paged_splits(heads);
if (rows * heads * splits > slots) splits = (int)std::max(1l, slots / (rows * heads));
const PagedMeta m{ q.stride[0], q.stride[1], qr.stride[0], qr.stride[1],
kv.stride[0], kv.stride[2], bt.stride[0], bt.stride[1],
o.stride[0], o.stride[1], gate ? (long)gate->stride[0] : 0L,
(int)q.shape[0], (int)heads, (int)su.shape[0], (int)bt.shape[1],
(int)bs, (int)kv.shape[0], splits, scale };
const uint16_t* gp = gate ? (const uint16_t*)gate->data : nullptr;
(void)hipGetLastError();
R3D_KLAUNCH(attend_paged, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128),
(hipStream_t)stream, (const uint16_t*)q.data, (const uint16_t*)qr.data,
(const uint16_t*)kv.data, (const int*)bt.data, (const int*)su.data,
(const int*)cu.data, gp, (uint16_t*)o.data, (float*)a->scratch, m);
hipError_t e = hipGetLastError();
if (e != hipSuccess) return R3D_NO(RAD_E_DEVICE);
if (splits > 1) {
(void)hipGetLastError();
R3D_KLAUNCH(merge_paged, dim3(m.rows, (m.heads + 3) / 4), dim3(128), (hipStream_t)stream,
(const float*)a->scratch, gp, (uint16_t*)o.data, m);
e = hipGetLastError();
if (e != hipSuccess) return R3D_NO(RAD_E_DEVICE);
}
return RAD_OK;
}
} // namespace
extern "C" int r3d_rad_mla_attn_paged(const RadArgs* a, RadStream s) {
return paged_body(a, s);
}
/* Sized at the band's top row count, at most kPagedRows (paged_splits). */
extern "C" int64_t r3d_rad_mla_attn_paged_scratch(const RadArgs* a) {
const long heads = r3d_geti_or(a, "heads", 0), rows = r3d_geti_or(a, "M", kPagedRows);
if (heads < 1 || heads > 64 || rows < 1) return R3D_NO(RAD_E_SHAPE);
return paged_scratch_bytes(rows, heads);
}
+175
View File
@@ -0,0 +1,175 @@
/* r3d_mla_project.hip -- mla_project: the per-head absorbed-MLA projections.
*
* An absorbed MLA model keeps one 512-wide latent per token and folds the per-head K/V
* projections into two matrices:
*
* mode "absorb" y[M, heads, 512] = x[M, heads, head_dim] @ w[head, 0, :, :]^T per head
* mode "expand" y[M, heads, head_dim] = x[M, heads, 512] @ w[head, 1, :, :]^T per head
*
* where w is the shared [heads, 2 * head_dim, 512] BF16 matrix (the K half, then the V half, of
* each head's rows) and head_dim is 128 or 256. f32 arithmetic, one bf16 rounding at the store,
* as libref.
*
* Absorption streams adjacent latent columns: one thread a column, R rows a thread, and each
* weight element is loaded once for the R rows it serves. Expansion reduces a contiguous weight
* row: one wave a column, R rows a wave, each lane its share of the 512-wide sum in ascending j,
* then one wave sum. Every row's sum runs over j in the same order whatever R is, so a row's
* bytes do not depend on the batch it is in. A tail group past the last row reads that row again
* and stores nothing for it.
*
* Bandwidth-bound GEMV shapes: plain vectorised f32 is the idiomatic RDNA3 path here, as in the
* skinny GEMM rows. No WMMA (RDNA3's wave matrix is f16/i8 only and adds a fragment layout for no
* throughput at these shapes) and no fp8.
*
* The launcher (r3d_rad_mla_project) checks: bf16 in, weights and out; heads 1..64; head_dim
* 128 or 256; latent_dim 512; x [M, heads, head_dim|512], w [heads, 2*head_dim, 512], y
* [M, heads, 512|head_dim], M 1..65535, last axes contiguous and row pitches at least the dense
* ones (a 2-D [M, heads*width] plane is viewed as 3-D); RAD_E_INVAL, RAD_E_DTYPE, RAD_E_SHAPE.
*
* RDNA4 -> RDNA3: the kernels use only bf16 loads, f32 FMAs and the wave-sum butterfly
* (r3d_xor_sum<32>, the same order as libr4d's, so bit-identical). The element loads are the
* library's ldg_u16 (a whole register, no register-half wait); everything else is unchanged.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace {
struct ProjectMeta {
long xr, xh, wp, yr, yh;
int rows, heads;
};
/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. R rows
* a thread (absorb) or a wave (expand): each weight element is loaded once for R rows. Every row's
* sum runs over j in the same order whatever R is (expand: each lane's share in ascending j, then
* r3d_xor_sum<32>), so a row's bytes do not depend on the batch it is in. A tail group past the
* last row reads that row again and stores nothing for it. */
template <int R, int HD>
__global__ __launch_bounds__(128) R3D_WAVES(4)
void project_absorb_rows(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
uint16_t* __restrict__ y, ProjectMeta m) {
const int col = (int)blockIdx.x * 128 + (int)threadIdx.x, head = (int)blockIdx.y,
r0 = (int)blockIdx.z * R;
if (col >= 512) return;
const uint16_t* xr[R];
#pragma unroll
for (int r = 0; r < R; ++r)
xr[r] = x + (long)std::min(r0 + r, m.rows - 1) * m.xr + (long)head * m.xh;
float sum[R];
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = 0;
for (int j = 0; j < HD; ++j) {
const float wv = bf16_to_f32((uint16_t)ldg_u16(w + ((long)head * 2 * HD + j) * m.wp + col));
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32((uint16_t)ldg_u16(xr[r] + j)), wv, sum[r]);
}
#pragma unroll
for (int r = 0; r < R; ++r)
if (r0 + r < m.rows) y[(long)(r0 + r) * m.yr + (long)head * m.yh + col] = f32_to_bf16(sum[r]);
}
template <int R, int HD>
__global__ __launch_bounds__(128) R3D_WAVES(4)
void project_expand_rows(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
uint16_t* __restrict__ y, ProjectMeta m) {
const int lane = (int)threadIdx.x & 31, col = (int)blockIdx.x * 4 + ((int)threadIdx.x >> 5),
head = (int)blockIdx.y, r0 = (int)blockIdx.z * R;
const uint16_t* xr[R];
#pragma unroll
for (int r = 0; r < R; ++r)
xr[r] = x + (long)std::min(r0 + r, m.rows - 1) * m.xr + (long)head * m.xh;
const uint16_t* const wr = w + ((long)head * 2 * HD + HD + col) * m.wp;
float sum[R];
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = 0;
for (int j = lane; j < 512; j += 32) {
const float wv = bf16_to_f32((uint16_t)ldg_u16(wr + j));
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32((uint16_t)ldg_u16(xr[r] + j)), wv, sum[r]);
}
float mine = 0;
#pragma unroll
for (int r = 0; r < R; ++r) {
sum[r] = r3d_xor_sum<32>(sum[r]);
if (lane == r) mine = sum[r];
}
if (lane < R && r0 + lane < m.rows)
y[(long)(r0 + lane) * m.yr + (long)head * m.yh + col] = f32_to_bf16(mine);
}
int project_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
RadTensor x = a->t[0], y = a->t[2];
const RadTensor& w = a->t[1];
const char* mode = r3d_gets(a, "mode");
const bool absorb = mode && !std::strcmp(mode, "absorb"),
expand = mode && !std::strcmp(mode, "expand");
const long h = r3d_geti_or(a, "heads", 0), hd = r3d_geti_or(a, "head_dim", 0);
auto heads_view = [&](RadTensor& t, long width) {
if (h > 0 && t.rank == 2 && t.shape[1] == h * width) {
t.rank = 3;
t.shape[1] = h;
t.shape[2] = width;
t.stride[2] = t.stride[1];
t.stride[1] *= width;
}
};
heads_view(x, absorb ? hd : 512);
heads_view(y, absorb ? 512 : hd);
if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16)
return R3D_NO(RAD_E_DTYPE);
if (!x.data || !w.data || !y.data) return R3D_NO(RAD_E_INVAL);
if ((!absorb && !expand) || h < 1 || h > 64 || (hd != 128 && hd != 256) ||
r3d_geti_or(a, "latent_dim", 0) != 512 || x.rank != 3 || w.rank != 2 || y.rank != 3 ||
x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != h ||
x.shape[2] != (absorb ? hd : 512) || w.shape[0] != h * 2 * hd || w.shape[1] != 512 ||
y.shape[0] != x.shape[0] || y.shape[1] != h || y.shape[2] != (absorb ? 512 : hd) ||
x.stride[2] != 1 || w.stride[1] != 1 || y.stride[2] != 1 || x.stride[1] < x.shape[2] ||
x.stride[0] < h * x.stride[1] || w.stride[0] < 512 || y.stride[1] < y.shape[2] ||
y.stride[0] < h * y.stride[1])
return R3D_NO(RAD_E_SHAPE);
const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0],
y.stride[1], (int)x.shape[0], (int)h };
const uint16_t* xp = (const uint16_t*)x.data;
const uint16_t* wp = (const uint16_t*)w.data;
uint16_t* yp = (uint16_t*)y.data;
/* The largest of 8, 4, 2 and 1 rows a group that the batch fills. */
const int R = m.rows >= 8 ? 8 : m.rows >= 4 ? 4 : m.rows >= 2 ? 2 : 1;
#define MLA_PROJECT_HD(RR, HD) \
do { \
const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \
(void)hipGetLastError(); \
if (absorb) \
R3D_KLAUNCH((project_absorb_rows<RR, HD>), dim3(4, h, groups), dim3(128), \
(hipStream_t)stream, xp, wp, yp, m); \
else \
R3D_KLAUNCH((project_expand_rows<RR, HD>), dim3(HD / 4, h, groups), dim3(128), \
(hipStream_t)stream, xp, wp, yp, m); \
const hipError_t e = hipGetLastError(); \
return e == hipSuccess ? RAD_OK : R3D_NO(RAD_E_DEVICE); \
} while (0)
#define MLA_PROJECT_ROWS(RR) \
do { \
if (hd == 128) MLA_PROJECT_HD(RR, 128); \
MLA_PROJECT_HD(RR, 256); \
} while (0)
if (R == 8) MLA_PROJECT_ROWS(8);
if (R == 4) MLA_PROJECT_ROWS(4);
if (R == 2) MLA_PROJECT_ROWS(2);
MLA_PROJECT_ROWS(1);
#undef MLA_PROJECT_ROWS
#undef MLA_PROJECT_HD
}
} // namespace
extern "C" int r3d_rad_mla_project(const RadArgs* a, RadStream s) {
return project_body(a, s);
}
+4 -1
View File
@@ -125,7 +125,10 @@ int r3d_rad_moe_gather(const RadArgs* a, RadStream s)
const uint32_t ew_ld = (uint32_t)ew->stride[0];
const uint32_t y_ld = (uint32_t)y->stride[0];
const uint32_t T = (uint32_t)r3d_numel(sorted);
if (T < M * top_k) return R3D_NO(RAD_E_SHAPE);
/* M is the batch capacity, not the token count: the engine pads the batch, and the slot
* table covers only the tokens present, so it may be shorter than M * top_k (the kernel
* zeroes the padding rows). It may never be longer. */
if (T > (uint64_t)M * top_k) return R3D_NO(RAD_E_SHAPE);
// The optional shared arm (operands 3 and 4, present together).
const RadTensor* sh = r3d_opt(a, 3), *sg = r3d_opt(a, 4);
+271
View File
@@ -0,0 +1,271 @@
/* r3d_ple_conv.hip -- ple_conv: Per-Layer Embedding's dilated depthwise convolution, its silu, and
* the residual add that finishes the layer.
*
* y[t][c] = resid[t][c] + silu( sum_j w[c][j] * x[t - (width-1-j)*dilation][c] )
*
* x [M, n] bf16, w [n, width] bf16, conv_state [n_slots, n, state_len] bf16, cu [N+1] i32,
* resid [M, n] bf16 (optional), cache_idx [N] i32 (optional), has_init [N] i32 (optional),
* num_accepted [N] i32 (optional), y [M, n] bf16 out.
*
* libref/ref_ple.cpp is the oracle and docs/OPS.md the contract. The taps are `dilation` apart, so
* at width 4 and dilation 3 they sit 9, 6, 3 and 0 timesteps back and a sequence carries a history
* of (width-1)*dilation = 9, not 3. An off-by-one in a convolution cache yields fluent output from
* a slightly wrong context, so the indexing mirrors ref's line for line: state slot `i` holds
* relative position `i - hist`, a read at `src < 0` becomes `cs[slot][c][off + src + hist]`, and
* `has_init` 0 means that window is zeros, not the slot's stale contents.
*
* One thread per channel: a depthwise convolution never mixes channels, so only time must stay
* together. A thread walks a tile of tokens; consecutive threads own consecutive channels, so a
* wave loads one contiguous 64-byte slice of a token row and a workgroup a contiguous 512-byte one.
*
* The grid is (channel blocks, token tiles, sequences). Token tiles are counted from the batch's
* total token count, an upper bound on any one sequence's; a short sequence's extra blocks find
* `t0 >= slen` and return. A per-sequence count would mean reading `cu` on the host.
*
* The taps are read from memory, not kept in a shift register: the window would need `hist + 1`
* registers indexed by a runtime value, which compiles to a select tree, and a compile-time window
* would need a specialisation per (width, dilation). The re-reads hit a tile working set of
* (BT + hist) * 512 bytes (21 KB at BT 32), and the op is bound by the three arrays it must touch
* anyway. Nothing is staged in LDS: there is no reduction here, so the launcher's 60 KiB stage
* check has no stage to size, and no wave barrier is needed for the write-back (see below).
*
* The window write-back is in the same launch; see the note at the end of the kernel. It relies
* on `hist < kPcBT`, asserted below.
*
* RDNA3 notes. The kernel is the libr4d one (r4d_ple_conv_bf16.hip) with three adaptations:
* every 16-bit read goes through ldg_u16, so it is a global load through the device address space
* (measured on the box: the two builds emit the same 50 global_load_u16 / 50 global_load_d16_b16 /
* 46 global_load_d16_hi_b16 / 2 global_load_b32, the d16 pairs being the write-back packing two
* bf16 into one register); the kernel is annotated R3D_WAVES(16), the wave-slot cap of a gfx11
* SIMD, not R3D_WAVES(8) for its own eight waves -- the op is bandwidth-bound and wants the most
* resident waves it can get, and the 8 annotation costs registers (113 VGPRs against 28 at 16,
* both spill-free, 28 being what the RDNA4 build of the same source allocates); and an optional
* operand whose descriptor is present but unbound is read as absent (r3d_has), which is how the
* kernel treats it. The compute is plain f32: the op moves bytes, and RDNA3 has no bf16 dot2 and
* nothing here is a 16x16x16 tile, so the wave matrix would add a fragment layout for no
* throughput (r3d_common.h).
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
#include <cstdint>
namespace {
enum {
kPcThreads = 256,
kPcWaves = kPcThreads / kWave, /* 8 waves of 32 a workgroup */
kPcWpS = 16, /* waves a SIMD: gfx11's wave32 slot count, and the register budget (64) */
kPcBT = 32, /* tokens a thread walks; the tile's working set is (BT + hist) * 512 B */
kPcMaxW = 8, /* taps held in registers, so the weight loop unrolls to a static bound */
kPcMaxHist = 16, /* (width-1)*dilation, the write-back's register window; see cPleConv */
};
/* The write-back lives in tile 0, which is sound only while the deepest tap is inside the first
* tile. At hist >= BT a second block would read history and the write-back would overwrite bytes
* it is still reading, silently corrupting a sequence's first tokens. The constraint table caps
* hist <= 16; the tile size is the other half of that bound. */
static_assert(kPcMaxHist < kPcBT, "the conv history must fit inside tile 0 for the fused write-back");
/* A bf16 of global memory widened in one instruction; see ldg_u16 in r3d_common.h. */
__device__ __forceinline__ float pc_ld(const uint16_t* p, size_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
/* expf rather than __expf: the op is bound by memory, not the transcendental, and the oracle uses
* std::exp (ref_common.h's act_silu). The instruction-bound GDN conv makes the opposite trade. */
__device__ __forceinline__ float pc_silu(float z) { return z / (1.0f + expf(-z)); }
/* SILU is ple_conv's activation; causal_conv1d (LFM2's short convolution) is the same window with
* no activation, no residual and dilation one, and shares this kernel. */
template <bool SILU>
__global__ __launch_bounds__(kPcThreads) R3D_WAVES(kPcWpS) void r3d_ple_conv_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
uint16_t* __restrict__ cs, const int32_t* __restrict__ cu,
const uint16_t* __restrict__ resid, const int32_t* __restrict__ sidx,
const int32_t* __restrict__ hini, const int32_t* __restrict__ nacc,
uint16_t* __restrict__ y, uint32_t n, uint32_t wid, uint32_t dil, uint32_t hist,
uint32_t xld, uint32_t rld, uint32_t yld, uint32_t wld,
long long cs_slot, long long cs_ch, long long cs_tok, long long state_len) {
const uint32_t c = blockIdx.x * kPcThreads + threadIdx.x;
if (c >= n) return;
const uint32_t s = blockIdx.z;
const int32_t bos = cu[s];
const int32_t slen = cu[s + 1] - bos;
if (slen <= 0) return;
const int32_t t0 = (int32_t)(blockIdx.y * kPcBT);
if (t0 >= slen) return;
const int32_t t1 = min(t0 + (int32_t)kPcBT, slen);
const int32_t slot = sidx ? sidx[s] : (int32_t)s;
if (slot < 0) return;
/* A cold slot's window is zeros: a fresh sequence on a recycled slot would otherwise convolve
* the previous sequence's tail into its first `hist` tokens. */
const bool warm = cs && (!hini || hini[s] != 0);
const long long off = nacc ? (long long)nacc[s] - 1 : 0;
/* This channel's taps, read once for the whole tile. */
float wt[kPcMaxW];
#pragma unroll
for (uint32_t j = 0; j < kPcMaxW; ++j) wt[j] = j < wid ? pc_ld(w, (size_t)c * wld + j) : 0.0f;
const uint16_t* __restrict__ xc = x + (size_t)bos * xld + c;
const uint16_t* __restrict__ rc = resid ? resid + (size_t)bos * rld + c : nullptr;
uint16_t* __restrict__ dst = cs ? cs + (size_t)slot * cs_slot + (size_t)c * cs_ch : nullptr;
const uint16_t* __restrict__ hc = warm ? dst + off * cs_tok : nullptr;
uint16_t* __restrict__ yc = y + (size_t)bos * yld + c;
for (int32_t t = t0; t < t1; ++t) {
float acc = 0.0f;
#pragma unroll
for (uint32_t j = 0; j < kPcMaxW; ++j) {
if (j < wid) {
const int32_t src = t - (int32_t)hist + (int32_t)(j * dil);
const float v = src >= 0 ? pc_ld(xc, (size_t)src * xld)
: (hc ? pc_ld(hc, (size_t)(src + (int32_t)hist) * cs_tok)
: 0.0f);
acc += v * wt[j];
}
}
const float r = rc ? pc_ld(rc, (size_t)t * rld) : 0.0f;
yc[(size_t)t * yld] = f32_to_bf16(r + (SILU ? pc_silu(acc) : acc));
}
/* The window this step leaves, in the same launch with no barrier. History is read only where
* `t - hist + j*dilation < 0`, i.e. by tokens below `hist` (9, against a 32-token tile), so
* tile 0 is the only block touching state[slot][c]. One thread owns the whole channel there, so
* its reads precede its writes in program order. At decode the op's cost is the dispatch itself
* (flat from M=1 to M=8), so a second launch would roughly double it.
*
* The layout is libref/ref_ple.cpp's, chosen by `num_accepted`. Present, this is a decode step
* whose drafts a verify may reject: the history read shifts down by one and every input of the
* step follows it, slot i holding position i + 1 of (window read ++ step), so a next step that
* kept k tokens reads at k - 1. Absent, every token commits and the last `hist` inputs land at
* offset zero. The two agree at one token. Slots past `state_len` are not written; the manager
* sizes the window hist + n_spec, enough for a step of 1 + n_spec tokens.
*
* Values are copied as bf16 bits, the same tensor's bytes on both sides. The step's rows come
* from the read-only `x`, so other tiles reading them is no hazard. Every history value is
* loaded before the first store. */
if (!dst || blockIdx.y != 0) return;
uint16_t keep[kPcMaxHist];
if (nacc) {
#pragma unroll
for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i)
if (i + 1 < hist)
keep[i] = hc ? (uint16_t)ldg_u16(hc + (size_t)(i + 1) * cs_tok) : (uint16_t)0;
#pragma unroll
for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i)
if (i + 1 < hist) dst[(size_t)i * cs_tok] = keep[i];
for (int32_t t = 0; t < slen && (long long)hist - 1 + t < state_len; ++t)
dst[(size_t)(hist - 1 + (uint32_t)t) * cs_tok] = (uint16_t)ldg_u16(xc + (size_t)t * xld);
return;
}
#pragma unroll
for (uint32_t i = 0; i < kPcMaxHist; ++i) {
if (i < hist) {
const int32_t src = slen - (int32_t)hist + (int32_t)i;
keep[i] = src >= 0 ? (uint16_t)ldg_u16(xc + (size_t)src * xld)
: (hc ? (uint16_t)ldg_u16(hc + (size_t)(src + (int32_t)hist) * cs_tok)
: (uint16_t)0);
}
}
#pragma unroll
for (uint32_t i = 0; i < kPcMaxHist; ++i)
if (i < hist) dst[(size_t)i * cs_tok] = keep[i];
}
/* The operand slots, in ple_conv's schema order. causal_conv1d is this kernel's SILU=false arm
* with `resid` out of the schema and `dilation` fixed at one; its entry point and operand table
* are not in this unit, so only ple_conv's positions are named here. */
enum { PC_X = 0, PC_W, PC_CS, PC_CU, PC_RESID, PC_CIDX, PC_HINIT, PC_NACC, PC_Y };
/* The launcher: the shape checks libr4d's r4d_rad_ple_conv makes, in the same order with the same
* refusals. `silu` selects the activation. */
int r3d_conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, const RadTensor* w,
const RadTensor* cs, const RadTensor* cu, const RadTensor* resid,
const RadTensor* cidx, const RadTensor* hini, const RadTensor* nacc,
const RadTensor* y) {
if (!r3d_p(x) || !r3d_p(w) || !r3d_p(cu) || !r3d_wp(y)) return R3D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || w->dtype != RAD_BF16 || y->dtype != RAD_BF16)
return R3D_NO(RAD_E_DTYPE);
/* An optional operand the engine bound to nothing is absent, so it is tested with r3d_has:
* a descriptor with a null `data` carries the schema's dtype, not a tensor's. */
if (r3d_has(resid) && resid->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
if (r3d_has(cs) && cs->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
if (cu->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE);
if (r3d_has(cidx) && cidx->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE);
/* `has_init` must be int32 (RadBatch::ctx_lens, like every derived buffer): read as bytes, a
* ctx_len of 512 has a zero low byte and the history would be dropped. Anything else is
* refused. */
if (r3d_has(hini) && hini->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE);
if (r3d_has(nacc) && nacc->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE);
const long long n = r3d_geti_or(a, "n", 0);
const long long wid = r3d_geti_or(a, "width", 0);
const long long dil = r3d_geti_or(a, "dilation", 1);
if (n <= 0 || wid <= 0 || dil <= 0) return R3D_NO(RAD_E_SHAPE);
if (wid > kPcMaxW) return R3D_NO(RAD_E_UNSUPPORTED);
const long long hist = (wid - 1) * dil;
if (hist > kPcMaxHist) return R3D_NO(RAD_E_UNSUPPORTED);
long long T = 0, ty = 0, tr = 0, wrows = 0;
const long long xld = r3d_rows_pitch(x, n, &T);
const long long yld = r3d_rows_pitch(y, n, &ty);
const bool have_r = r3d_has(resid);
const long long rld = have_r ? r3d_rows_pitch(resid, n, &tr) : 0;
const long long wld = r3d_rows_pitch(w, wid, &wrows);
if (xld < 0 || yld < 0 || wld < 0 || (have_r && rld < 0)) return R3D_NO(RAD_E_STRIDE);
/* The row count comes from the operands, and they must agree: `M` is ranged, so the arg holds
* the band's upper bound and a grid sized by it would run off the arena. */
if (T <= 0 || ty != T || (have_r && tr != T)) return R3D_NO(RAD_E_SHAPE);
if (wrows < n) return R3D_NO(RAD_E_SHAPE);
const long long N = r3d_numel(cu) - 1;
if (N <= 0) return R3D_NO(RAD_E_SHAPE);
if (!r3d_contig(cu)) return R3D_NO(RAD_E_STRIDE);
/* [n_slots, n, state_len]. A state too shallow for the deepest tap is refused here; the
* rollback offset cannot be checked without reading `num_accepted` on the host, which is why
* the manager sizes the window hist + n_spec. */
long long cs_slot = 0, cs_ch = 0, cs_tok = 0, state_len = 0;
const bool have_cs = r3d_has(cs) && hist > 0;
if (have_cs) {
if (cs->rank != 3) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(cs, 1) < n || r3d_dim(cs, 2) < hist) return R3D_NO(RAD_E_SHAPE);
cs_slot = r3d_stride(cs, 0);
cs_ch = r3d_stride(cs, 1);
cs_tok = r3d_stride(cs, 2);
state_len = r3d_dim(cs, 2);
}
const uint32_t cb = (uint32_t)((n + kPcThreads - 1) / kPcThreads);
const uint32_t tb = (uint32_t)((T + kPcBT - 1) / kPcBT);
const auto kernel = silu ? r3d_ple_conv_kernel<true> : r3d_ple_conv_kernel<false>;
R3D_KLAUNCH(R3D_KNAME(kernel), dim3(cb, tb, (uint32_t)N), dim3(kPcThreads), (hipStream_t)s,
(const uint16_t*)r3d_p(x), (const uint16_t*)r3d_p(w),
have_cs ? (uint16_t*)r3d_wp(cs) : nullptr,
(const int32_t*)r3d_p(cu),
have_r ? (const uint16_t*)r3d_p(resid) : nullptr,
r3d_has(cidx) ? (const int32_t*)r3d_p(cidx) : nullptr,
r3d_has(hini) ? (const int32_t*)r3d_p(hini) : nullptr,
r3d_has(nacc) ? (const int32_t*)r3d_p(nacc) : nullptr,
(uint16_t*)r3d_wp(y), (uint32_t)n, (uint32_t)wid, (uint32_t)dil,
(uint32_t)hist, (uint32_t)xld, (uint32_t)rld, (uint32_t)yld, (uint32_t)wld,
cs_slot, cs_ch, cs_tok, state_len);
return hipGetLastError() == hipSuccess ? RAD_OK : R3D_NO(RAD_E_DEVICE);
}
} // namespace
extern "C" int r3d_rad_ple_conv(const RadArgs* a, RadStream s) {
return r3d_conv_launch(a, s, true, r3d_opt(a, PC_X), r3d_opt(a, PC_W), r3d_opt(a, PC_CS),
r3d_opt(a, PC_CU), r3d_opt(a, PC_RESID), r3d_opt(a, PC_CIDX),
r3d_opt(a, PC_HINIT), r3d_opt(a, PC_NACC), r3d_opt(a, PC_Y));
}
+18
View File
@@ -142,6 +142,7 @@ int r3d_rad_dequant (const RadArgs* a, RadStream s);
/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_f16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */
int r3d_rad_gemm_nt_bf16_m16 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_f16_m16 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_f32 (const RadArgs* a, RadStream s);
/* --- r3d_gemm_w4a16_nt_m64.hip: the 4-bit weight against an f16 activation at M <= 64. The
* codes are read in the container's order; the layout and relayout hooks present the
@@ -184,11 +185,19 @@ int r3d_rad_gdn_gated_norm_hq_i8(const RadArgs* a, RadStream s);
int r3d_rad_gdn_conv_prep(const RadArgs* a, RadStream s);
int r3d_rad_gdn_conv_update(const RadArgs* a, RadStream s);
/* --- r3d_ple_conv.hip: PLE's dilated depthwise convolution, its silu and the residual add that
* finishes the layer: one thread a channel, the conv window rewritten in the same launch. */
int r3d_rad_ple_conv(const RadArgs* a, RadStream s);
/* --- r3dh_gdn_recurrent_update.hip (libhalo's): the gated-delta-net recurrent state update at
* decode against the paged state cache, in either state form (per_candidate or anchor). */
extern "C" int r3dh_rad_gdn_recurrent_update(const RadArgs* a, RadStream s);
extern "C" int r3dh_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s);
/* --- r3d_kda_update.hip: GLM's per-channel KDA recurrence at decode and prefill, over the
* paged f32 state cache, with the speculative candidate snapshots. */
int r3d_rad_kda_update(const RadArgs* a, RadStream s);
/* --- r3d_expert_scale_bf16.hip: each routing weight times its expert's own scale, in place. */
int r3d_rad_expert_scale_bf16(const RadArgs* a, RadStream s);
@@ -205,6 +214,10 @@ int r3d_rad_moe_gather(const RadArgs* a, RadStream s);
int r3d_rad_moe_gather_inv(const RadArgs* a, RadStream s);
int r3d_rad_router_topk_scatter(const RadArgs* a, RadStream s);
int r3d_rad_router_sigmoid_topk(const RadArgs* a, RadStream s);
int r3d_rad_router_sigmoid_group_topk(const RadArgs* a, RadStream s);
int r3d_rad_mla_project(const RadArgs* a, RadStream s);
int r3d_rad_mla_attn_paged(const RadArgs* a, RadStream s);
int64_t r3d_rad_mla_attn_paged_scratch(const RadArgs* a);
/* --- r3d_moe_gemm_q.hip: the grouped quantised GEMM (E4M3 x E4M3, the per-(row, grid) scale fold). */
int r3d_rad_moe_gemm_q(const RadArgs* a, RadStream s);
@@ -274,7 +287,12 @@ int r3d_shape_scale (const RadParam* p, int n_p, int operand, RadOpdDe
int r3d_shape_fill (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_rope (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_kv_store (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_kda_update (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_embed_lookup (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gemm_nt_f32 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_router_sigmoid_group_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_mla_project (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_mla_attn_paged (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gather_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_scatter_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_quant_act_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
+257
View File
@@ -0,0 +1,257 @@
/* r3d_router_group_topk.hip -- router_sigmoid_group_topk: group-limited sigmoid routing.
*
* p[e] = sigmoid(logit[e]) and rank[e] = p[e] + bias[e]. The experts fall into `n_group` equal
* groups; a group ranks by the sum of its two highest ranks, the `topk_group` best groups are
* kept, and the top_k are taken from the kept groups' experts only. The weights are the kept
* experts' unbias'd p, times `route_scale` (divided by their own sum first, if `norm`): the
* correction bias selects, it never weights.
*
* logits [M][n_expert] f32, bias [n_expert] f32 -> ids [M][top_k] i32, weights [M][top_k] f32
*
* One wave per row: a lane holds experts lane, lane+32, ... as 64-bit keys -- the rank's
* order-preserving bits (-0 folded to +0, a NaN keyed 0 so it is never selected) above ~expert, so
* a tie goes to the lower expert -- and lane g holds group g's sum. Round j takes the largest key
* below round j-1's winner, which is a serial scan with a strict `>` done as a wave reduce: equal
* ranks to the lower expert, equal group sums to the lower group, a group with no finite pair
* never. A row with fewer selectable experts than top_k names expert 0 in the slots left over,
* weighted by expert 0's p, as libr4d's wave leaves it.
*
* The shim takes the row count from `logits` and every pitch from the operands, and refuses:
* fewer than 1 or more than 512 experts, top_k outside 1..32, fewer than 1 or more than 32 groups,
* a group count that does not divide the experts into at least two each, topk_group outside
* 1..n_group, a top_k wider than the kept groups can supply, a non-finite or non-positive
* route_scale, a logits plane that is not [M >= 1, pitch >= n_expert] with rows of stride 1, a
* bias that is not [n_expert] with a stride of at least 1, ids and weights that are not [M, pitch
* >= top_k] with rows of stride 1, and any dtype other than f32 logits, f32 bias, i32 ids and f32
* weights. Null operands are RAD_E_INVAL and every geometry rule above RAD_E_SHAPE, as in
* libr4d's launcher; libr3d's convention (r3d_args.h: an issue bug, not a shape) names the null
* case, and libr4d spells it inside its shape clause.
*
* gfx1102, from libr4d's router_group_wave_kernel (r4d_glm.hip). Two adaptations, no change to the
* arithmetic:
* * One wave per block, one block per row, where libr4d packs four rows into a 128-thread block.
* A wave reduction in a loop body miscompiles for a non-first wave of a block here -- wave 0
* is right, waves 1+ drop out (r3d_moe_router_topk_bf16.hip) -- and every loop in this kernel
* is one: the group ranking runs a wave merge per group, the group selection and the top_k
* each run one per round. One wave a block retires the case, and the __syncthreads that stages
* the scores is then a single-wave barrier.
* * The wave reductions are libr3d's DPP16 and v_permlanex16 lane exchanges (r3d_common.h),
* which is what libr4d's butterflies lower to and what `__shfl_xor` costs on RDNA3 (a
* ds_bpermute and a dscnt wait). Same lanes, same order, so the merge is bit-identical to
* libr4d's: the top-2 merge over 16, 8, 4, 2, 1, the group max and the expert max are the r4d
* kernel's, key for key, so a tied row, a row with a -0 rank and a row with a NaN rank land on
* the same bytes in both backends. The scores are staged in LDS and the kept sum read back lane
* by lane (the libr3d router's idiom) instead of a gather shuffle per key.
*
* No matrix instruction: this is a selection over at most 512 f32, bandwidth-bound and
* register-resident. The only LDS is a small static stage -- `n_expert` scores plus 32 kept sums,
* 2.2 KiB at the widest row, far under RDNA3's 64 KiB -- so there is no dynamic LDS to size
* against the cap in the launcher.
*/
#include <hip/hip_runtime.h>
#include <cmath>
#include <cstdint>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
namespace {
/* (order-preserving rank, ~expert) as one 64-bit key: the rank's monotone bits (-0 folded to +0)
* above the complemented expert, so a tie goes to the lower expert. A NaN rank keys 0, which no
* round selects. libr4d's router_rank_key, unchanged. */
__device__ __forceinline__ unsigned long long r3d_router_rank_key(float rank, uint32_t e) {
uint32_t u = __float_as_uint(rank);
if (u == 0x80000000u) u = 0;
const uint32_t k = (u & 0x80000000u) ? ~u : (u | 0x80000000u);
return rank == rank ? ((unsigned long long)k << 32) | (uint32_t)~e : 0ull;
}
/* The wave's largest key: the xor butterfly over 16, 8, 4, 2, 1, the halves exchanged as a 64-bit
* shuffle does. Keys are unique (the low half is the expert), so the winner is unique and the
* butterfly's order cannot matter. */
__device__ __forceinline__ unsigned long long r3d_router_wave_max(unsigned long long b) {
unsigned long long o;
o = r3d_xor_lane_u64<16>(b);
b = b > o ? b : o;
o = r3d_xor_lane_u64<8>(b);
b = b > o ? b : o;
o = r3d_xor_lane_u64<4>(b);
b = b > o ? b : o;
o = r3d_xor_lane_u64<2>(b);
b = b > o ? b : o;
o = r3d_xor_lane_u64<1>(b);
b = b > o ? b : o;
return b;
}
/* One butterfly round of the two best: the higher head, and the higher of the two tails and the
* lower head. A NaN rank never reaches here -- a lane's own scan drops it on both `>` tests. */
template <int N>
__device__ __forceinline__ void r3d_router_top2_merge(float& t0, float& t1) {
const float o0 = r3d_xor_lane<N>(t0), o1 = r3d_xor_lane<N>(t1);
const float hi = fmaxf(t0, o0), lo = fmaxf(fminf(t0, o0), fmaxf(t1, o1));
t0 = hi;
t1 = lo;
}
/* The wave's two best, in the order libr4d's `for (mask = 16; mask; mask >>= 1)` runs them. */
__device__ __forceinline__ void r3d_router_top2_wave(float& t0, float& t1) {
r3d_router_top2_merge<16>(t0, t1);
r3d_router_top2_merge<8>(t0, t1);
r3d_router_top2_merge<4>(t0, t1);
r3d_router_top2_merge<2>(t0, t1);
r3d_router_top2_merge<1>(t0, t1);
}
/* One row, one wave, one block. OWN is a template bound because the keys are registers: a
* lane-derived trip count would index them divergently. A tail expert reads address 0 of its row
* and keys absent; it is never stored. */
template <int OWN>
__global__ __launch_bounds__(kWave) void r3d_router_group_topk_kernel(
const float* __restrict__ logits, const float* __restrict__ bias, int32_t* __restrict__ ids,
float* __restrict__ weights, long lp, long bp, long ip, long wp, uint32_t m, uint32_t ne,
uint32_t k, uint32_t ng, uint32_t kg, int norm, float factor) {
__shared__ float s_score[kWave * OWN]; // the row's p, so a weight is read back, not recomputed
__shared__ float s_sel[kWave]; // the kept p, lane j = round j
const uint32_t lane = threadIdx.x, r = blockIdx.x;
if (r >= m) return;
const uint32_t gs = ne / ng; // experts a group; the shim divided ne by ng exactly
float p[OWN], rank[OWN];
#pragma unroll
for (uint32_t i = 0; i < OWN; ++i) {
const uint32_t e = lane + i * kWave, s = e < ne ? e : 0;
p[i] = 1.0f / (1.0f + expf(-logits[(size_t)r * lp + s])); // the reference's sigmoid
rank[i] = e < ne ? p[i] + bias[(size_t)s * bp] : -INFINITY;
s_score[lane * OWN + i] = p[i];
}
R3D_BARRIER();
// The groups, largest sum first: lane g takes group g's two-best sum after the wave merge.
float group = -INFINITY;
for (uint32_t g = 0; g < ng; ++g) {
float t0 = -INFINITY, t1 = -INFINITY;
#pragma unroll
for (uint32_t i = 0; i < OWN; ++i) {
const uint32_t e = lane + i * kWave;
if (e < ne && e / gs == g) {
const float v = rank[i];
if (v > t0) {
t1 = t0;
t0 = v;
} else if (v > t1)
t1 = v;
}
}
r3d_router_top2_wave(t0, t1);
if (lane == g) group = t0 + t1;
}
const unsigned long long gkey =
lane < ng && group > -INFINITY ? r3d_router_rank_key(group, lane) : 0ull;
// The kg best groups, by key: bit g of `kept` says group g's experts are selectable.
unsigned kept = 0;
unsigned long long below = ~0ull;
for (uint32_t j = 0; j < kg; ++j) {
const unsigned long long best = r3d_router_wave_max(gkey < below ? gkey : 0ull);
if (best) kept |= 1u << (int)~(uint32_t)best;
below = best;
}
// Then the top_k of the kept groups' experts, the same rounds on the experts' own keys.
unsigned long long key[OWN];
#pragma unroll
for (uint32_t i = 0; i < OWN; ++i) {
const uint32_t e = lane + i * kWave;
key[i] = e < ne && ((kept >> (e / gs)) & 1u) ? r3d_router_rank_key(rank[i], e) : 0ull;
}
unsigned long long mine = 0;
below = ~0ull;
for (uint32_t j = 0; j < k; ++j) {
unsigned long long best = 0;
#pragma unroll
for (uint32_t i = 0; i < OWN; ++i) {
const unsigned long long c = key[i] < below ? key[i] : 0ull;
best = c > best ? c : best;
}
best = r3d_router_wave_max(best);
if (lane == j) mine = best;
below = best;
}
// The weights are the unbias'd scores, summed in round order -- lane order, since lane j parked
// round j's winner -- and the sum is over the kept k, not over the wave.
const uint32_t e = mine ? (uint32_t)~(uint32_t)mine : 0u;
const float chosen = s_score[(e & (kWave - 1)) * OWN + (e >> 5)];
s_sel[lane] = chosen;
R3D_BARRIER();
float total = 0.0f;
#pragma unroll
for (uint32_t j = 0; j < kWave; ++j)
if (j < k) total += s_sel[j];
const float mult = norm ? factor / (total + 1e-20f) : factor;
if (lane < k) {
ids[(size_t)r * ip + lane] = (int32_t)e;
weights[(size_t)r * wp + lane] = chosen * mult;
}
static_assert(sizeof(s_score) + sizeof(s_sel) <= 60 * 1024,
"the row's stage is 2.2 KiB at 512 experts, well under RDNA3's 64 KiB");
}
} // namespace
extern "C" {
int r3d_rad_router_sigmoid_group_topk(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 4) return R3D_NO(RAD_E_INVAL);
const long long ne = r3d_geti_or(a, "n_expert", 0), k = r3d_geti_or(a, "top_k", 0),
ng = r3d_geti_or(a, "n_group", 0), kg = r3d_geti_or(a, "topk_group", 0);
const float factor = (float)r3d_getf(a, "route_scale", 0.0);
const RadTensor* lg = r3d_opt(a, 0);
const RadTensor* bs = r3d_opt(a, 1);
const RadTensor* id = r3d_opt(a, 2);
const RadTensor* w = r3d_opt(a, 3);
if (!r3d_p(lg) || !r3d_p(bs) || !r3d_wp(id) || !r3d_wp(w)) return R3D_NO(RAD_E_INVAL);
if (lg->dtype != RAD_F32 || bs->dtype != RAD_F32 || id->dtype != RAD_I32 ||
w->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
const long long m = r3d_dim(lg, 0); // the row count of the call, not the band's bound
if (ne < 1 || ne > 512 || k < 1 || k > 32 || ng < 1 || ng > 32 || ne % ng || ne / ng < 2 ||
kg < 1 || kg > ng || k > kg * (ne / ng) || !std::isfinite(factor) || factor <= 0 ||
lg->rank != 2 || m < 1 || m > 65535 || r3d_dim(lg, 1) != ne || bs->rank != 1 ||
r3d_dim(bs, 0) != ne || id->rank != 2 || w->rank != 2 || r3d_dim(id, 0) != m ||
r3d_dim(w, 0) != m || r3d_dim(id, 1) != k || r3d_dim(w, 1) != k ||
r3d_stride(lg, 1) != 1 || r3d_stride(id, 1) != 1 || r3d_stride(w, 1) != 1 ||
r3d_stride(lg, 0) < ne || r3d_stride(id, 0) < k || r3d_stride(w, 0) < k ||
r3d_stride(bs, 0) < 1)
return R3D_NO(RAD_E_SHAPE);
const int norm = (int)(r3d_geti_or(a, "norm", 0) != 0);
const long lp = r3d_stride(lg, 0), bp = r3d_stride(bs, 0), ip = r3d_stride(id, 0),
wp = r3d_stride(w, 0);
dim3 grid((unsigned)m), blk(kWave); // one wave a row, one block a row (gfx1102)
const float* lgd = (const float*)r3d_p(lg);
const float* bpd = (const float*)r3d_p(bs);
int32_t* ipd = (int32_t*)r3d_wp(id);
float* wpd = (float*)r3d_wp(w);
// 9 keys a lane to 288 experts (DeepSeek-V3's 256, GLM-5.3's 288), 16 to 512; libr4d's split.
if (ne <= (long long)9 * kWave)
R3D_KLAUNCH(r3d_router_group_topk_kernel<9>, grid, blk, (hipStream_t)s, lgd, bpd, ipd,
wpd, lp, bp, ip, wp, (uint32_t)m, (uint32_t)ne, (uint32_t)k, (uint32_t)ng,
(uint32_t)kg, norm, factor);
else
R3D_KLAUNCH(r3d_router_group_topk_kernel<16>, grid, blk, (hipStream_t)s, lgd, bpd, ipd,
wpd, lp, bp, ip, wp, (uint32_t)m, (uint32_t)ne, (uint32_t)k, (uint32_t)ng,
(uint32_t)kg, norm, factor);
return (int)hipGetLastError();
}
} // extern "C"
+179 -15
View File
@@ -184,6 +184,8 @@ static const RadOperandSpec oRouterSigmoid[] = { { "logits", RAD_OPD_IN, 0 },
{ "weights", RAD_OPD_OUT, 0 } };
static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
static const RadParamSpec pRouterSigmoidGroup[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
P_INT("n_group"), P_INT("topk_group"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
static const RadOperandSpec oGatedQuant[] = { { "gate_up", RAD_OPD_IN, 0 },
{ "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 },
@@ -227,6 +229,9 @@ static const RadOperandSpec oDequant[] = { { "q", RAD_OPD_IN, 0 }, { "scale", RA
/* --- gemm --- */
static const RadParamSpec pGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype") };
/* pGemmNt/oGemmNt (gemm_nt_f32) reuse pGemm/oGemm above: the pair is byte-identical to
* libr4d's, and the loader compares positionally. */
static const RadOperandSpec oGemm[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 } };
@@ -313,6 +318,22 @@ static const RadOperandSpec oGdnConvUpdate[] = { { "x", RAD_OPD_IN, 0 },
{ "k", RAD_OPD_OUT, 0 },
{ "v", RAD_OPD_OUT, 0 } };
static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width"),
P_INT("dilation"), P_STR("dtype") };
/* The optionals unite gdn_conv_prep's and gdn_conv_update's contracts: `has_init` serves
* prefill, `num_accepted` decode. */
static const RadOperandSpec oPleConv[] = {
{ "x", RAD_OPD_IN, 0 },
{ "w", RAD_OPD_WEIGHT, 0 },
{ "conv_state", RAD_OPD_INOUT, 0 },
{ "cu", RAD_OPD_IN, 0 },
{ "resid", RAD_OPD_IN, 1 },
{ "cache_idx", RAD_OPD_IN, 1 },
{ "has_init", RAD_OPD_IN, 1 },
{ "num_accepted", RAD_OPD_IN, 1 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pExpertScale[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
P_STR("dtype") };
static const RadOperandSpec oExpertScale[] = { { "ids", RAD_OPD_IN, 0 },
@@ -394,6 +415,18 @@ static const RadOperandSpec oGdnRecurrent[] = { { "q", RAD_OPD_IN, 0 },
{ "o", RAD_OPD_OUT, 0 },
{ "o_q", RAD_OPD_OUT, 1 },
{ "o_scale", RAD_OPD_OUT, 1 } };
static const RadParamSpec pKdaUpdate[] = {
P_INT("M"), P_INT("heads"), P_INT("head_k"), P_INT("head_v"), P_F64("lower_bound"),
P_F64("scale"), P_F64("l2_eps"), P_STR("mode"), P_STR("dtype"),
P_STRO("state_form"),
};
static const RadOperandSpec oKdaUpdate[] = {
{"q", RAD_OPD_IN, 0}, {"k", RAD_OPD_IN, 0}, {"v", RAD_OPD_IN, 0},
{"a", RAD_OPD_IN, 0}, {"b", RAD_OPD_IN, 0}, {"A_log", RAD_OPD_WEIGHT, 0},
{"dt_bias", RAD_OPD_WEIGHT, 0}, {"state", RAD_OPD_INOUT, 0}, {"state_idx", RAD_OPD_IN, 0},
{"cu", RAD_OPD_IN, 0}, {"num_accepted", RAD_OPD_IN, 1}, {"has_init", RAD_OPD_IN, 1},
{"o", RAD_OPD_OUT, 0},
};
/* gdn_conv_recurrent_update: the decode conv and the recurrent update as one kernel, the
* convolution's operands then the recurrence's minus q, k and v (never materialised). */
@@ -487,6 +520,21 @@ static const RadOperandSpec oAttnPaged[] = {
{ "cu_seqlens", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 }
};
static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") };
static const RadParamSpec pMlaAttnPaged[] = { P_INT("M"), P_INT("heads"), P_INT("latent_dim"),
P_INT("rope_dim"), P_INT("block_size"), P_F64("scale"),
P_STR("dtype") };
static const RadOperandSpec oMlaAttnPaged[] = { { "q", RAD_OPD_IN, 0 },
{ "q_rope", RAD_OPD_IN, 1 },
{ "kv", RAD_OPD_IN, 0 },
{ "block_table", RAD_OPD_IN, 0 },
{ "seqused", RAD_OPD_IN, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 },
{ "gate", RAD_OPD_IN, 1 },
{ "out", RAD_OPD_OUT, 0 } };
/* The row's top-R over a vocabulary slice, and the sampler's stages. The history stages write this
* rank's columns and read global ids, so they carry `vocab_off`; the narrowing stages work on the
* candidate set the top-k produced and need only its width. */
@@ -693,6 +741,9 @@ static const RadOpSchema kSchemas[] = {
"y = code * scale, the read of a container's own quantised weight: `group`-wide f32 "
"scales against E4M3, E5M2 or int8 codes."),
SCHEMA("gemm_nt", pGemm, oGemm, "y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate."),
SCHEMA("gemm_nt_f32", pGemm, oGemm,
"BF16 activations times F32 weights, F32 accumulation and output; preserves routing "
"and index gate precision."),
SCHEMA("gemm_nt_q", pGemmQ, oGemmQ,
"The same product against a quantised weight. `dtype` names the scheme: fp8a16 a bf16 "
"activation against E4M3 codes, fp8a8 quant_act_fp8's codes and scales, i8a8 int8 on "
@@ -728,6 +779,22 @@ static const RadOpSchema kSchemas[] = {
"conv-state buffer, read at the slot the last accepted token left and rewritten "
"shifted by one; writes q, k and v in their own layouts."),
SCHEMA("ple_conv", pPleConv, oPleConv,
"y[t] = resid[t] + silu(sum_j w[c][j] * x[t - (width-1-j)*dilation]), a DEPTHWISE "
"CAUSAL convolution whose taps are `dilation` apart -- at width 4 and dilation 3 they "
"are 9, 6, 3 and 0 timesteps back, so the history a sequence carries is "
"(width-1)*dilation and not width-1. The state is [n_slots, n, state_len] with slot i "
"holding the value at relative position i - (width-1)*dilation, and `has_init` 0 means "
"that window is ZEROS rather than whatever the slot last held. `num_accepted` shifts "
"the READ offset within a deeper window and marks a decode step: the window is then "
"rewritten as gdn_conv_update rewrites its own -- the history read shifted down by one, "
"then every input of the step -- so a next step that kept k tokens reads at k - 1. "
"Absent, every token commits: the read is at offset zero and the last "
"(width-1)*dilation inputs land at offset zero, which is the prefill chunk. "
"`resid` absent drops the add and leaves the plain convolution."),
SCHEMA("kda_update", pKdaUpdate, oKdaUpdate,
"Bounded per-channel KDA recurrence. verify stores candidate states; prefill commits final state. "
"Absolute cu offsets, accepted-prefix read slot, optional cold initialization, no output norm."),
SCHEMA("gdn_recurrent_update", pGdnRecurrent, oGdnRecurrent,
"The gated-delta-net recurrent state update at decode: g = -exp(A_log) softplus(a + "
"dt_bias), beta = sigmoid(b), q/k l2-normalised, S *= e^g, u = beta (v - S k), S += u "
@@ -760,6 +827,10 @@ static const RadOpSchema kSchemas[] = {
"n_expert logits, then the sort over this rank's n_local slice. expert_w is the "
"selection output the sort reads."),
SCHEMA("router_sigmoid_group_topk", pRouterSigmoidGroup, oRouterSigmoid,
"Group-limited sigmoid routing: groups rank by the sum of their two best p + bias, "
"selection runs over the topk_group best groups; correction bias selects, original "
"scores weight."),
SCHEMA("router_sigmoid_topk", pRouterSigmoid, oRouterSigmoid,
"The GLM-style router: scores = sigmoid(logits), the selection on scores + bias, the "
"kept weights the scores scaled by route_scale (renormalised if `norm`). Ties to the "
@@ -793,6 +864,12 @@ static const RadOpSchema kSchemas[] = {
"`seqused` its length. `gqa` is the head ratio; `causal` and `window` are the mask; "
"`scale` is 1/sqrt(head_dim) unless the graph says otherwise. k_descale and v_descale "
"come with an fp8 cache, cu_seqlens with a packed prefill."),
SCHEMA("mla_attn_paged", pMlaAttnPaged, oMlaAttnPaged,
"Dense causal latent attention over a paged cache whose token row is the latent then the "
"rotated key part: score = scale * (q . latent + q_rope . rope), value = the latent; "
"sequences as in attn_paged. With `gate`, out = bf16(bf16(out) * bf16(sigmoid(gate[head])))."),
SCHEMA("mla_project", pMlaProject, oGemm,
"Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix."),
SCHEMA("row_topk", pRowTopk, oRowTopk,
"Exact per-row top-R, descending, ties to the lower column. `vocab_off` shifts every "
"column reported, so a rank's slice reports global ids; `pairs` is the [M, R, 2] plane an "
@@ -1194,11 +1271,13 @@ static const RadConstraint cActSigmoid[] = { C_IN("act", "sigmoid"), C_IN("dtype
static const RadConstraint cFillBf16[] = { C_IN("dtype", "bf16") };
static const RadConstraint cFillF32[] = { C_IN("dtype", "f32") };
static const RadConstraint cDequantW4[] = { C_DIV("N", 16), C_DIV("K", 64) };
static const RadConstraint cRowTopkMerge[] = { C_GE("R", 1), C_LE("R", 32) };
static const RadConstraint cRowTopkMerge[] = { C_GE("R", 1), C_LE("R", 32), C_IN("dtype", "f32") };
static const RadConstraint cNgramIds[] = { C_GE("ngram", 2), C_LE("ngram", 8) };
static const RadConstraint cGemmQBias[] = { C_IN("dtype", "fp8a8"), C_GE("M", 1), C_LE("M", 16) };
static const RadConstraint cGemmQShort[] = { C_IN("dtype", "fp8a8"), C_GE("M", 1), C_LE("M", 64) };
static const RadConstraint cMoeGemmQMod4[] = { C_GE("n_expert", 4) };
static const RadConstraint cFillI32[] = { C_IN("dtype", "i32") };
static const RadConstraint cFillI64[] = { C_IN("dtype", "i64") };
@@ -1219,6 +1298,22 @@ static const RadConstraint cKvFp8[] = { C_IN("kv_dtype", "fp8_e4m3"), C_DIV("he
C_DIV("block_size", 16) };
static const RadConstraint cKvF16[] = { C_IN("kv_dtype", "f16"), C_DIV("head_dim", 2),
C_DIV("block_size", 16) };
/* head_dim is 128 or 256 (the launcher refuses anything else); the constraint system has no
* int-set form, so the row states the range and the kernel enforces the set. */
static const RadConstraint cMlaProject[] = { C_GE("M", 1),
C_LE("M", 65535),
C_GE("heads", 1),
C_LE("heads", 64),
C_GE("head_dim", 128),
C_LE("head_dim", 256),
C_EQ("latent_dim", 512),
C_IN("mode", "absorb expand"),
C_IN("dtype", "bf16") };
static const RadConstraint cMlaAttnPaged[] = {
C_GE("M", 1), C_LE("M", 65535), C_EQ("latent_dim", 512), C_EQ("rope_dim", 64),
C_GE("heads", 1), C_LE("heads", 64), C_GE("block_size", 1), C_LE("block_size", 256),
C_IN("dtype", "bf16")
};
static const RadConstraint cEmbed[] = { C_IN("dtype", "bf16"), C_DIV("n_embd", 2) };
@@ -1275,6 +1370,10 @@ static const RadConstraint cDequantI8[] = { C_IN("dtype", "i8"), C_EQ("group",
* through LDS pays. K even because the inner loop consumes pairs. N has no bound: a wave covering N
* handles the tail, and feed-forward and vocabulary widths (11008, 14336, 128256, a checkpoint's
* `intermediate_size`) vary. */
static const RadConstraint cGemmNtF32[] = { C_GE("M", 1), C_LE("M", 65535),
C_GE("N", 1), C_LE("N", 512),
C_GE("K", 1), C_LE("K", 16384),
C_IN("dtype", "bf16") };
static const RadConstraint cGemmM16[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 16),
C_DIV("K", 2), C_GE("N", 1) };
static const RadConstraint cGemmM16F16[] = { C_IN("dtype", "f16"), C_GE("M", 1), C_LE("M", 16),
@@ -1300,8 +1399,20 @@ static const RadConstraint cGdnConvW4[] = { C_GE("M", 1), C_EQ("head_k", 128), C
C_EQ("conv_width", 4) };
static const RadConstraint cGdnConvUpdW4[] = { C_GE("q_len", 1), C_EQ("head_k", 128),
C_EQ("head_v", 128), C_EQ("conv_width", 4) };
/* PLE's convolution. The kernel bounds (width-1)*dilation, the state write-back's register
* window, at 16; a constraint cannot express a product, so these are the tightest separate caps
* admitting every combination under it. */
static const RadConstraint cPleConv[] = { C_IN("dtype", "bf16"), C_GE("width", 1),
C_LE("width", 5), C_GE("dilation", 1),
C_LE("dilation", 4) };
static const RadConstraint cGdnRecurrent[] = { C_GE("q_len", 1), C_EQ("head_k", 128),
C_EQ("head_v", 128) };
static const RadConstraint cKdaUpdate[] = {
C_GE("M", 1), C_GE("heads", 1), C_LE("heads", 65535),
C_EQ("head_k", 128), C_EQ("head_v", 128), C_IN("mode", "prefill verify"),
C_IN("dtype", "bf16"),
};
static const RadConstraint cGdnConvRecurrent[] = { C_GE("q_len", 1), C_EQ("head_k", 128),
C_EQ("head_v", 128), C_EQ("conv_width", 4) };
static const RadConstraint cExpertScaleBf16[] = { C_IN("dtype", "bf16"), C_GE("top_k", 1),
@@ -1332,6 +1443,11 @@ static const RadConstraint cRouterTopkScatter[] = { C_GE("M", 1), C_GE("n_expert
static const RadConstraint cRouterSigmoid[] = { C_GE("M", 1), C_GE("n_expert", 1),
C_GE("top_k", 1), C_LE("n_expert", 512),
C_IN("dtype", "bf16") };
static const RadConstraint cRouterSigmoidGroup[] = { C_GE("M", 1), C_LE("M", 65535),
C_GE("n_expert", 1), C_LE("n_expert", 512),
C_GE("top_k", 1), C_LE("top_k", 32),
C_GE("n_group", 1), C_LE("n_group", 32),
C_IN("dtype", "f32") };
static const RadConstraint cMoeGemmBf16[] = { C_IN("dtype", "bf16"), C_GE("n_expert", 1),
C_GE("top_k", 1) };
/* The vocabulary projection has no `dtype` constraint because its band carries no `dtype` key: the
@@ -1976,6 +2092,21 @@ static const RadKernelInfo kKernels[] = {
[](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); },
nullptr, nullptr, r3d_shape_gemm_nt },
/* ------------------------------------------------------------------ r3d_gemm_nt_f32.hip
*
* The router's F32 projection: a bf16 activation against an f32 weight, f32 out, no narrowing.
* One wave R rows by C columns, lane l folding k = l, l+32, ... with fmaf and the xor butterfly;
* the tile form its rule picks for M, every form byte-identical.
*/
{ "gemm_nt_f32_bf16", "gemm_nt_f32", "gemm",
"F32 routing and index gate projection",
"N<=512, K<=16384; pitched rows",
"bf16 input, f32 weights and output",
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY,
ROW(cGemmNtF32), NOTUNE,
nullptr, nullptr, r3d_rad_gemm_nt_f32, nullptr, nullptr, nullptr,
r3d_shape_gemm_nt_f32 },
/* ------------------------------------------------------------------ r3d_gemm_w4a16_nt_m64.hip
*
* The 4-bit weight against an f16 activation, at the verify and small-prefill heights: the
@@ -2122,6 +2253,14 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, nullptr,
nullptr, nullptr },
{ "ple_conv_bf16", "ple_conv", "norm",
"PLE's dilated depthwise conv, silu and residual add; one thread a channel",
"width up to 5 and dilation up to 4 -- (width-1)*dilation is a register window",
"bf16 activations, weights and conv state; i32 cu, slots, has_init and num_accepted",
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY,
ROW(cPleConv), NOTUNE,
nullptr, nullptr, r3d_rad_ple_conv, nullptr, nullptr, nullptr, nullptr },
{ "expert_scale_bf16", "expert_scale", "moe",
"Each routing weight times its expert's own per-expert scale, in place",
"the router's renormalised top-k weight scaled by the [n_expert] table, an out-of-table id "
@@ -2168,6 +2307,14 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r3d_rad_router_sigmoid_topk,
nullptr, nullptr, nullptr,
nullptr, nullptr },
{ "moe_router_sigmoid_group_topk_f32", "router_sigmoid_group_topk", "moe",
"group-limited sigmoid correction-bias routing, one wave a row",
"experts <=512, groups <=32, top_k<=32",
"f32 logits, bias and weights; i32 ids",
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY,
ROW(cRouterSigmoidGroup), NOTUNE,
nullptr, nullptr, r3d_rad_router_sigmoid_group_topk, nullptr, nullptr, nullptr,
r3d_shape_router_sigmoid_group_topk },
{ "moe_scatter_small", "moe_scatter", "moe",
"The routed slots' stable counting sort",
@@ -2328,19 +2475,6 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr },
{ "ngram_ids_i32", "ngram_ids", "vocab",
"The hashed row ids of the Per-Layer Embedding: mixed(k) = XOR of t_s * mult[s], "
"ids[h] = mixed % vocab_sizes[h] + offsets[h]",
"One thread a token, looping its heads; n-gram shifts with EOS walk; 64-bit wrapping "
"multiply and floor-mod; ngram <= 8, heads divisible by (ngram-1)",
"i32 tok, i32 state, i32 cu, i64 mult, i64 vsz, i64 off, i32 ids; "
"optional i32 cidx, hini, nacc, ahead",
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY,
ROW(cNgramIds), NOTUNE,
nullptr, nullptr, r3d_rad_ngram_ids,
nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr },
{ "gemm_nt_q_bias_fp8a8_m16", "gemm_nt_q_bias", "gemm",
"The narrow fp8 GEMM with a per-column bias epilogue: y = a @ b^T + bias",
"M <= 16, K a multiple of the block; fp8a8 codes and scales, bf16 bias and output; "
@@ -2376,7 +2510,23 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr },
/* ------------------------------------------------------------------ r3d_gdn_recurrent_update_k128_v128.hip
/* ------------------------------------------------------------------ r3d_kda_update.hip
*
* GLM's per-channel KDA recurrence over a paged f32 state cache: the decay from the softplus-
* limited gate, the l2-normalised q and k, the delta-rule step and o = S q per token, with the
* speculative candidate snapshots. The state never touches LDS: a wave owns four value rows and
* keeps each row's 128 state elements in four registers a lane, so the RDNA3 64 KiB stage is not
* in play.
*/
{ "kda_update_k128_v128_bf16", "kda_update", "gdn",
"per-channel KDA recurrence and candidate rollback",
"heads 1..65535, K=V=128, prefill and verify",
"bf16 activations, f32 gates and state",
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY,
ROW(cKdaUpdate), NOTUNE,
nullptr, nullptr, r3d_rad_kda_update, nullptr, nullptr, nullptr, r3d_shape_kda_update },
/* ------------------------------------------------------------------ r3d_gdn_recurrent_update_k128_v128.hip
*
* The gated-delta-net recurrent state update at decode: the per-token state step against a paged
* fp32 state cache, the state in registers (one thread per v row and half its k range), the
@@ -2640,6 +2790,20 @@ static const RadKernelInfo kKernels[] = {
r3d_shape_attn_paged },
{ "mla_project_bf16", "mla_project", "attn", "per-head absorbed MLA projections",
"head_dim 128 or 256, latent_dim=512; pitched tensors", "bf16 input, weights and output; fp32 arithmetic",
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cMlaProject), NOTUNE,
nullptr, nullptr, r3d_rad_mla_project, nullptr, nullptr, nullptr,
r3d_shape_mla_project },
{ "mla_attn_paged_bf16", "mla_attn_paged", "attn",
"dense causal latent attention with a rotary part, a wave a (row, head), split history",
"latent_dim=512, rope_dim=64, heads<=64, block_size<=256; one page table a sequence",
"bf16 Q/rotary/cache/gate/output, f32 softmax and partials",
RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cMlaAttnPaged), NOTUNE,
nullptr, nullptr, r3d_rad_mla_attn_paged, r3d_rad_mla_attn_paged_scratch, nullptr, nullptr,
r3d_shape_mla_attn_paged },
/* ------------------------------------------------------------------ r3d_sample_f32.hip
*
* The sampler's spine: the row's top-R and the stages that turn its candidate plane into one token.
+82
View File
@@ -277,6 +277,27 @@ int r3d_shape_kv_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
/* x[r] = wte[ids[r] - vocab_offset]. Ids are global, so the draw's bound is `vocab_offset + n_vocab`:
* under a shard the draw crosses the slice boundary and exercises the zero-row path. */
/* The KDA recurrence (r3d_kda_update.hip). The state cache's slot axis is the step's candidate
* count plus one, and `state_idx` draws inside it, uniquely per sequence. */
int r3d_shape_kda_update(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const char* form = gs(p, n_p, "state_form");
if (form && !std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED;
const int64_t M = gi(p, n_p, "M", 0), H = gi(p, n_p, "heads", 0);
const int64_t K = gi(p, n_p, "head_k", 0), V = gi(p, n_p, "head_v", 0);
const uint32_t D = act_dt(p, n_p);
const char* mode = gs(p, n_p, "mode");
const int64_t history = (mode && !std::strcmp(mode, "verify")) ? M : 1;
const RadOpdDesc l[] = {
opd(D, M, H, K), opd(D, M, H, K), opd(D, M, H, V), opd(D, M, H, K), opd(D, M, H),
opd((uint32_t)RAD_F32, H), opd((uint32_t)RAD_F32, H * K),
opd((uint32_t)RAD_F32, history + 1, H, V, K),
opd_idx(1, history + 1, -1, RAD_OPD_F_IDX_UNIQUE, history),
opd_idx(2, M, -1, RAD_OPD_F_IDX_CU),
opd_idx(1, 0, 1), opd_idx(1, 0, 1), opd(D, M, H, V),
};
R3D_PICK(l);
}
int r3d_shape_embed_lookup(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t ne = gi(p, n_p, "n_embd", 0);
@@ -504,6 +525,15 @@ int r3d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
const RadOpdDesc list[] = { opd(D, M, K), opd(D, N, K), opd(D, M, N) }; /* a, b, y */
R3D_PICK(list);
}
/* y[M,N] = a[M,K] @ b[N,K]^T with an F32 weight and output: the router's logits and the index
* gates, the row's own dtype. */
int r3d_shape_gemm_nt_f32(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, K), opd((uint32_t)RAD_F32, N, K),
opd((uint32_t)RAD_F32, M, N) }; /* a, b, y */
R3D_PICK(list);
}
/* The vocabulary projection, transcribed from ref_logits_gemm_shape: x [M, n_embd] and the head
* [n_vocab, n_embd] in the activation's dtype, logits in f32 because every sampler stage reads
@@ -708,6 +738,42 @@ int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
};
R3D_PICK(list);
}
/* The absorbed MLA projection (r3d_mla_project.hip): a[M, heads, head_dim|latent] against the
* shared [heads, 2*head_dim, latent] weight, absorb or expand. */
int r3d_shape_mla_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), h = gi(p, n_p, "heads", 0), d = gi(p, n_p, "head_dim", 0),
l = gi(p, n_p, "latent_dim", 0);
const char* mode = gs(p, n_p, "mode");
const bool absorb = mode && !std::strcmp(mode, "absorb"),
expand = mode && !std::strcmp(mode, "expand");
if (!absorb && !expand) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, absorb ? d : l),
opd((uint32_t)RAD_BF16, h * 2 * d, l),
opd((uint32_t)RAD_BF16, M, h, absorb ? l : d) };
R3D_PICK(list);
}
/* The paged latent attention (r3d_mla_attn_paged.hip): the cache row is the latent then the
* rotated key part; `block_table` draws its page indices, `seqused` the context so far, and
* `cu_seqlens` the [0, M+1] cumulative form. */
int r3d_shape_mla_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), h = gi(p, n_p, "heads", 0), L = gi(p, n_p, "latent_dim", 0),
R = gi(p, n_p, "rope_dim", 0), bs = gi(p, n_p, "block_size", 0);
if (M <= 0 || h <= 0 || L <= 0 || R <= 0 || bs <= 0) return RAD_E_UNSUPPORTED;
int64_t ctx = gi(p, n_p, "ctx", 0);
if (ctx < M) ctx = M;
const int64_t blocks = (ctx + bs - 1) / bs;
const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, L),
opd((uint32_t)RAD_BF16, M, h, R),
opd((uint32_t)RAD_BF16, blocks, 1, bs, L + R),
opd_idx(1, blocks, -1, 0, blocks),
opd_idx(1, 0, ctx),
opd_idx(2, M + 1, -1, (uint32_t)RAD_OPD_F_IDX_CU),
opd_none(),
opd((uint32_t)RAD_BF16, M, h, L) };
R3D_PICK(list);
}
/* Exact per-row top-R. `pairs` packs an int32 id's bits in the first slot beside its value, in an
* f32 plane. */
@@ -721,6 +787,22 @@ int r3d_shape_row_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
}; /* x, idx, val, pairs */
R3D_PICK(list);
}
/* Group-limited sigmoid routing: the group form of router_sigmoid_topk. The geometry's bounds are
* the shim's: `n_expert` 1..512, `n_group` 1..32 dividing the experts by at least two,
* `topk_group` a group count, `top_k` inside the kept groups' experts. f32 operands, as the row's
* constraints; `ids` is drawn over `n_expert`. (libr4d's r4d_shape_router_sigmoid_group_topk.) */
int r3d_shape_router_sigmoid_group_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), ne = gi(p, n_p, "n_expert", 0), k = gi(p, n_p, "top_k", 0);
const int64_t ng = gi(p, n_p, "n_group", 0), kg = gi(p, n_p, "topk_group", 0);
if (ne <= 0 || ne > 512 || k <= 0 || ng <= 0 || ng > 32 || ne % ng || ne / ng < 2 || kg <= 0 ||
kg > ng || k > kg * (ne / ng))
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const RadOpdDesc list[] = { opd(D, M, ne), opd((uint32_t)RAD_F32, ne),
opd_idx(M, ne, -1, 0, k), opd(D, M, k) };
R3D_PICK(list);
}
int r3d_shape_sample_argmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;