Merge main into clef-flash-arch-plugin

This commit is contained in:
Brandon Bertelsen committed 2026-10-28 22:53:52 -04:00
commit d24cf32a13
114 files changed
+26614 -621

No files matched your search

+2 -2
View File
@@ -31,10 +31,10 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set.
| `attn_decode_h256_gqa6_fp8kv` / `..._bf16kv` | the same geometry, split-KV, `q_len * gqa` ≤ 64 |
| `attn_decode_h256_gqa6_scratch_bytes` / `attn_decode_h128_gqa4_scratch_bytes` | bytes of split-KV scratch a launch needs; ask before allocating, since the split count is chosen from the geometry |
| `attn_vit_h72_bf16` | dense non-causal vision-encoder attention, head_dim 72 native, varlen over images |
| `gdn_conv_prep_w4_h128_bf16` | the GDN prefill preamble in one kernel: causal conv (width 4, silu, with its state cache), q/k/v split, qk l2norm, gating and the per-chunk gate cumsum |
| `gdn_conv_prep_w4_h128_bf16` / `..._f32wgt` | the GDN prefill preamble in one kernel: causal conv (width 4, silu, with its state cache), q/k/v split, qk l2norm, gating and the per-chunk gate cumsum |
| `gdn_kkt_solve_k128_c64_bf16` | `A = (I + strict_lower(diag(beta) K K^T e^dg))^-1` per chunk of 64: the gram and its triangular inverse, without the fp32 gram reaching memory |
| `gdn_chunk_scan_k128_v128_c64_bf16` | gated-delta-net chunked scan: WY recompute, state recurrence and output in one kernel; head_k 128, head_v 128, chunk 64 |
| `gdn_conv_update_w4_h128_bf16` | the same convolution for a decode step: a rolling speculative window over the conv state cache, writing q/k/v directly |
| `gdn_conv_update_w4_h128_bf16` / `..._f32wgt` | the same convolution for a decode step: a rolling speculative window over the conv state cache, writing q/k/v directly |
| `gdn_recurrent_update_k128_v128_bf16_fp32state` | the decode-time recurrent delta-rule update against the paged fp32 state cache, gating and qk l2norm included |
| `gdn_gated_rmsnorm_h128_bf16` | gated RMS norm over a 128-channel row, `out = rms(x) . w . act(z)` |
| `ar_oneshot_2rank_exact` | one-shot push all-reduce over P2P, exactly 2 ranks, exact bf16/fp16/fp32 |
+24 -2
View File
@@ -220,6 +220,16 @@ int r4d_gdn_conv_prep_w4_h128_bf16(
const void* A_log, const void* dt_bias, void* q, void* k, void* v, void* g, void* beta,
const void* cu, int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr,
void* stream);
// The same with an f32 `wgt`, as a GGUF stores ssm_conv1d. Every other operand is as above, and
// a bf16-representable weight gives the same bytes.
int r4d_gdn_conv_prep_w4_h128_bf16_f32wgt(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
const void* has_init, int hi_i32,
const void* a, const void* b, long ab_stride, int ab_is_bf16,
const void* A_log, const void* dt_bias, void* q, void* k, void* v, void* g, void* beta,
const void* cu, int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr,
void* stream);
// The same convolution for a decode step over a speculative window. The state cache is a rolling
// buffer of width-1 + num_spec entries read at the slot the last accepted token left; q / k / v
@@ -229,6 +239,12 @@ int r4d_gdn_conv_update_w4_h128_bf16(
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream);
// The same with an f32 `wgt`, as for the prefill convolution.
int r4d_gdn_conv_update_w4_h128_bf16_f32wgt(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream);
// The gated RMS norm on the layer's output: out = rms(x) . w . act(z), one row per (token, head).
// Replaces FLA's rmsnorm_fn. act: 0 = silu/swish, 1 = sigmoid. Prefill only; the decode kernel
@@ -685,6 +701,12 @@ void r4d_moe_gemm_pin_down_dec(int pin);
// (refused likewise, and below 512 rows, whose scratch is not sized for their weight planes).
// All bit-identical; r4d_selftest compares their bytes.
void r4d_hc_read_pin_prefill(int form);
// Test hook: pins the gated residual read's decode kernels. 0 is the launcher's rule (kernels A and
// B as one grid at one to seven rows where the per-stream counters exist, the tiled up-mix's K
// passes pipelined from eight rows), 1 the kernels the rule replaced (A, then the up-mix in a second
// launch; the tiled up-mix's passes in sequence). Bit-identical; r4d_selftest compares their bytes
// and --perfhc times both.
void r4d_hc_read_pin_decode(int form);
// Test hook: pins the MLA matrix row's key load. 0 is the launcher's rule (sixteen-byte vectors
// wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to.
// Bit-identical; r4d_selftest compares them and --perfmla times both.
@@ -791,8 +813,8 @@ int r4d_gate_quant_fp8(long g, long x, long y, long q, long s, int M, int n, in
// on the norm's load. IPC arguments are r4d_ar_oneshot_2rank_exact's; `nblocks` is clamped to M
// because a block owns whole rows, and `x` takes no pitch because it is also the message. Like the
// int8 twin r4d_ar_ln_had_quant_i8 it has two wires: `wire` 0 is the exact bf16 payload, 6 the
// rotated 6-bit one. Wire 6 needs `n` to be a multiple of r4d_ar_rmsnorm_quant_fp8_chunk_elems()
// so a chunk never straddles a row.
// rotated 6-bit one. Wire 6 needs `n` to be a multiple of 64 (a group never straddles a row); a
// row that is not whole r4d_ar_rmsnorm_quant_fp8_chunk_elems() chunks pads its last one with zeros.
int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
+14 -5
View File
@@ -351,11 +351,13 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen));
/* This rank's own packed copy, for the rotated 6-bit wire only: the reduce must fold exactly
* the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the scales 1/64, so half
* the message plus a thirty-second plus a page is ample. */
* the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the f32 scales 1/32 of
* it, laid out from half the slot; a row padded to whole 512-element chunks
* (ar_rmsnorm_quant_fp8) adds up to 7 groups' scales a row, so the scales get a sixteenth
* (enough for any row of 512 or more) plus a page. ar_rmsnorm_quant checks the fit. */
if (in->dtype != 2) {
R4D_TRY("ar_ipc_alloc(locpack)",
lp = r4d_ar_ipc_alloc(in->slot_bytes / 2 + in->slot_bytes / 32 + 4096, 0,
lp = r4d_ar_ipc_alloc(in->slot_bytes / 2 + in->slot_bytes / 16 + 4096, 0,
handle, &hlen));
}
@@ -1353,11 +1355,18 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
if (wire != 0 && wire != 6) return RAD_E_INVAL;
if (wire == 6) {
const int ce = r4d_ar_rmsnorm_quant_fp8_chunk_elems();
if (ce <= 0 || K % ce) return RAD_E_SHAPE;
/* Whole 64-element groups a row; the last 512-element chunk may be partial (padded). */
if (ce <= 0 || K % 64) return RAD_E_SHAPE;
/* This rank's packed-half side buffer exists for every bf16 instance; missing means a
* broken init. */
if (!in->locpack) return RAD_E_STATE;
if (wpo) return RAD_E_UNSUPPORTED; // the post-norm is the exact wire's only
/* The padded message must fit: payload (3/4 byte an element) in the peer slot's half and
* in locpack's, the bf16 scales in the slot's other half, the f32 ones in locpack after
* half the slot (its allocation: a sixteenth of the slot plus a page). */
const long long chunks = M * ((K + ce - 1) / ce), groups = chunks * (ce / 64);
if (chunks * (ce * 6 / 8) > in->slot_bytes / 2 || groups * 2 > in->slot_bytes / 2 ||
groups * 4 > in->slot_bytes / 16 + 4096)
return RAD_E_SHAPE;
}
R4dArCfg cfgv;
+54 -18
View File
@@ -310,6 +310,10 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
// Rotation and amax close over a 64-element group, so the bytes are identical; the chunk size only
// sets ownership. A chunk may not straddle a row (both ranks must agree on a block's bytes), and a
// wave owns a whole chunk, so a smaller chunk employs more waves (see r4d_ar_ln_had_quant_i8.hip).
// A row of whole 64-element groups that is not whole chunks (TranslateGemma's 5376 = 10.5 chunks)
// ends in a partial chunk: its missing groups go out as zeros and are not stored back. Every real
// group is the same 64 elements as in the flat message, so its bytes, and the sum, are the
// standalone wire's; with whole chunks the mapping is the flat one.
//
// The reduced row goes back to global `x`, not LDS: unlike the int8 twin this norm needs no
// in-place rotation, and pass two re-reads the row L1-hot as the standalone norm does.
@@ -372,11 +376,16 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) {
// POST: a sandwich-norm junction (Gemma 3): the reduced sum is post-normed against `wp` before the
// residual add, `v = bf16(sum * s1 * (wp + wadd))` with s1 the sum's own rms, as rmsnorm_quant_i8's
// POST computes it. `x` still receives the reduced sum. Exact wire and a residual only.
// POST computes it. `x` still receives the reduced sum. Either wire (the compressed one has already
// stored the sum into `x`); a residual only.
//
// HI8: ar_rmsnorm_had_quant_i8g, pass two in norm_quant_row's rotated int8 form. The reduction and
// the norm are untouched, so `x`, the residual and `y` are ar_rmsnorm_quant_fp8's bytes.
template <bool WF32, bool RES, uint32_t THR, int WIRE, bool POST = false, bool HI8 = false>
// PAD (wire 6 only): the row is whole 64-element groups but not whole chunks, so its last chunk is
// padded and a chunk's elements are found by (row, chunk in row). Without it the flat index is the
// element offset, the code a row of whole chunks has always run.
template <bool WF32, bool RES, uint32_t THR, int WIRE, bool POST = false, bool HI8 = false,
bool PAD = false>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp,
@@ -393,7 +402,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb);
/* Chunks per row and this block's window into the global chunk numbering, derived identically
* on both ranks from (M, nb, n). */
const int cpr = WIRE ? (int)(n / ARQ_CE) : 0;
const int cpr = WIRE ? (int)(PAD ? (n + ARQ_CE - 1) / ARQ_CE : n / ARQ_CE) : 0;
const int gpr = (int)(n / ARQ_GROUP); /* the real groups a row has; the rest of its last chunk pads */
(void)gpr;
const int c00 = r0 * cpr, cpb = (r1 - r0) * cpr;
const uint32_t lane = tid & (ARQ_WV - 1), wave = tid / ARQ_WV;
const int lig = (int)(lane & (ARQ_LPG - 1)), gw = (int)(lane / ARQ_LPG);
@@ -430,8 +441,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
} else {
/* Rotate, amax, quantise and pack straight into the peer's slot. A wave owns whole chunks,
* so every lane emits ARQ_NWORD dwords per chunk and the flush is lane-uniform. No group is
* partial (n is whole chunks, a block owns whole rows), so the standalone kernel's `live`
* guard is unnecessary and every cross-lane stage is fully active. */
* partial (n is whole groups, a block owns whole rows), so every cross-lane stage is fully
* active; a group past the row's end (a partial last chunk) packs zeros. */
for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) {
const int c = c00 + ci;
unsigned int acc[ARQ_NWORD];
@@ -440,10 +451,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
#pragma unroll
for (int t = 0; t < ARQ_ITERS; ++t) {
const int g = c * ARQ_CG + t * ARQ_GPW + gw;
const long off = (long)g * ARQ_GROUP + (long)lig * ARQ_EPL;
float v[ARQ_EPL];
if constexpr (PAD) {
const int cr = c / cpr, gr = (c - cr * cpr) * ARQ_CG + t * ARQ_GPW + gw;
const bool live = gr < gpr;
const long off = (long)cr * n + (long)gr * ARQ_GROUP + (long)lig * ARQ_EPL;
#pragma unroll
for (int i = 0; i < ARQ_EPL; ++i) v[i] = bf2f(x[off + i]);
for (int i = 0; i < ARQ_EPL; ++i) v[i] = live ? bf2f(x[off + i]) : 0.0f;
} else {
const long off = (long)g * ARQ_GROUP + (long)lig * ARQ_EPL;
#pragma unroll
for (int i = 0; i < ARQ_EPL; ++i) v[i] = bf2f(x[off + i]);
}
arq_wht(v, lig);
float a = 0.0f;
#pragma unroll
@@ -590,9 +609,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
+ (float)((int)(lsy & ARQ_MASK) + ARQ_QMIN) * lsc;
}
arq_wht(v, lig);
const long off = (long)g * ARQ_GROUP + (long)lig * ARQ_EPL;
if constexpr (PAD) {
const int cr = c / cpr, gr = (c - cr * cpr) * ARQ_CG + gl;
if (gr < gpr) {
const long off = (long)cr * n + (long)gr * ARQ_GROUP + (long)lig * ARQ_EPL;
#pragma unroll
for (int i = 0; i < ARQ_EPL; ++i) x[off + i] = f2bf(v[i]);
for (int i = 0; i < ARQ_EPL; ++i) x[off + i] = f2bf(v[i]);
}
} else {
const long off = (long)g * ARQ_GROUP + (long)lig * ARQ_EPL;
#pragma unroll
for (int i = 0; i < ARQ_EPL; ++i) x[off + i] = f2bf(v[i]);
}
}
}
/* Pass two reads all of `x`'s row; each wave wrote only its own chunks. */
@@ -610,13 +638,14 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
(void)pr;
float ss = 0.0f;
if constexpr (POST && WIRE == 0 && RES) {
if constexpr (POST && RES) {
/* Pass one reduces and takes the sum's sum of squares; pass two post-norms it, adds it
* into the stream and takes the stream's. Each thread reads back only its own columns. */
float s1s = 0.0f;
for (uint32_t i = tid; i < n; i += THR) {
const uint16_t a = f2bf(bf2f(xr[i]) + bf2f(pr[i]));
xr[i] = a;
uint16_t a;
if constexpr (WIRE == 0) { a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a; }
else { a = xr[i]; }
const float av = bf2f(a);
s1s += av * av;
}
@@ -862,7 +891,7 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long wp, bool hi8) {
if (!x || !w || !q || !s) return -1;
if (wp && (!res || wire != 0)) return -10; // a post-norm needs the stream and the exact wire
if (wp && !res) return -10; // a post-norm needs the stream
if (hi8 && wp) return -11;
if (hi8 && (n % (int)kGroup)) return -12;
if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1;
@@ -871,8 +900,9 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
// four columns (see norm_quant_row).
if (n % 8) return -5;
if (wire != 0 && wire != 6) return -7;
// A chunk may not straddle a row, or the ranks would disagree about a block's bytes.
if (wire == 6 && (n % ARQ_CE)) return -8;
// A group may not straddle a row, or the ranks would disagree about a block's bytes; a row's
// last chunk may be partial (its missing groups go out as zeros).
if (wire == 6 && (n % ARQ_GROUP)) return -8;
if (wire == 6 && (!loc_pack || loc_scale_off <= 0)) return -9;
if (!r_ld) r_ld = n;
if (!y_ld) y_ld = n;
@@ -887,8 +917,9 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
// The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order).
const int thr = nthreads ? nthreads : r4d_act_threads(M, n);
if (thr != 256 && thr != 512 && thr != 1024) return -6;
#define R4D_ARQ_H(wf, rs, T, W, PO, H) \
hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel<wf, rs, T, W, PO, H>), dim3((uint32_t)nb), \
const bool pad = wire == 6 && (n % ARQ_CE) != 0;
#define R4D_ARQ_HP(wf, rs, T, W, PO, H, PD) \
hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel<wf, rs, T, W, PO, H, PD>), dim3((uint32_t)nb), \
dim3(T), 0, \
(hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, (const void*)w, \
(const void*)wp, \
@@ -898,12 +929,16 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
(long)loc_scale_off, M, (uint32_t)n, \
(uint32_t)nkb, eps, wadd, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
(uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw)
#define R4D_ARQ_H(wf, rs, T, W, PO, H) \
do { if (pad) R4D_ARQ_HP(wf, rs, T, W, PO, H, (W == 6)); \
else R4D_ARQ_HP(wf, rs, T, W, PO, H, false); } while (0)
#define R4D_ARQ_P(wf, rs, T, W, PO) R4D_ARQ_H(wf, rs, T, W, PO, false)
#define R4D_ARQ_T(wf, rs, T, W) \
do { if (hi8) R4D_ARQ_H(wf, rs, T, W, false, true); \
else R4D_ARQ_P(wf, rs, T, W, false); } while (0)
#define R4D_ARQ_W(wf, rs, T) \
do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \
do { if (wire == 6 && rs && wp) R4D_ARQ_P(wf, rs, T, 6, true); \
else if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \
else if (rs && wp) R4D_ARQ_P(wf, rs, T, 0, true); \
else R4D_ARQ_T(wf, rs, T, 0); } while (0)
#define R4D_ARQ(wf, rs) \
@@ -917,6 +952,7 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
#undef R4D_ARQ_T
#undef R4D_ARQ_P
#undef R4D_ARQ_H
#undef R4D_ARQ_HP
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+1 -1
View File
@@ -10,7 +10,7 @@
/* Every `const void*` libr4d takes has one element type, cast inside the kernel (e.g.
* r4d_gdn_conv_prep_w4_h128_bf16 reads `wgt` as bf16 and `A_log` as f32); the signature does not
* say so. A plugin declaring `ssm_conv1d.weight` or the `gdn_kkt` buffer as f32 would be read as
* say so. A plugin declaring the `gdn_kkt` buffer as f32 would be read as
* bf16 on the device, while libref (which honours each operand's dtype) stays correct, so the bug
* would show only on the device path. The shim therefore checks dtypes by name (spec §2.1). */
static inline int r4d_dt(const RadTensor* t, uint32_t want) {
+13
View File
@@ -4,9 +4,22 @@
// A single definition keeps the fold byte-identical to the standalone path: the reciprocal form
// below changes the last bit of some bf16 outputs.
#pragma once
#include "r4d_gdn_wmma.h"
#define R4D_GDN_CONV_W 4 // conv width; the state holds R4D_GDN_CONV_W - 1 taps of history
// The weight is bf16 from a checkpoint and f32 from a GGUF, which keeps ssm_conv1d unquantised.
// cp_taps is a channel's taps as one vector load; cp_tap widens one tap to f32, exactly for
// either type.
template <typename WT> struct cp_vec4;
template <> struct cp_vec4<unsigned short> { using T = ushort4; };
template <> struct cp_vec4<float> { using T = float4; };
template <typename WT> using cp_taps = typename cp_vec4<WT>::T;
static_assert(R4D_GDN_CONV_W == 4, "cp_taps holds a channel's taps in one four-wide vector");
__device__ __forceinline__ float cp_tap(unsigned short w) { return bf2f(w); }
__device__ __forceinline__ float cp_tap(float w) { return w; }
// The result is rounded to bf16 immediately, so an IEEE-exact divide buys nothing: v_rcp_f32 is
// 1 ULP (~1e-7 relative) against bf16's 2^-8 quantum. The exact form is ~10 dependent instructions
// (v_div_scale, v_rcp, Newton, v_div_fmas, v_div_fixup); this is two. The conv update runs four
+80 -22
View File
@@ -72,10 +72,10 @@ __device__ __forceinline__ bool r4d_has_init(const void* p, int i32, int n) {
return i32 ? ((const int*)p)[n] != 0 : ((const unsigned char*)p)[n] != 0;
}
template <int HPB, int ABF16>
template <int HPB, int ABF16, typename WT>
__global__ __launch_bounds__(HPB * 32)
void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
const unsigned short* __restrict__ wgt,
const WT* __restrict__ wgt,
const unsigned short* __restrict__ bias,
unsigned short* __restrict__ cstate,
long cs_seq, long cs_dim, long cs_tok,
@@ -150,7 +150,7 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
#pragma unroll
for (int c = 0; c < CP_DPL; ++c) {
#pragma unroll
for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(wgt[(size_t)(d0 + c) * CP_W + i]);
for (int i = 0; i < CP_W; ++i) wt[i][c] = cp_tap(wgt[(size_t)(d0 + c) * CP_W + i]);
bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f;
}
@@ -241,7 +241,8 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
}
}
extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
template <typename WT>
static int cp_prep_launch(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
const void* has_init, int hi_i32,
@@ -256,8 +257,8 @@ extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
const int nchunk_ub = (T + CP_BT - 1) / CP_BT + N;
dim3 grid(nchunk_ub, units / hpb), blk(hpb * 32);
#define CP_LAUNCH(P, AB) \
hipLaunchKernelGGL((r4d_gdn_conv_prep_kernel<P, AB>), grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)x, xpitch, (const unsigned short*)wgt, \
hipLaunchKernelGGL((r4d_gdn_conv_prep_kernel<P, AB, WT>), grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)x, xpitch, (const WT*)wgt, \
(const unsigned short*)bias, (unsigned short*)cstate, \
cs_seq, cs_dim, cs_tok, (const int*)cache_idx, ci_stride, \
has_init, hi_i32, a, b, ab_stride, \
@@ -277,16 +278,44 @@ extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
return (int)hipGetLastError();
}
extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
const void* has_init, int hi_i32,
const void* a, const void* b, long ab_stride, int ab_is_bf16, const void* A_log,
const void* dt_bias, void* q, void* k, void* v, void* g, void* beta, const void* cu,
int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr, void* stream)
{
return cp_prep_launch<unsigned short>(x, xpitch, wgt, bias, cstate, cs_seq, cs_dim, cs_tok,
cache_idx, ci_stride, has_init, hi_i32, a, b, ab_stride,
ab_is_bf16, A_log, dt_bias, q, k, v, g, beta, cu, N, T, H,
Hg, K, V, width, softplus_thr, stream);
}
extern "C" int r4d_gdn_conv_prep_w4_h128_bf16_f32wgt(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
const void* has_init, int hi_i32,
const void* a, const void* b, long ab_stride, int ab_is_bf16, const void* A_log,
const void* dt_bias, void* q, void* k, void* v, void* g, void* beta, const void* cu,
int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr, void* stream)
{
return cp_prep_launch<float>(x, xpitch, wgt, bias, cstate, cs_seq, cs_dim, cs_tok, cache_idx,
ci_stride, has_init, hi_i32, a, b, ab_stride, ab_is_bf16, A_log,
dt_bias, q, k, v, g, beta, cu, N, T, H, Hg, K, V, width,
softplus_thr, stream);
}
// ---------------------------------------------------------------------------------------------
// Decode-time convolution. Same filter, but a step's tokens are a speculative window and the
// state cache is a rolling buffer of width-1 + num_spec entries: a step reads its window starting
// at the slot the last accepted token left, and rewrites the buffer shifted by one. Writes q, k
// and v in their own layouts (no torch.cat for the recurrent kernel).
// ---------------------------------------------------------------------------------------------
template <int HPB>
template <int HPB, typename WT>
__global__ __launch_bounds__(HPB * 32)
void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitch,
const unsigned short* __restrict__ wgt,
const WT* __restrict__ wgt,
const unsigned short* __restrict__ bias,
unsigned short* __restrict__ cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max,
@@ -312,15 +341,14 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc
const int unit = blockIdx.y * HPB + warp;
const int d0 = unit * CP_HD + lane * CP_DPL;
// A channel's weights are CP_W contiguous shorts: one vector load per channel.
static_assert(CP_W == 4, "the weight load reads a channel's taps as one ushort4");
// A channel's weights are CP_W contiguous elements: one vector load per channel.
float wt[CP_W][CP_DPL], bs[CP_DPL];
#pragma unroll
for (int c = 0; c < CP_DPL; ++c) {
const ushort4 w4 = *(const ushort4*)(wgt + (size_t)(d0 + c) * CP_W);
const unsigned short* ws = (const unsigned short*)&w4;
const cp_taps<WT> w4 = *(const cp_taps<WT>*)(wgt + (size_t)(d0 + c) * CP_W);
const WT* ws = (const WT*)&w4;
#pragma unroll
for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(ws[i]);
for (int i = 0; i < CP_W; ++i) wt[i][c] = cp_tap(ws[i]);
bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f;
}
@@ -428,7 +456,8 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc
#undef CU_TOKEN_BODY
}
extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
template <typename WT>
static int cu_update_launch(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
@@ -443,8 +472,8 @@ extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
while (hpb > 1 && (long)N * (units / hpb) < 256) hpb >>= 1;
dim3 grid(N, units / hpb), blk(hpb * 32);
#define CU_LAUNCH(P) \
hipLaunchKernelGGL((r4d_gdn_conv_update_kernel<P>), grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)x, xpitch, (const unsigned short*)wgt, \
hipLaunchKernelGGL((r4d_gdn_conv_update_kernel<P, WT>), grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)x, xpitch, (const WT*)wgt, \
(const unsigned short*)bias, (unsigned short*)cstate, cs_seq, cs_dim, \
cs_tok, state_len_max, (const int*)cache_idx, ci_stride, \
(const int*)num_accepted, (unsigned short*)q, (unsigned short*)k, \
@@ -459,6 +488,28 @@ extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
return (int)hipGetLastError();
}
extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream)
{
return cu_update_launch<unsigned short>(x, xpitch, wgt, bias, cstate, cs_seq, cs_dim, cs_tok,
state_len_max, cache_idx, ci_stride, num_accepted, q,
k, v, cu, N, H, Hg, K, V, width, max_query_len, stream);
}
extern "C" int r4d_gdn_conv_update_w4_h128_bf16_f32wgt(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream)
{
return cu_update_launch<float>(x, xpitch, wgt, bias, cstate, cs_seq, cs_dim, cs_tok,
state_len_max, cache_idx, ci_stride, num_accepted, q, k, v, cu,
N, H, Hg, K, V, width, max_query_len, stream);
}
// ============================================================== the plugin ABI entry points
// Shared operand helpers: r4d_gdn_args.h. Operand enums use an OPD_ prefix because CP_W and CP_ST
// are already kernel constants in this unit.
@@ -535,12 +586,16 @@ extern "C" int r4d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) {
if (tb->dtype != ta->dtype) return R4D_NO(RAD_E_DTYPE);
if (!ab_is_bf16 && ta->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
/* bf16 x, weights, conv state and q/k/v; fp32 A_log, dt_bias, g and beta. */
R4D_DT(x, RAD_BF16); R4D_DT(w, RAD_BF16); R4D_DT(cst, RAD_BF16);
/* bf16 x, conv state and q/k/v; bf16 or f32 weights (r4d_gdn_conv_tap.h); fp32 A_log,
* dt_bias, g and beta. */
R4D_DT(x, RAD_BF16); R4D_DT(cst, RAD_BF16);
R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16);
R4D_DT(alog, RAD_F32); R4D_DT(dtb, RAD_F32); R4D_DT(g, RAD_F32); R4D_DT(beta, RAD_F32);
if (w->dtype != RAD_BF16 && w->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const auto prep = w->dtype == RAD_F32 ? r4d_gdn_conv_prep_w4_h128_bf16_f32wgt
: r4d_gdn_conv_prep_w4_h128_bf16;
return R4D_RAW(r4d_gdn_conv_prep_w4_h128_bf16(
return R4D_RAW(prep(
x->data, (long)xpitch, w->data, b ? b->data : nullptr, cst->data,
(long)cst->stride[0], (long)cst->stride[1], (long)cst->stride[2],
cidx->data, (long)cidx->stride[0], hin ? hin->data : nullptr,
@@ -588,9 +643,12 @@ extern "C" int r4d_rad_gdn_conv_update(const RadArgs* a, RadStream s) {
if (H == 0 || Hg == 0 || H % Hg) return R4D_NO(RAD_E_SHAPE);
if (v->shape[0] != T || k->shape[0] != T) return R4D_NO(RAD_E_SHAPE);
/* bf16 x, weights, conv state and q/k/v, as in the prefill conv. */
R4D_DT(x, RAD_BF16); R4D_DT(w, RAD_BF16); R4D_DT(cst, RAD_BF16);
/* bf16 x, conv state and q/k/v, bf16 or f32 weights, as in the prefill conv. */
R4D_DT(x, RAD_BF16); R4D_DT(cst, RAD_BF16);
R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16);
if (w->dtype != RAD_BF16 && w->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const auto update = w->dtype == RAD_F32 ? r4d_gdn_conv_update_w4_h128_bf16_f32wgt
: r4d_gdn_conv_update_w4_h128_bf16;
const int width = (int)r4d_geti_or(a, "conv_width", 4);
/* state_len_max and max_query_len describe one window, so only one is free. The state cache
@@ -606,7 +664,7 @@ extern "C" int r4d_rad_gdn_conv_update(const RadArgs* a, RadStream s) {
const long long mql = state_len_max - (width - 2);
if (width < 2 || mql < 1) return R4D_NO(RAD_E_SHAPE);
return R4D_RAW(r4d_gdn_conv_update_w4_h128_bf16(
return R4D_RAW(update(
x->data, (long)xpitch, w->data, b ? b->data : nullptr, cst->data,
(long)cst->stride[0], (long)cst->stride[1], (long)cst->stride[2],
(int)state_len_max, sidx->data, (long)sidx->stride[0],
@@ -37,6 +37,7 @@
#include <cstring>
#include <map>
#include <mutex>
#include <type_traits>
#include <utility>
#define RU_K 128 // head_k
@@ -187,9 +188,11 @@ __device__ __forceinline__ float ru_act(float z, int kind) {
// channels and resets the counter (no waiting). A value head's v channels have one reader and are
// rewritten by it. Two launches sharing a counter block must not overlap; blocks are keyed on
// (stream, output), as split_ctr in r4d_gemm_fp8a8.hip.
//
// CV is also the weight's type: 1 bf16, 2 f32, read as gdn_conv_update reads it.
struct RuConv {
const unsigned short* x; long xpitch; // the projection's [q | k | v] columns, row pitch
const unsigned short* w; // [conv_dim, R4D_GDN_CONV_W]
const void* w; // [conv_dim, R4D_GDN_CONV_W], bf16 or f32 (CV)
const unsigned short* b; // [conv_dim] or null
unsigned short* cs; // the conv state cache
long cs_seq, cs_dim, cs_tok;
@@ -293,13 +296,15 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
const int off = naccept ? naccept[n] - 1 : 0;
const int ca = tid < RU_K ? hk * RU_K + tid : (Hg + hk) * RU_K + (tid - RU_K);
const int cb = (2 * Hg + hv) * RU_V + tid;
using CWT = std::conditional_t<CV == 2, float, unsigned short>;
const CWT* const cw = (const CWT*)cv.w;
const unsigned short* xr = cv.x + (size_t)bos * cv.xpitch;
#pragma unroll
for (int t = 0; t < RU_CVT; ++t)
if (t < T) cxa[t] = xr[(size_t)t * cv.xpitch + ca];
{
const ushort4 w4 = *(const ushort4*)(cv.w + (size_t)ca * CW);
cwa[0] = bf2f(w4.x); cwa[1] = bf2f(w4.y); cwa[2] = bf2f(w4.z); cwa[3] = bf2f(w4.w);
const cp_taps<CWT> w4 = *(const cp_taps<CWT>*)(cw + (size_t)ca * CW);
cwa[0] = cp_tap(w4.x); cwa[1] = cp_tap(w4.y); cwa[2] = cp_tap(w4.z); cwa[3] = cp_tap(w4.w);
if (cv.b) cba = bf2f(cv.b[ca]);
}
spa = cv.cs + (size_t)cslot * cv.cs_seq + (size_t)ca * cv.cs_dim;
@@ -309,8 +314,8 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
#pragma unroll
for (int t = 0; t < RU_CVT; ++t)
if (t < T) cxb[t] = xr[(size_t)t * cv.xpitch + cb];
const ushort4 w4 = *(const ushort4*)(cv.w + (size_t)cb * CW);
cwb[0] = bf2f(w4.x); cwb[1] = bf2f(w4.y); cwb[2] = bf2f(w4.z); cwb[3] = bf2f(w4.w);
const cp_taps<CWT> w4 = *(const cp_taps<CWT>*)(cw + (size_t)cb * CW);
cwb[0] = cp_tap(w4.x); cwb[1] = cp_tap(w4.y); cwb[2] = cp_tap(w4.z); cwb[3] = cp_tap(w4.w);
if (cv.b) cbb = bf2f(cv.b[cb]);
spb = cv.cs + (size_t)cslot * cv.cs_seq + (size_t)cb * cv.cs_dim;
#pragma unroll
@@ -864,7 +869,7 @@ static unsigned int* ru_conv_ctr(RadStream s, const void* out) {
// The recurrent update with gdn_conv_update folded in, decode shape only (bf16 a/b, fused row
// norm, one workgroup per (sequence, value head)). State contract, non-temporal choice and
// factor-block bounds are as in ru_update_launch.
// factor-block bounds are as in ru_update_launch. `w_f32` is the conv weight's type.
static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* b, long ab_stride,
const void* A_log, const void* dt_bias, void* state,
long st_slot, long st_head, void* o, void* oq, void* os,
@@ -872,7 +877,7 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
long sidx_stride, const void* nacc, const void* z,
long z_pitch, const void* nw, float neps, int nact, int N,
int H, int Hg, float scale, float thr, int state_fp16,
RadStream stream, int oq_i8, bool anc) {
RadStream stream, int oq_i8, bool anc, bool w_f32) {
if (anc && sidx_stride < 6) return RAD_E_SHAPE;
if (anc && sidx_stride * RU_FSTR > st_head) return RAD_E_SHAPE;
const int sdt = state_fp16 ? 1 : 0;
@@ -880,11 +885,11 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
const long flood = (long)N * slots_written * st_slot * (sdt ? 2 : 4);
const bool nt = flood <= (long)RU_NT_MB * 1024 * 1024;
const dim3 grid(N, H, 1), blk(RU_V * 2);
#define RC_LAUNCH(NTC, ANCC, SDTC) \
do { if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC); else RC_LAUNCH_NM(1, NTC, ANCC, SDTC); } \
while (0)
#define RC_LAUNCH_NM(NM, NTC, ANCC, SDTC) \
hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, 1>), \
#define RC_LAUNCH(NTC, ANCC, SDTC, CVC) \
do { if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC, CVC); \
else RC_LAUNCH_NM(1, NTC, ANCC, SDTC, CVC); } while (0)
#define RC_LAUNCH_NM(NM, NTC, ANCC, SDTC, CVC) \
hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, CVC>), \
grid, blk, 0, (hipStream_t)stream, nullptr, nullptr, nullptr, a, b, \
ab_stride, (const float*)A_log, (const float*)dt_bias, \
(ru_state<SDTC>::T*)state, st_slot, st_head, (unsigned short*)o, \
@@ -892,11 +897,14 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
(const int*)sidx, sidx_stride, (const int*)nacc, \
(const unsigned short*)z, z_pitch, (const float*)nw, neps, nact, H, Hg, \
scale, thr, cv)
#define RC_PICKNT(ANCC, SDTC) \
do { if (nt) RC_LAUNCH(1, ANCC, SDTC); else RC_LAUNCH(0, ANCC, SDTC); } while (0)
#define RC_PICKANC(SDTC) \
do { if (anc) RC_PICKNT(1, SDTC); else RC_PICKNT(0, SDTC); } while (0)
if (sdt) RC_PICKANC(1); else RC_PICKANC(0);
#define RC_PICKNT(ANCC, SDTC, CVC) \
do { if (nt) RC_LAUNCH(1, ANCC, SDTC, CVC); else RC_LAUNCH(0, ANCC, SDTC, CVC); } while (0)
#define RC_PICKANC(SDTC, CVC) \
do { if (anc) RC_PICKNT(1, SDTC, CVC); else RC_PICKNT(0, SDTC, CVC); } while (0)
#define RC_PICKSDT(CVC) \
do { if (sdt) RC_PICKANC(1, CVC); else RC_PICKANC(0, CVC); } while (0)
if (w_f32) RC_PICKSDT(2); else RC_PICKSDT(1);
#undef RC_PICKSDT
#undef RC_PICKANC
#undef RC_PICKNT
#undef RC_LAUNCH
@@ -1082,9 +1090,10 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s)
const long long ab_stride = r4d_row_pitch(ta);
if (ab_stride < 0 || r4d_row_pitch(tb) != ab_stride) return R4D_NO(RAD_E_STRIDE);
R4D_DT(x, RAD_BF16); R4D_DT(cw, RAD_BF16); R4D_DT(cb, RAD_BF16); R4D_DT(cst, RAD_BF16);
R4D_DT(x, RAD_BF16); R4D_DT(cb, RAD_BF16); R4D_DT(cst, RAD_BF16);
R4D_DT(ta, RAD_BF16); R4D_DT(tb, RAD_BF16); R4D_DT(o, RAD_BF16); R4D_DT(z, RAD_BF16);
R4D_DT(alog, RAD_F32); R4D_DT(dtb, RAD_F32); R4D_DT(nw, RAD_F32);
if (cw->dtype != RAD_BF16 && cw->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (state->dtype != RAD_F32 && state->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE);
if (oq) {
if (oq->dtype != RAD_F8E4M3 && oq->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
@@ -1113,7 +1122,7 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s)
RuConv cv{};
cv.x = (const unsigned short*)x->data; cv.xpitch = (long)xpitch;
cv.w = (const unsigned short*)cw->data; cv.b = cb ? (const unsigned short*)cb->data : nullptr;
cv.w = cw->data; cv.b = cb ? (const unsigned short*)cb->data : nullptr;
cv.cs = (unsigned short*)cst->data;
cv.cs_seq = (long)cst->stride[0]; cv.cs_dim = (long)cst->stride[1];
cv.cs_tok = (long)cst->stride[2];
@@ -1128,5 +1137,5 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s)
os ? (long)r4d_row_pitch(os) : 0, cu->data, sidx->data, (long)sidx->stride[0],
nacc ? nacc->data : nullptr, z->data, (long)z_row, nw->data, neps, nact, N, (int)H,
(int)Hg, scale, thr, state->dtype == RAD_F16 ? 1 : 0, s,
oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0);
oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0, cw->dtype == RAD_F32);
}
+138 -33
View File
@@ -151,19 +151,30 @@ constexpr uint32_t kSplitThinCap = 64u;
* tuned at (the NT accumulators and K-step unroll are sized against it), so a compiler release
* cannot change occupancy. Shapes with one or two waves per block are LDS-bound and use that
* count. */
constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bool i8) {
constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bool i8,
bool gated = false) {
if (mw == 1u) return nt == 1u ? 8u : nt == 2u ? 4u : nt == 3u ? 3u : 2u;
if (mw == 2u) return nt == 1u ? 12u : nt == 2u ? 8u : nt == 3u ? 5u : 4u;
if (!i8) {
if (fk == 128u)
return nt == 1u ? 16u : nt == 2u ? (full ? 16u : 12u) : nt == 3u ? 10u
: (full && mw >= 8u) ? 10u : 9u;
return nt == 1u ? 12u : nt == 2u ? 10u : nt == 3u ? 9u : mw == 4u ? 7u : 8u;
/* The gated three-tile form at 8, not 9. At 9 waves' 168 registers its epilogue spilled
* 57 at the full tile (48 rows), which ran gate_up 51 % slower than 56 rows, and 10 below
* it, 70 with the LDS-staged scales. 8 waves leave 192, where it spills 9 and 10. The gated
* form is always MW 16, four waves a SIMD a block, so 8 and 9 both hold two blocks a WGP:
* no occupancy is lost. */
return nt == 1u ? 12u : nt == 2u ? 10u : nt == 3u ? (gated ? 8u : 9u)
: mw == 4u ? 7u : 8u;
}
if (fk == 128u)
return nt == 1u ? 16u : nt == 2u ? (full ? 10u : 12u) : nt == 3u ? (full ? 9u : 10u)
: full ? 7u : 9u;
if (nt == 1u) return 12u;
/* 10, not 12. The fold's LDS-staged scales (gemm_fp8a8_kernel) need a few more
* registers than 12 waves' 120 leave, and spilled. gfx12 allocates registers 24 at a time, so
* 11 waves leave 120 as well and 10 is the next step (144). No decode shape puts more than 8 of
* these waves on a SIMD, so the lower pin costs no occupancy. */
if (nt == 1u) return 10u;
if (nt == 2u) return full ? 9u : mw == 4u ? 9u : 10u;
if (nt == 3u) return full ? (mw == 16u ? 8u : 7u) : (mw == 4u ? 8u : 9u);
return full ? (mw == 4u ? 5u : 6u) : (mw == 4u ? 7u : 8u);
@@ -252,10 +263,6 @@ __device__ __forceinline__ void gemm_fp8a8_body(
const uint32_t sn = tid / kTPR, sk = (tid % kTPR) * kSeg;
// The B rows this lane owns, one per N tile (column `frag_c` of each of its NT accumulators,
// 16 apart). A per-B-row scale must be looked up for each, not just the first.
const uint32_t brow0 = n0 + wn + frag_c(lane);
const uint8_t* bsrc = Bp + (size_t)(n0 + sn) * b_ld + sk;
// A as fragments: a wave owns one 16-row weight tile, so its A operand for 64 k is this lane's
// 32 bytes. `ksuper` is the plane's tile stride; `arow` is out of range only when N is not a
@@ -287,12 +294,76 @@ __device__ __forceinline__ void gemm_fp8a8_body(
afrag + (size_t)(arow * ksuper + st) * r4d_fp8::kTileBytes, alive && st < ksuper);
}
/* The fold's scales are staged through LDS a K tile ahead, beside the B tile. The
* fold loaded them itself, after the next tile's prefetch had been issued; loads return in
* order, so each fold waited for that whole prefetch, twice a tile at FK = 256, and the "one
* tile ahead" overlapped nothing. Now the block's threads each load one weight-scale dword and
* one activation scale of tile c0+FK with its B prefetch (a few each only in the selftest's
* one- and two-wave pins) and store them at the top of the next pass with the B tile, so a fold
* reads LDS. Two registers a thread: holding a tile's scales a lane (8 + 2*NT registers)
* spilled at the decode shapes' register pins. Same values as before: bit-identical. A dead
* wave's fp8 block scale reads as 0 instead of the plane row past the end it used to read; its
* rows are never stored.
*
* A tile holds kFolds = FK / kBlock scale blocks, and the fold at `ks` uses block ks / kBlock
* of its tile. s_ws: I8, each wave's 16 bf16 row scales a block, [MW][kFolds][8] dwords
* (r4d_fp8_layout.cpp's tile-major plane); fp8, each wave's one bf16 block scale,
* [MW][kFolds]. s_as: each B row's f32 scale a block, [kFolds][FN]. */
constexpr uint32_t kFolds = (FK + kBlock - 1) / kBlock;
constexpr uint32_t kWS = I8 ? MW * kFolds * 8u : MW * kFolds;
constexpr uint32_t kAS = kFolds * FN;
constexpr uint32_t kWSPer = (kWS + MW * kWave - 1) / (MW * kWave);
constexpr uint32_t kASPer = (kAS + MW * kWave - 1) / (MW * kWave);
__shared__ __attribute__((aligned(16))) uint32_t s_ws[kWS];
__shared__ float s_as[kAS];
const uint32_t nkb8 = (cols + kBlock - 1) / kBlock;
auto load_ws = [&](uint32_t c, uint32_t i) -> uint32_t {
if (i >= kWS) return 0u;
if constexpr (I8) {
const uint32_t tr = (m0 + (i / (kFolds * 8u)) * 16u) / 16u;
const uint32_t kb = c / kBlock + (i / 8u) % kFolds;
return ((Full || tr * 16u < rows) && kb < nkb8)
? ((const uint32_t*)Sa)[((size_t)tr * nkb8 + kb) * 8u + i % 8u] : 0u;
} else {
const uint32_t w = i / kFolds, kb = c / kBlock + i % kFolds;
const uint32_t wr = GATED ? ((w < kGHalf ? 0u : rows / 2u) + blockIdx.x * (FM / 2u)
+ (w % kGHalf) * 16u)
: (m0 + w * 16u);
return ((Full || wr < rows) && kb < nkb8)
? (uint32_t)((const uint16_t*)Sa)[(size_t)(wr / kBlock) * sa_ld + kb] : 0u;
}
};
auto load_as = [&](uint32_t c, uint32_t i) -> float {
if (i >= kAS) return 0.0f;
const uint32_t tok = n0 + i % FN, kb = c / kBlock + i / FN;
return ((Full || tok < nb) && kb < nkb8) ? ((const float*)Sb)[(size_t)tok * sb_ld + kb]
: 0.0f;
};
uint32_t qws[kWSPer];
float qas[kASPer];
auto load_q = [&](uint32_t c) {
#pragma unroll
for (uint32_t r = 0; r < kWSPer; ++r) qws[r] = load_ws(c, tid + r * MW * kWave);
#pragma unroll
for (uint32_t r = 0; r < kASPer; ++r) qas[r] = load_as(c, tid + r * MW * kWave);
};
load_q(kbeg);
// The B rows this lane owns within the tile, one per N tile (column `frag_c` of each of its NT
// accumulators, 16 apart). A per-B-row scale must be looked up for each, not just the first.
const uint32_t bl0 = wn + frag_c(lane);
for (uint32_t c0 = kbeg; c0 < kend; c0 += FK) {
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
const uint32_t r = sn + p * kRPP;
if (r < FN) stage8_store<FK>(s_b, r, sk, pb[p]);
}
#pragma unroll
for (uint32_t r = 0; r < kWSPer; ++r)
if (tid + r * MW * kWave < kWS) s_ws[tid + r * MW * kWave] = qws[r];
#pragma unroll
for (uint32_t r = 0; r < kASPer; ++r)
if (tid + r * MW * kWave < kAS) s_as[tid + r * MW * kWave] = qas[r];
__syncthreads();
const uint32_t c1 = c0 + FK;
if (c1 < kend) {
@@ -311,6 +382,7 @@ __device__ __forceinline__ void gemm_fp8a8_body(
afrag + (size_t)(arow * ksuper + st) * r4d_fp8::kTileBytes,
alive && st < ksuper);
}
load_q(c1);
}
#pragma unroll
@@ -332,19 +404,16 @@ __device__ __forceinline__ void gemm_fp8a8_body(
// Gating it at the compile-time-known positions is legal and byte-identical but raises
// the register live range of the fold; see libr4d/isa/README.md.
if ((c0 + ks + kK) % kBlock == 0 || c0 + ks + kK >= kend) {
const uint32_t kb = (c0 + ks) / kBlock;
/* This tile's scale block for `ks`, staged with the tile. */
const uint32_t f = ks / kBlock < kFolds ? ks / kBlock : kFolds - 1u;
if constexpr (I8) {
// A is the int8 weight with a bf16 scale per row. A lane's eight accumulator
// slots are eight consecutive rows of one 16-row tile, adjacent in the
// tile-major [N/16][K/128][16] plane: one 16-byte load. B is the activation.
const uint32_t nkb8 = (cols + kBlock - 1) / kBlock;
float wsr[8];
{
const uint32_t tr = wrow0 / 16u;
uint4 w8 = make_uint4(0u, 0u, 0u, 0u);
if (Full || tr * 16u < rows)
w8 = *(const uint4*)((const uint16_t*)Sa +
((size_t)tr * nkb8 + kb) * 16u + (lane >> 4) * 8u);
const uint4 w8 =
*(const uint4*)&s_ws[(wave * kFolds + f) * 8u + (lane >> 4) * 4u];
const uint32_t d[4] = { w8.x, w8.y, w8.z, w8.w };
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
@@ -352,9 +421,7 @@ __device__ __forceinline__ void gemm_fp8a8_body(
}
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t tok = brow0 + j * 16;
const float s = (Full || tok < nb)
? ((const float*)Sb)[(size_t)tok * sb_ld + kb] : 0.0f;
const float s = s_as[f * FN + bl0 + j * 16u];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
out[j][t] += acc_val<I8>(raw[j][t]) * (wsr[t] * s);
@@ -365,14 +432,10 @@ __device__ __forceinline__ void gemm_fp8a8_body(
// A is the weight: one bf16 scale for this wave's 16 rows, which sit in one
// scale row. B is the activation: one f32 scale per (token, 128-column block),
// one per lane per tile.
const float ws =
bscale(((const uint16_t*)Sa)[(size_t)(wrow0 / kBlock) * sa_ld + kb]);
const float ws = bscale((uint16_t)s_ws[wave * kFolds + f]);
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t tok = brow0 + j * 16;
const float s = ws * ((Full || tok < nb)
? ((const float*)Sb)[(size_t)tok * sb_ld + kb]
: 0.0f);
const float s = ws * s_as[f * FN + bl0 + j * 16u];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
out[j][t] += raw[j][t] * s;
@@ -382,8 +445,8 @@ __device__ __forceinline__ void gemm_fp8a8_body(
}
}
}
// Wait until every wave has finished reading before the tile is overwritten. The
// prefetched fragments become current.
// Wait until every wave has finished reading before the tile and its scales are
// overwritten. The prefetched fragments become current.
#pragma unroll
for (uint32_t p = 0; p < kAF; ++p) pf[p] = pfn[p];
__syncthreads();
@@ -583,12 +646,54 @@ __device__ __forceinline__ void gemm_fp8a8_body(
const uint32_t rlo = m0, rhi = min(m0 + FM, rows);
const float* const w0 = (const float*)Y;
uint16_t* const cy = (uint16_t*)C;
for (uint32_t idx = tid; idx < (rhi - rlo) * nb; idx += MW * kWave) {
const uint32_t r = rlo + idx / nb, col = idx % nb;
const size_t o = (size_t)col * rows + r;
float acc = 0.0f;
for (uint32_t z = 0; z < gridDim.z; ++z) acc += w0[(size_t)z * rows * nb + o];
cy[o] = f32_to_bf16(acc);
/* Consecutive threads take consecutive weight rows, which are adjacent in a
* partial plane ([nb][rows]), four rows a thread as one 16-byte load and kFinU quads in
* flight at each z. The loop walked the token index fastest, `rows` floats apart, one
* element a thread at a time: a cache line a load and a round trip each, which at
* N = 512, M = 64 (four columns of blocks finishing 8,192 elements over four planes)
* was most of a 45 us call. Each element is still summed from 0.0f in ascending z:
* bit-identical. */
const uint32_t nr = rhi - rlo;
const size_t zs = (size_t)rows * nb;
if ((rows & 3u) == 0u && (nr & 3u) == 0u && ((uintptr_t)C & 7u) == 0u
&& ((uintptr_t)Y & 15u) == 0u) {
constexpr uint32_t kFinU = 4;
const uint32_t nq = nr / 4u, total = nq * nb;
for (uint32_t b = tid; b < total; b += kFinU * MW * kWave) {
size_t o[kFinU];
float4 acc[kFinU];
#pragma unroll
for (uint32_t u = 0; u < kFinU; ++u) {
const uint32_t idx = b + u * MW * kWave;
o[u] = idx < total ? (size_t)(idx / nq) * rows + rlo + (idx % nq) * 4u : 0u;
acc[u] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
}
for (uint32_t z = 0; z < gridDim.z; ++z) {
float4 v[kFinU];
#pragma unroll
for (uint32_t u = 0; u < kFinU; ++u)
v[u] = b + u * MW * kWave < total ? *(const float4*)(w0 + z * zs + o[u])
: make_float4(0.0f, 0.0f, 0.0f, 0.0f);
#pragma unroll
for (uint32_t u = 0; u < kFinU; ++u) {
acc[u].x += v[u].x; acc[u].y += v[u].y;
acc[u].z += v[u].z; acc[u].w += v[u].w;
}
}
#pragma unroll
for (uint32_t u = 0; u < kFinU; ++u) {
if (b + u * MW * kWave >= total) continue;
*(uint2*)(cy + o[u]) = make_uint2(bf16x2_rne(acc[u].x, acc[u].y),
bf16x2_rne(acc[u].z, acc[u].w));
}
}
} else {
for (uint32_t idx = tid; idx < nr * nb; idx += MW * kWave) {
const size_t o = (size_t)(idx / nr) * rows + rlo + idx % nr;
float acc = 0.0f;
for (uint32_t z = 0; z < gridDim.z; ++z) acc += w0[z * zs + o];
cy[o] = f32_to_bf16(acc);
}
}
}
}
@@ -598,7 +703,7 @@ __device__ __forceinline__ void gemm_fp8a8_body(
Sc, Yb, q_ld, s_ld, y_ld, Bias, c_ld
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
bool GATED = false, bool I8 = false, bool BIAS = false>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8, GATED))
void gemm_fp8a8_kernel(
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
@@ -613,7 +718,7 @@ void gemm_fp8a8_kernel(
}
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
bool GATED = false, bool I8 = false, bool BIAS = false>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8, GATED))
void r4dchain_gemm_fp8a8(
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
+1287 -196
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -365,6 +365,7 @@ int w4_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
WGeom g;
int rc = wgeom(p, n_p, R4D_W4_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_W4_GROUP) return RAD_E_DTYPE;
if (g.K % R4D_W4_KPB) return RAD_E_SHAPE;
const bool asym = w4_asym(p, n_p);
const bool ok = asym ? (r4d_enc::affine(enc, RAD_U4, RAD_F16, 1, g.group, RAD_U8) ||
@@ -474,6 +475,7 @@ int w5_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
WGeom g;
int rc = wgeom(p, n_p, R4D_W4_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_W4_GROUP) return RAD_E_DTYPE;
if (g.K % R4D_W4_KPB) return RAD_E_SHAPE;
if (!w5_enc(enc, g.group)) return RAD_E_DTYPE;
if (gout) *gout = g;
@@ -676,6 +678,7 @@ int w8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
WGeom g;
int rc = wgeom(p, n_p, R4D_W8_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_W8_GROUP) return RAD_E_DTYPE;
if (g.K % R4D_W8_KPB) return RAD_E_SHAPE;
if (!r4d_enc::affine(enc, RAD_I8, RAD_F16, 1, g.group)) return RAD_E_DTYPE;
if (gout) *gout = g;
@@ -760,6 +763,7 @@ int w2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
WGeom g;
int rc = wgeom(p, n_p, R4D_W2_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_W2_GROUP) return RAD_E_DTYPE;
if (g.K % 128) return RAD_E_SHAPE;
if (!(r4d_enc::affine(enc, RAD_U2, RAD_F16, 1, g.group, RAD_U8) ||
r4d_enc::affine(enc, RAD_U2, RAD_F16, 1, g.group, RAD_U4))) return RAD_E_DTYPE;
+35 -21
View File
@@ -1448,7 +1448,7 @@ static const RadOperandSpec oArRmsNormQuantFp8[] = {
};
/* ar_rmsnorm_post_quant_fp8: the same with a sandwich post-norm of the reduced sum before the add
* (Gemma 3's junction, arch/gemma3), exact wire only. Its own op: an optional seventh operand on
* (Gemma 3's junction, arch/gemma3), on either wire. Its own op: an optional seventh operand on
* ar_rmsnorm_quant_fp8 would break every plugin that issues that op's six. */
static const RadOperandSpec oArRmsNormPostQuantFp8[] = {
{ "x", RAD_OPD_INOUT, 0 },
@@ -3542,7 +3542,7 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("ar_rmsnorm_post_quant_fp8", pArRmsNormQuantFp8, oArRmsNormPostQuantFp8,
"ar_rmsnorm_quant_fp8 with a post-norm of the reduced sum against w_post before the "
"residual add (a sandwich-norm junction), exact wire only, byte-identical to all_reduce, "
"residual add (a sandwich-norm junction), either wire, byte-identical to all_reduce, "
"rmsnorm, rmsnorm_quant_fp8."),
SCHEMA("ar_rmsnorm_quant_fp8", pArRmsNormQuantFp8, oArRmsNormQuantFp8,
"the two-rank all-reduce and the residual add, RMS norm and block-scaled fp8 "
@@ -4704,30 +4704,39 @@ static const RadConstraint cGemmNt64[] = {
static const RadConstraint cGemmNtTiled[] = {
C_GE("M", 65), C_LE("M", 65536), C_GE("N", 128), C_DIV("K", 64), C_IN("dtype", "bf16"),
};
/* The dense integer kernels take their group from a build constant and read no `group` argument.
* A declaration at another group gets no kernel rather than a silent 128. */
static const RadConstraint cGemmNtW4[] = {
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16"),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a16"),
};
/* w5a16 serves any M: the dispatcher takes rows past 64 as chunks of 64. */
static const RadConstraint cGemmNtW5[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w5a16"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w5a16"),
};
static const RadConstraint cGemmNtW4Asym[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16_asym"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a16_asym"),
};
static const RadConstraint cGemmNtW4A8I8[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a8i8_asym"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a8i8_asym"),
};
static const RadConstraint cGemmNtW5A8I8[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w5a8i8"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w5a8i8"),
};
static const RadConstraint cGemmNtW2A8[] = {
C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w2a8"),
C_DIV("K", 128), C_DIV("N", 16), C_EQ("group", R4D_W2_GROUP), C_IN("dtype", "w2a8"),
};
static const RadConstraint cGemmNtW8[] = {
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w8a16"),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W8_GROUP), C_IN("dtype", "w8a16"),
};
static const RadConstraint cGemmNtW4A8[] = {
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a8 w4a8_asym"),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a8 w4a8_asym"),
};
static const RadConstraint cGemmNtMxfp4A8[] = {
C_LE("M", 64), C_DIV("K", 32), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
@@ -5053,11 +5062,13 @@ static const RadConstraint cDequantW4Bf16[] = {
* K % (SK*group)). Its MAX_M of 32768 is not structural; as a skinny kernel with a tiled sibling
* above 64, it takes the w4a8 row's band. */
static const RadConstraint cGemmNtW8A8[] = {
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w8a8"),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W8_GROUP), C_IN("dtype", "w8a8"),
};
/* r4d_gemm_w4a8_tiled / _asym_tiled. Entry point: N % 256, K % group, M >= 1. */
static const RadConstraint cGemmW4A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w4a8 w4a8_asym"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a8 w4a8_asym"),
};
/* r4d_gemm_mxfp4a8_decode. Entry point: M <= 128, N % 16, K % 64, and N up to its counter block's
* 36864. Above the skinny row by priority, so it takes the decode band; the skinny row keeps the
@@ -5108,13 +5119,15 @@ static const RadConstraint cGemmM2xfp4A8Tiled[] = {
/* r4d_gemm_w8a8_tiled: the same kernel at radix 8. Its asym arm is not declared in r4d.h, so
* `w8a8_asym` is absent from the dtype set. */
static const RadConstraint cGemmW8A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w8a8"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256),
C_EQ("group", R4D_W8_GROUP), C_IN("dtype", "w8a8"),
};
/* r4d_gemm_w4a8_prefill. Entry point: N % BN and K % group, BN being the variant's block width
* (256 except for the two 1024-thread arms). N % 256 is the default's condition; the shim refuses
* a variant whose BN does not divide N (the per-call half of spec §2.1). */
static const RadConstraint cGemmW4A8Prefill[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w4a8"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a8"),
};
/* =================================================================================== tunables
@@ -7272,7 +7285,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"gdn prefill preamble: causal conv + qkv split + qk l2norm + gating + per-chunk cumsum "
"[UNVALIDATED: DPP row_xmask rewrite never correctness-gated]",
"conv width 4, head_k/head_v 128, chunk 64, varlen, conv state read and rewritten in place",
"bf16 x / weights / conv state / q,k,v out, fp32 a,b and gate/beta out",
"bf16 x / conv state / q,k,v out, bf16 or f32 weights, fp32 a,b and gate/beta out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGdnConvPrep), NOTUNE,
nullptr, nullptr, r4d_rad_gdn_conv_prep },
@@ -7282,7 +7295,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"gdn decode conv: rolling speculative window over the conv state cache, writes q/k/v "
"[UNVALIDATED: DPP row_xmask rewrite never correctness-gated]",
"conv width 4, head_k/head_v 128, state cache width-1 + num_spec, read at accepted offset",
"bf16 x / weights / conv state / q,k,v out",
"bf16 x / conv state / q,k,v out, bf16 or f32 weights",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGdnConvUpdate), NOTUNE,
nullptr, nullptr, r4d_rad_gdn_conv_update },
@@ -7311,7 +7324,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"workgroup convolves its key head's q and k and its value head's v into LDS, and the last "
"workgroup of a key head to arrive rewrites that head's conv state",
"head_k/head_v 128, conv width 4, a sequence's window at most 8 tokens, the fused row norm",
"bf16 x / conv weights / conv state / a,b / out; the state cache is f32 or f16. "
"bf16 x / conv state / a,b / out, bf16 or f32 conv weights; the state cache is f32 or f16. "
"Byte-identical to gdn_conv_update followed by gdn_recurrent_update",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGdnConvRecurrentUpdate), NOTUNE,
@@ -8779,7 +8792,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"exactly 2 ranks; n a multiple of 8 and x unpitched, because x is the message and a block pushes "
"its rows as 16B words; group 128; a block owns whole ROWS, so the block count is clamped to M; "
"either wire, chosen by `wire` -- the rotated 6-bit payload additionally needs n to be a "
"multiple of 512, so that a chunk never straddles a row; residual and out_bf16 may be null",
"multiple of 64, so that a group never straddles a row (a row's last 512-element chunk may be partial); residual and out_bf16 may be null",
"bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; codes "
"taken over the BF16-ROUNDED norm output, and the reduced sum rounded to bf16 exactly as the "
"standalone all-reduce of the SAME wire stores it -- byte-identical to the pair it replaces",
@@ -8796,7 +8809,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"back",
"exactly 2 ranks; n a multiple of 128 (a rotation block cannot straddle a row) and x unpitched; "
"group 128; a block owns whole ROWS, so the block count is clamped to M; either wire, chosen by "
"`wire` -- the rotated 6-bit payload additionally needs n to be a multiple of 512; residual and "
"`wire` -- the rotated 6-bit payload pads a row's partial last 512-element chunk; residual and "
"out_bf16 may be null",
"bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out of the "
"UNROTATED norm output; x and the residual are ar_rmsnorm_quant_fp8's bytes, and the codes "
@@ -8809,8 +8822,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
{ "ar_rmsnorm_post_quant_fp8", "ar_rmsnorm_post_quant_fp8", "quant",
"the two-rank all-reduce, a post-norm of the reduced sum, the residual add, RMS norm and "
"block-scaled fp8 quantisation in one kernel: a sandwich-norm junction (Gemma 3)",
"exactly 2 ranks, the exact wire; n a multiple of 8 and x unpitched; group 128; a block owns whole "
"rows; the residual is required",
"exactly 2 ranks, either wire chosen by `wire` (the rotated 6-bit payload needs n a multiple of 64; "
"a row's last 512-element chunk may be partial); n a multiple of 8 and x unpitched; group 128; a "
"block owns whole rows; the residual is required",
"bf16 in, E4M3 out with an f32 scale per (row, 128 columns); x receives the reduced sum",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cArRmsNormQuantFp8), ROW(tAr), nullptr,
+388 -12
View File
@@ -142,6 +142,7 @@ struct Plugin {
void (*pin_gather)(int) = nullptr;
void (*pin_ddec)(int) = nullptr;
void (*pin_hc)(int) = nullptr;
void (*pin_hc_dec)(int) = nullptr;
void (*pin_qsel)(int) = nullptr;
void (*pin_mla)(int) = nullptr;
void (*mla_stats)(unsigned long long*) = nullptr;
@@ -212,6 +213,7 @@ static bool load(Plugin* pl, const char* path) {
okall &= sym(pl->h, "r4d_moe_gather_pin_form", &pl->pin_gather);
okall &= sym(pl->h, "r4d_moe_gemm_pin_down_dec", &pl->pin_ddec);
okall &= sym(pl->h, "r4d_hc_read_pin_prefill", &pl->pin_hc);
okall &= sym(pl->h, "r4d_hc_read_pin_decode", &pl->pin_hc_dec);
okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel);
okall &= sym(pl->h, "r4d_mla_matrix_pin_form", &pl->pin_mla);
okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats);
@@ -4146,9 +4148,10 @@ static int64_t i8_code_misses(const uint16_t* x, int64_t x_ld, const int8_t* q,
*
* The key heads' conv state must have moved, so the check is sensitive. The anchor form runs in a
* child process, as in gdn_recurrent_anchor. `i8` runs both at int8 codes and also holds the pair's
* codes to quant_act_i8g over its `o`. */
* codes to quant_act_i8g over its `o`. `f32w` hands the fold the conv weight in f32, as a GGUF
* stores it, and leaves the pair's in bf16: the values are bf16's, so the bytes must not change. */
static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form,
bool i8 = false) {
bool i8 = false, bool f32w = false) {
const RadKernelInfo* rf = find(pl, "gdn_conv_recurrent_update_k128_v128_bf16");
const RadKernelInfo* rc = find(pl, "gdn_conv_update_w4_h128_bf16");
const RadKernelInfo* rr = find(pl, "gdn_recurrent_update_k128_v128_bf16_fp32state");
@@ -4175,7 +4178,8 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
const std::vector<uint16_t> hw = bf((size_t)(conv_dim * W), 0.5f);
const std::vector<uint16_t> hcs = bf((size_t)(CSLOTS * conv_dim * SL), 1.0f);
std::vector<float> hst((size_t)(SSLOTS * H * V * K)), halog((size_t)H), hdtb((size_t)H),
hnw((size_t)V);
hnw((size_t)V), hwf(hw.size());
for (size_t i = 0; i < hw.size(); ++i) hwf[i] = h_bf16(hw[i]);
for (auto& e : hst) e = 0.1f * rnd();
for (int64_t h = 0; h < H; ++h) { halog[(size_t)h] = -2.0f + 0.25f * (float)h;
hdtb[(size_t)h] = -1.0f + 0.5f * (float)h; }
@@ -4196,6 +4200,7 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
void* d_in = dev(nullptr, in_b);
void* d_ab = dev(nullptr, (size_t)(Td * 2 * H) * 2);
void* d_w = dev(hw.data(), hw.size() * 2);
void* d_wf = dev(hwf.data(), hwf.size() * 4);
void* d_alog = dev(halog.data(), halog.size() * 4);
void* d_dtb = dev(hdtb.data(), hdtb.size() * 4);
void* d_nw = dev(hnw.data(), hnw.size() * 4);
@@ -4224,6 +4229,7 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
const RadTensor ta = view(d_ab, RAD_BF16, Td, H, 2 * H, 0);
const RadTensor tb = view(d_ab, RAD_BF16, Td, H, 2 * H, H);
const RadTensor tw = T(d_w, RAD_BF16, { conv_dim, W });
const RadTensor tfw = f32w ? T(d_wf, RAD_F32, { conv_dim, W }) : tw;
const RadTensor tal = T(d_alog, RAD_F32, { H }), tdt = T(d_dtb, RAD_F32, { H });
const RadTensor tnw = T(d_nw, RAD_F32, { V });
const RadTensor tci = T(d_cidx, RAD_I32, { N }), tsi = T(d_sidx, RAD_I32, { N, COLS });
@@ -4269,7 +4275,7 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
e = run(rr, { tq, tk, tv, ta, tb, tal, tdt, st(0), tsi, tna, tcu, tz, tnw, to(0),
toq(0), tos(0) }, pr);
if (e != RAD_OK) { why = "pair rc=" + std::to_string(e); break; }
e = run(rf, { tx, tw, none, cs(1), tci, ta, tb, tal, tdt, st(1), tsi, tna, tcu, tz, tnw,
e = run(rf, { tx, tfw, none, cs(1), tci, ta, tb, tal, tdt, st(1), tsi, tna, tcu, tz, tnw,
to(1), toq(1), tos(1) }, pf);
if (e != RAD_OK) { why = "fold rc=" + std::to_string(e); break; }
@@ -4316,6 +4322,8 @@ static void gdn_conv_fold(const Plugin& pl) {
const char* row = "gdn_conv_recurrent_update_k128_v128_bf16";
const char* nmp = "gdn_conv_recurrent_update is byte-identical to the pair, per_candidate";
const char* nma = "gdn_conv_recurrent_update is byte-identical to the pair, anchor";
const char* nmf = "gdn_conv_recurrent_update over an f32 conv weight is byte-identical to the "
"pair over its bf16 twin, per_candidate";
if (sel(row)) {
gdn_conv_fold_run(pl, nmp, "per_candidate");
gdn_conv_fold_run(pl, "gdn_conv_recurrent_update is byte-identical to the pair at int8 "
@@ -4323,6 +4331,174 @@ static void gdn_conv_fold(const Plugin& pl) {
"per_candidate", true);
}
if (sel(row) || sel(nma)) gdn_conv_fold_run(pl, nma, "anchor");
if (sel(row) || sel(nmf)) gdn_conv_fold_run(pl, nmf, "per_candidate", false, true);
}
/* gdn_conv_prep and gdn_conv_update over an f32 weight, as a GGUF stores ssm_conv1d, against the
* same weight in bf16.
*
* The weight's values are bf16's, so both forms widen to the same taps and every byte a row writes
* must match: q, k and v, g and beta at prefill, and the conv state. Both runs start from identical
* copies of the cache and from outputs poisoned with 0xFF, so an element the f32 instance never
* writes is caught even where the bf16 one misses it as well. Prefill has two sequences seeded
* from their cached history, one over two chunks, and a one-token sequence without; decode has
* uneven windows and read offsets, sequence 1 at slot 0. The cache must have moved, and an f16
* weight is refused. */
static void gdn_conv_f32_weight(const Plugin& pl) {
const struct { const char* row; const char* nm; bool prep; } forms[] = {
{ "gdn_conv_prep_w4_h128_bf16",
"gdn_conv_prep over an f32 weight is byte-identical to its bf16 twin", true },
{ "gdn_conv_update_w4_h128_bf16",
"gdn_conv_update over an f32 weight is byte-identical to its bf16 twin", false },
};
for (const auto& f : forms) {
if (!sel(f.row) && !sel(f.nm)) continue;
const RadKernelInfo* r = find(pl, f.row);
if (!r) { ok(f.nm, false, "row absent"); continue; }
const int64_t K = 128, V = 128, H = 4, Hg = 2, N = 3, W = 4, MQ = 4, CSLOTS = 3;
const int64_t xdim = 2 * Hg * K + H * V;
/* Prefill reads W - 1 taps of history from a W-deep slot; decode rolls a W - 2 + MQ one. */
const int64_t SL = f.prep ? W : W - 2 + MQ;
const int32_t plen[N] = { 70, 1, 57 }, dlen[N] = { 4, 1, 3 };
const int32_t slot[N] = { 2, 0, 1 }, nacc[N] = { 2, 1, 3 };
const uint8_t init[N] = { 1, 0, 1 };
int64_t Tn = 0;
std::vector<int32_t> cu(1, 0);
for (int64_t n = 0; n < N; ++n) {
Tn += f.prep ? plen[n] : dlen[n];
cu.push_back((int32_t)Tn);
}
uint32_t seed = 0x2f37c0d5u;
auto rnd = [&seed]() {
seed = st_mix32(seed + 0x9e3779b9u);
return (float)(seed & 0xFFFFu) * (1.0f / 32768.0f) - 1.0f;
};
auto bf = [&](size_t n, float s) {
std::vector<uint16_t> v(n);
for (auto& e : v) e = h_to_bf16(s * rnd());
return v;
};
const std::vector<uint16_t> hw = bf((size_t)(xdim * W), 0.5f), hb = bf((size_t)xdim, 0.25f);
const std::vector<uint16_t> hx = bf((size_t)(Tn * xdim), 1.0f);
const std::vector<uint16_t> hab = bf((size_t)(Tn * 2 * H), 1.0f);
const std::vector<uint16_t> hcs = bf((size_t)(CSLOTS * xdim * SL), 1.0f);
std::vector<float> hwf(hw.size()), halog((size_t)H), hdtb((size_t)H);
for (size_t i = 0; i < hw.size(); ++i) hwf[i] = h_bf16(hw[i]);
for (int64_t h = 0; h < H; ++h) { halog[(size_t)h] = -2.0f + 0.25f * (float)h;
hdtb[(size_t)h] = -1.0f + 0.5f * (float)h; }
auto dev = [](const void* h, size_t bytes) {
void* d = dalloc(bytes);
if (d && h) st_memcpy(d, h, bytes, hipMemcpyHostToDevice);
return d;
};
const size_t cs_b = hcs.size() * 2, qk_b = (size_t)(Tn * Hg * K) * 2,
v_b = (size_t)(Tn * H * V) * 2, g_b = (size_t)(Tn * H) * 4;
void* d_x = dev(hx.data(), hx.size() * 2);
void* d_ab = dev(hab.data(), hab.size() * 2);
void* d_b = dev(hb.data(), hb.size() * 2);
void* d_w[2] = { dev(hw.data(), hw.size() * 2), dev(hwf.data(), hwf.size() * 4) };
void* d_alog = dev(halog.data(), halog.size() * 4);
void* d_dtb = dev(hdtb.data(), hdtb.size() * 4);
void* d_slot = dev(slot, sizeof(slot));
void* d_nacc = dev(nacc, sizeof(nacc));
void* d_init = dev(init, sizeof(init));
void* d_cu = dev(cu.data(), cu.size() * 4);
void* d_cs[2]; void* d_q[2]; void* d_k[2]; void* d_v[2]; void* d_g[2]; void* d_beta[2];
for (int i = 0; i < 2; ++i) {
d_cs[i] = dev(hcs.data(), cs_b);
d_q[i] = dev(nullptr, qk_b); d_k[i] = dev(nullptr, qk_b); d_v[i] = dev(nullptr, v_b);
d_g[i] = dev(nullptr, g_b); d_beta[i] = dev(nullptr, g_b);
}
if (!d_x || !d_cu || !d_cs[1] || !d_beta[1]) { ok(f.nm, false, "hipMalloc"); continue; }
for (int i = 0; i < 2; ++i) {
st_memset(d_q[i], 0xFF, qk_b); st_memset(d_k[i], 0xFF, qk_b);
st_memset(d_v[i], 0xFF, v_b); st_memset(d_g[i], 0xFF, g_b);
st_memset(d_beta[i], 0xFF, g_b);
}
/* a and b_gate are column views of one [Tn, 2H] row, as the block lays them out. */
auto view = [](void* base, int64_t rows, int64_t cols, int64_t pitch, int64_t col0) {
RadTensor t = T((char*)base + (size_t)col0 * 2, RAD_BF16, { rows, cols });
t.stride[0] = pitch;
return t;
};
auto ops = [&](int i, uint32_t wdt) {
const RadTensor tx = T(d_x, RAD_BF16, { Tn, xdim }), tb = T(d_b, RAD_BF16, { xdim });
const RadTensor tw = T(d_w[i], wdt, { xdim, W });
const RadTensor tcs = T(d_cs[i], RAD_BF16, { CSLOTS, xdim, SL });
const RadTensor tcu = T(d_cu, RAD_I32, { N + 1 }), tsl = T(d_slot, RAD_I32, { N });
const RadTensor tq = T(d_q[i], RAD_BF16, { Tn, Hg, K }),
tk = T(d_k[i], RAD_BF16, { Tn, Hg, K }),
tv = T(d_v[i], RAD_BF16, { Tn, H, V });
if (!f.prep)
return std::vector<RadTensor>{ tx, tw, tb, tcs, tsl, T(d_nacc, RAD_I32, { N }), tcu,
tq, tk, tv };
return std::vector<RadTensor>{
tx, tw, tb, T(d_alog, RAD_F32, { H }), T(d_dtb, RAD_F32, { H }), tcs, tcu,
view(d_ab, Tn, H, 2 * H, 0), view(d_ab, Tn, H, 2 * H, H), tsl,
T(d_init, RAD_U8, { N }), tq, tk, tv, T(d_g[i], RAD_F32, { Tn, H }),
T(d_beta[i], RAD_F32, { Tn, H }) };
};
std::vector<RadParam> ps = f.prep
? std::vector<RadParam>{ PI("M", Tn), PI("head_k", K), PI("head_v", V),
PI("chunk", 64), PI("conv_width", W) }
: std::vector<RadParam>{ PI("q_len", MQ), PI("head_k", K), PI("head_v", V),
PI("conv_width", W) };
auto run = [&](std::vector<RadTensor> ts) {
RadArgs a; std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
const int rc_ = r->launch(&a, (RadStream) nullptr);
return rc_ != RAD_OK ? rc_ : (st_stream_sync(nullptr) != hipSuccess ? -1000 : RAD_OK);
};
auto fetch = [](void* d, size_t b) {
std::vector<uint8_t> h(b);
st_memcpy(h.data(), d, b, hipMemcpyDeviceToHost);
return h;
};
std::string why;
for (int i = 0; i < 2 && why.empty(); ++i) {
const int e = run(ops(i, i ? RAD_F32 : RAD_BF16));
if (e != RAD_OK) why = std::string(i ? "f32" : "bf16") + " rc=" + std::to_string(e);
}
struct Out { const char* what; void* a; void* b; size_t n; size_t es; };
std::vector<Out> outs = { { "q", d_q[0], d_q[1], qk_b, 2 },
{ "k", d_k[0], d_k[1], qk_b, 2 },
{ "v", d_v[0], d_v[1], v_b, 2 },
{ "conv_state", d_cs[0], d_cs[1], cs_b, 2 } };
if (f.prep) {
outs.push_back({ "g", d_g[0], d_g[1], g_b, 4 });
outs.push_back({ "beta", d_beta[0], d_beta[1], g_b, 4 });
}
for (const Out& o : outs) {
if (!why.empty()) break;
const std::vector<uint8_t> A = fetch(o.a, o.n), B = fetch(o.b, o.n);
size_t diff = 0, poisoned = 0;
for (size_t j = 0; j < o.n; ++j) diff += A[j] != B[j];
for (size_t j = 0; j < o.n; j += o.es) {
size_t ff = 0;
for (size_t e = 0; e < o.es; ++e) ff += B[j + e] == 0xFF;
poisoned += ff == o.es;
}
if (diff)
why = std::string(o.what) + " differs in " + std::to_string(diff) + " of " +
std::to_string(o.n) + " bytes";
else if (poisoned)
why = std::string(o.what) + ": " + std::to_string(poisoned) + " elements unwritten";
}
if (why.empty() && fetch(d_cs[1], cs_b) == std::vector<uint8_t>(
(const uint8_t*)hcs.data(), (const uint8_t*)hcs.data() + cs_b))
why = "the conv state never moved";
if (why.empty()) {
const int e = run(ops(1, RAD_F16));
if (e != RAD_E_DTYPE) why = "an f16 weight gave rc=" + std::to_string(e);
}
ok(f.nm, why.empty(), why);
}
}
/* The gated norm's gate as a column slice, which one pitch cannot describe.
@@ -17914,6 +18090,129 @@ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form)
: "the int8 run changed" + bad);
}
/* The gated residual's read at its decode kernels, byte for byte: the launcher's rule (kernels A and
* B as one grid at one to seven rows, the tiled up-mix pipelined from eight) against the kernels it
* replaced, pinned through r4d_hc_read_pin_decode(1). E4M3 or int8 codes, on a real stream (the
* one-grid form keys its counters on it). The two forms must dispatch different kernels, so a pin
* that is ignored cannot pass by comparing a form with itself. */
static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) {
const std::string nm = fmt("hc_read_e4m3 decode kernels at M=%lld, %s codes: the rule "
"byte-identical to the previous kernels", (long long)M,
i8 ? "int8" : "E4M3");
const RadKernelInfo* r = find(pl, "hc_read_e4m3");
if (!r) { skip(nm.c_str(), "row absent"); return; }
if (!pl.pin_hc_dec || !pl.record) { skip(nm.c_str(), "no r4d_hc_read_pin_decode"); return; }
const int64_t n = 2560, hc = 4, lr = 320, HN = hc * n, grp = 128, nkb = n / grp;
const int64_t dld = r4d_hc8::row_bytes(HN, r4d_hc8::down_group(HN));
const int64_t uld = r4d_hc8::row_bytes(lr, r4d_hc8::up_group(lr));
uint64_t rs = 0xD1B54A32D192ED03ull ^ (uint64_t)M;
auto rnd = [&]() { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; };
std::vector<uint16_t> hh((size_t)(M * HN));
for (auto& v : hh) v = h_to_bf16((float)((int)(rnd() % 2001) - 1000) / 400.0f);
std::vector<float> wg((size_t)HN);
for (auto& v : wg) v = (float)((int)(rnd() % 201) - 100) / 1000.0f;
auto plane = [&](int64_t rows, int64_t K, int64_t G, int64_t ld) {
std::vector<uint8_t> b((size_t)(rows * ld), 0);
for (int64_t r0 = 0; r0 < rows; ++r0) {
uint8_t* row = b.data() + r0 * ld;
for (int64_t k = 0; k < K; ++k) row[k] = (uint8_t)(8 + rnd() % 111) | ((rnd() & 1) ? 0x80u : 0u);
float* sc = (float*)(row + K);
for (int64_t g = 0; g < K / G; ++g) sc[g] = 0.002f + 0.004f * (float)(rnd() % 1000) / 1000.0f;
}
return b;
};
std::vector<uint8_t> down = plane(lr, HN, r4d_hc8::down_group(HN), dld);
std::vector<uint8_t> up = plane(HN, lr, r4d_hc8::up_group(lr), uld);
std::vector<uint16_t> injw((size_t)(hc * HN));
for (auto& v : injw) v = h_to_bf16((float)((int)(rnd() % 201) - 100) / 50000.0f);
const size_t xb = (size_t)(M * n * 2), ib = (size_t)(M * hc * 2), qb = (size_t)(M * n),
sb = (size_t)(M * nkb * 4);
void* d_h = dalloc(hh.size() * 2);
void* d_w = dalloc(wg.size() * 4);
void* d_dn = dalloc(down.size());
void* d_up = dalloc(up.size());
void* d_iw = dalloc(injw.size() * 2);
void* d_x = dalloc(xb);
void* d_inj = dalloc(ib);
void* d_q = dalloc(qb);
void* d_qs = dalloc(sb);
void* d_rq = dalloc(qb);
void* d_rs = dalloc(sb);
if (!d_h || !d_w || !d_dn || !d_up || !d_iw || !d_x || !d_inj || !d_q || !d_qs || !d_rq || !d_rs) {
ok(nm.c_str(), false, "hipMalloc failed");
return;
}
st_memcpy(d_h, hh.data(), hh.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_w, wg.data(), wg.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_dn, down.data(), down.size(), hipMemcpyHostToDevice);
st_memcpy(d_up, up.data(), up.size(), hipMemcpyHostToDevice);
st_memcpy(d_iw, injw.data(), injw.size() * 2, hipMemcpyHostToDevice);
hipStream_t hs = nullptr;
if (hipStreamCreate(&hs) != hipSuccess) { ok(nm.c_str(), false, "stream"); return; }
const uint32_t qdt = i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
std::vector<RadTensor> ts = {
T(d_h, RAD_BF16, { M, HN }), T(d_w, RAD_F32, { HN }),
T(d_dn, RAD_F8E4M3, { lr, HN }), T(d_up, RAD_F8E4M3, { HN, lr }),
T(d_iw, RAD_BF16, { hc, HN }), T(d_x, RAD_BF16, { M, n }),
T(d_inj, RAD_BF16, { M, hc }), T(d_q, qdt, { M, n }),
T(d_qs, RAD_F32, { M, nkb }), T(d_rq, RAD_F8E4M3, { M, n }),
T(d_rs, RAD_F32, { M, nkb }),
};
std::vector<RadParam> ps = {
PI("M", M), PI("n", n), PI("hc", hc), PI("lowrank", lr), PF("eps", 1e-6),
PS("dtype", "bf16"), PF("wadd", 1.0), PI("inject", 1), PI("group", grp),
PI("rotate", 1), PS("mix", "e4m3"),
};
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
if (r->scratch) {
const int64_t need = r->scratch(&a);
if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; }
}
struct Out { std::vector<uint8_t> x, inj, q, qs, rq, rs; std::vector<const void*> fns; };
Out out[2];
for (int form = 0; form < 2; ++form) {
pl.pin_hc_dec(form);
st_memset(d_x, 0, xb); st_memset(d_q, 0, qb); st_memset(d_qs, 0, sb);
st_memset(d_rq, 0, qb); st_memset(d_rs, 0, sb); st_memset(d_inj, 0, ib);
const void* fns[16] = {};
pl.record(fns, 16);
const int rc = r->launch(&a, (RadStream)hs);
const int nd = pl.record(nullptr, 0);
if (rc != RAD_OK || st_stream_sync(hs) != hipSuccess) {
ok(nm.c_str(), false, fmt("%s rc=%d", form ? "the previous kernels" : "the rule", rc));
pl.pin_hc_dec(0);
(void)hipStreamDestroy(hs);
return;
}
out[form].fns.assign(fns, fns + (nd < 16 ? nd : 16));
auto get = [&](std::vector<uint8_t>& v, void* d, size_t b) {
v.resize(b); st_memcpy(v.data(), d, b, hipMemcpyDeviceToHost);
};
get(out[form].x, d_x, xb); get(out[form].inj, d_inj, ib); get(out[form].q, d_q, qb);
get(out[form].qs, d_qs, sb); get(out[form].rq, d_rq, qb); get(out[form].rs, d_rs, sb);
}
pl.pin_hc_dec(0);
(void)hipStreamDestroy(hs);
std::string bad;
if (out[0].x != out[1].x) bad += " x";
if (out[0].inj != out[1].inj) bad += " inj";
if (out[0].q != out[1].q) bad += " q";
if (out[0].qs != out[1].qs) bad += " qs";
if (out[0].rq != out[1].rq) bad += " rq";
if (out[0].rs != out[1].rs) bad += " rs";
int64_t nz = 0;
for (uint8_t v : out[0].q) nz += v != 0;
const bool distinct = out[0].fns != out[1].fns;
ok(nm.c_str(), bad.empty() && nz > (int64_t)qb / 2 && distinct,
!bad.empty() ? "differs in" + bad
: !distinct ? std::string("both forms dispatched the same kernels")
: fmt("%lld of %zu codes non-zero; %zu and %zu launches", (long long)nz, qb,
out[0].fns.size(), out[1].fns.size()));
}
/* The gated residual's read at a prefill chunk: hc_read_e4m3 at Qwen3.8-Flash-Next's shape (n
* 2560, four streams, lowrank 320, inject gains, the fp8 twin and its rotated twin). Several
* launches at prefill, so also a harness for libr4d/isa/trace.sh. Random codes, small positive
@@ -18024,11 +18323,20 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
static const char* const kForm[] = { "the launcher's rule", "the decode tiles' kernels",
"the wide kernels", "the PF2 kernels" };
std::vector<Out> outs;
std::vector<int> ran; /* the form each of `outs` came from */
for (int form = f_lo; form <= f_hi; ++form) {
if (pl.pin_hc) pl.pin_hc(form);
st_memset(d_x, 0, xb); st_memset(d_inj, 0, ib); st_memset(d_q, 0, qb);
st_memset(d_qs, 0, sb); st_memset(d_rq, 0, qb); st_memset(d_rs, 0, sb);
const int rc = r->launch(&a, rst);
/* A pinned form refusing the shape is not a failure: the wide kernels serve only the wide
* row tile, so from 8 rows up to it --perfhc times the decode tiles' kernels alone. The
* first form (the decode tiles') must serve. */
if (rc == RAD_E_SHAPE && pl.pin_hc && form > f_lo) {
skip(fmt("%s prefill form '%s' at M=%lld", rn, kForm[form], (long long)M).c_str(),
"not served at this row count");
continue;
}
if (rc != RAD_OK || st_stream_sync(hs) != hipSuccess) {
ok(fmt("%s prefill form '%s' at M=%lld is served", rn, kForm[form],
(long long)M).c_str(), false, fmt("rc=%d", rc));
@@ -18043,6 +18351,7 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
get(o.x, d_x, xb); get(o.inj, d_inj, ib); get(o.q, d_q, qb);
get(o.qs, d_qs, sb); get(o.rq, d_rq, qb); get(o.rs, d_rs, sb);
outs.push_back(std::move(o));
ran.push_back(form);
}
/* Form f against the decode tiles' kernels, outs[0]. */
auto same = [&](size_t f, const char* what) {
@@ -18061,11 +18370,10 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
bad.empty() && nz > qb / 2, bad.empty() ? fmt("%zu of %zu codes non-zero", nz, qb)
: "differs in" + bad);
};
for (size_t f = 1; f < outs.size(); ++f) same(f, kForm[f_lo + (int)f]);
for (size_t f = 1; f < outs.size(); ++f) same(f, kForm[ran[f]]);
if (timed) {
for (int form = f_lo; form <= f_hi; ++form) {
if (pl.pin_hc) pl.pin_hc(form);
auto time_now = [&](const char* label) {
hipEvent_t w0, w1;
st_ev_create(&w0); st_ev_create(&w1);
st_ev_record(w0, hs);
@@ -18081,8 +18389,21 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
const double flop = 2.0 * (double)M * (double)HN * (double)(2 * lr + hc);
std::printf("%s at M=%lld (n %lld, hc %lld, lowrank %lld, inject, fp8 twin + "
"rotated), %s: %.1f us a call, %.1f TFLOP/s\n", rn, (long long)M,
(long long)n, (long long)hc, (long long)lr, kForm[form], us,
(long long)n, (long long)hc, (long long)lr, label, us,
flop / (us * 1e6));
};
for (const int form : ran) {
if (pl.pin_hc) pl.pin_hc(form);
time_now(kForm[form]);
}
/* The decode kernels against the ones they replaced (r4d_hc_read_pin_decode), under the
* launcher's prefill rule. */
if (pl.pin_hc_dec && f8) {
if (pl.pin_hc) pl.pin_hc(0);
pl.pin_hc_dec(1);
time_now("the previous decode kernels");
pl.pin_hc_dec(0);
time_now("the launcher's rule");
}
}
if (pl.pin_hc) pl.pin_hc(0);
@@ -20254,6 +20575,27 @@ static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iter
};
perf_row(pl, "gemm_fp8a8_nt_m16", ts, ps, d_w, wbytes, copies, bytes, iters);
perf_row(pl, "gemm_fp8a8_tiled", ts, ps, d_w, wbytes, copies, bytes, iters);
/* The gated row, at a gate_up shape: N is the gate and up rows together, as the engine
* fuses them, and the output is their quantised SiLU product, N / 2 wide. It refuses a
* shape the split rule would split. */
if (N % 256 == 0 && K % 256 == 0 && M <= 64) {
const int64_t nout = N / 2, gkb = nout / 128;
void* d_gq = dalloc((size_t)M * nout);
void* d_gs = dalloc((size_t)M * gkb * 4);
void* d_gy = dalloc((size_t)M * nout * 2);
if (!d_gq || !d_gs || !d_gy) {
std::printf(" %-22s hipMalloc failed\n", "gemm_fp8a8_gated_nt_m16");
} else {
perf_row(pl, "gemm_fp8a8_gated_nt_m16",
{ T(d_q, RAD_F8E4M3, { M, K }), T(d_qs, RAD_F32, { M, sk }),
T(d_w, RAD_F8E4M3, { N, K }), T(d_s, RAD_BF16, { sn, sk }),
T(d_gq, RAD_F8E4M3, { M, nout }), T(d_gs, RAD_F32, { M, gkb }),
T(d_gy, RAD_BF16, { M, nout }) },
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 128),
PS("dtype", "fp8a8"), PS("act", "silu") },
d_w, wbytes, copies, bytes, iters);
}
}
}
/* The lm head, a decode GEMM too. Its weight is [N][K + 2*nkb] E4M3 with each row's bf16
@@ -25142,6 +25484,23 @@ struct ArThread {
int64_t spitch = 0;
};
/* Whether every rank device a collective case is about to use can reach every other directly.
* The engine carries this fact (device.p2p, RAD_FACT_P2P) and selects around its absence; a card
* count is not enough. hipDeviceCanAccessPeer answers it without a kernel: on a box with the IOMMU
* off the peer path is absent, the enable call throws `enable_peer: invalid device ordinal`, and
* init returns RAD_E_DEVICE — a skip line, like the card-count gates, not a failure. */
static bool ar_peer_path_ok(const std::vector<int>& devs, int world) {
if (world < 2 || (int)devs.size() < world) return false;
for (int a = 0; a < world; ++a)
for (int b = 0; b < world; ++b) {
if (a == b) continue;
int can = 0;
if (hipDeviceCanAccessPeer(&can, devs[a], devs[b]) != hipSuccess) return false;
if (!can) return false;
}
return true;
}
static void ar_worker(ArThread* t) {
if (st_set_device(t->dev) != hipSuccess) { t->rc_init = RAD_E_DEVICE; return; }
std::vector<RadParam> ps = {
@@ -25179,6 +25538,7 @@ static void ar_two_rank(const Plugin& pl, const std::vector<int>& devs, const ch
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, 2)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
/* 8192 fp32 elements: whole 16-byte pushes, small enough to exercise the handshake rather
* than the link. */
@@ -25290,6 +25650,7 @@ static void ar_two_rank_sweep(const Plugin& pl, const std::vector<int>& devs, co
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, 2)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
ArSweep a{ row, 0, devs[0] }, b{ row, 1, devs[1] };
std::thread ta(ar_sweep_worker, &a), tb(ar_sweep_worker, &b);
ta.join();
@@ -25314,6 +25675,7 @@ static void ar_two_rank_late(const Plugin& pl, const std::vector<int>& devs, con
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, 2)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
pl.pin_late_push(1);
ArSweep a{ row, 0, devs[0] }, b{ row, 1, devs[1] };
std::thread ta(ar_sweep_worker, &a), tb(ar_sweep_worker, &b);
@@ -25402,6 +25764,7 @@ static void gather_two_rank(const Plugin& pl, const std::vector<int>& devs, cons
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, 2)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
const int64_t numel = 8192; /* the sampler's own message at 4 rows and 1024 candidates */
ArThread a{ row, 0, devs[0], numel }, b{ row, 1, devs[1], numel };
@@ -25493,6 +25856,7 @@ static void ar_wide_rank(const Plugin& pl, const std::vector<int>& devs, const c
skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str());
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
const int64_t numel = 8192;
const std::string w = std::to_string(world);
std::vector<ArThread> t;
@@ -25787,6 +26151,7 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector<int>& devs, cons
skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str());
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
using Run = ArPatternRun;
/* The three-rank list walks the UNEVEN split (words % 3 of 0, 1 and 2); the four- and
* eight-rank rows cannot be given one -- cArTsExact4/cArTsExact8/cArTi8Ts4 constrain numel so
@@ -25869,6 +26234,7 @@ static void ar_wide_weighted(const Plugin& pl, const std::vector<int>& devs, con
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if ((int)devs.size() < W) { skip(name, "needs 8 gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, W)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
/* bf16: 72 elements are 9 words, 8 are one; 8256 is 1032 words, 4196352 is 524544. Without
* weights the words must divide by eight. */
const std::vector<ArPatternRun> uneven = {
@@ -26476,6 +26842,7 @@ static void ar_lane_forms(const Plugin& pl, const std::vector<int>& devs, const
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if ((int)devs.size() < 4) { skip(name, "needs 4 gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, 4)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
struct Run { bool coded; int pat; const char* dtype; std::vector<int64_t> sizes; int oop; };
/* 1024: one wave a shard; 1055744: 1031 waves, an odd split over the blocks; 524352: bf16
* outside the coded form; 46137344: the feed-forward reduce at an 8192-token chunk. */
@@ -26610,6 +26977,7 @@ static void ar_wide_ti8(const Plugin& pl, const std::vector<int>& devs, const ch
skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str());
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
/* 32768 is under the 128 KiB floor and 65544 is not whole groups (at four ranks, not whole
* SHARD groups -- the 4-rank wire tiles numel by 128): both exact. The rest are
* lossy: 65536 sits ON the floor (2048 groups, % 3 = 2), then 2048 x 2048 / 2049 / 2050 rows
@@ -26980,6 +27348,7 @@ static void ar_hc_write_case(const Plugin& pl, const std::vector<int>& devs, con
skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str());
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
struct Shape { int64_t M, n, hc, top_k; const char* act; bool scratch; };
std::vector<Shape> shapes;
if (!want_gather) {
@@ -27279,6 +27648,7 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
skip(name, world == 4 ? "needs 4 gfx1201 cards" : "needs 2 gfx1201 cards");
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
/* Only the four-rank P2P row ends the engine's link hold; the host twin and the two-rank rows
* leave it alone. */
const bool releases = world == 4 && !nm_ends_with(name, "_host");
@@ -29518,6 +29888,7 @@ static void device_phase(const Plugin& pl) {
}
gdn_recurrent_anchor(pl);
gdn_conv_fold(pl);
gdn_conv_f32_weight(pl);
if (sel("gdn_gated_rmsnorm_h128_bf16")) {
const RadKernelInfo* r = find(pl, "gdn_gated_rmsnorm_h128_bf16");
if (!r) ok("gdn_gated_rmsnorm_h128_bf16", false, "row absent");
@@ -30734,6 +31105,10 @@ static void device_phase(const Plugin& pl) {
for (int form : { 1, 2 }) hc_read_i8(pl, m, true, form);
for (int64_t m : { 700, 2048 }) hc_read_i8(pl, m, true, 3);
}
/* The decode kernels against the ones they replaced: each one-grid instantiation (1 to 7
* rows) and the tiled up-mix at both of its row tiles. */
for (int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 33, 64 })
for (bool i8 : { false, true }) hc_decode_forms(pl, m, i8);
}
if (sel("hc_read_bf16")) {
if (!g_case) std::printf("\nthe gated residual's read over bf16 mixing matrices at the "
@@ -31179,8 +31554,8 @@ static void usage(void) {
" given byte offsets in a safetensors file, compared with a host\n"
" reference over the same bytes. An offset is 8 + <header length, a\n"
" u64 at byte 0> + the tensor's own data_offsets[0].\n"
" --perf N K M [iters]: time the fp8 decode GEMMs at one shape and print the\n"
" weight bandwidth each reaches.\n"
" --perf N K M [iters]: time the fp8 decode GEMMs at one shape (the gated row with\n"
" N a gate_up's width) and print the weight bandwidth each reaches.\n"
" --perfwpa N K M [iters] [pb1]: the int5 and int4 x int8 tiled GEMMs (gemm_w5a8i8_tiled,\n"
" gemm_w4a8i8_tiled), warmed, min / median time and a hash of the output.\n"
" --perfmxd N K M [iters]: the dense MXFP4 GEMM rows (gemv, decode, skinny, tiled) at\n"
@@ -31197,8 +31572,9 @@ static void usage(void) {
" rows -- at one shape, each with its TFLOP/s.\n"
" --perfw2 N K M [iters]: the int2 DFlash2 draft head at every variant it has.\n"
" --perfhc M [iters]: hc_read_e4m3 at Qwen3.8-Flash-Next's shape and M rows, every\n"
" prefill-tile form (PF2 from M=512) compared byte for byte and timed\n"
" as one op each;\n"
" prefill-tile form that serves M (the wide kernels at the wide tile,\n"
" PF2 from M=512) compared byte for byte and timed as one op each,\n"
" then the previous decode kernels against the launcher's rule;\n"
" run it under libr4d/isa/trace.sh for its launches.\n"
" --cold MIB: with a --perf mode, time cold: read MIB through the caches before\n"
" every timed launch (256 empties this card's L2 and last level) and\n"