libr4d: chained forms for Flash-Next's decode step, hc_read forms G, S and B3

Every kernel of Flash-Next's speculative decode step gets a chained form (r4d_chain.h), so the
step's small launches wait on their predecessor on the card instead of behind a queue barrier:
the router and the fp8 and four-bit expert GEMMs, the gated quantisers, the delta-net recurrence
and conv, the hyper-connection write and its all-reduce gather, the attention layer's indexer,
norm/rope/gate, quantiser and gqa6 decode rows, and the tiled and fused hc_read kernels. A
chained form is taken only at steps of up to 32 token rows (kR4dChainMaxRows); above that the
waiting blocks hold room a wide predecessor needs.

hc_read at one to sixteen decode rows (hc 4, n 2560, E4M3 mixing matrices, inject gains), the
shape Flash-Next calls 97 times a pass:
- form G (1..8 rows): kernel A' as (16-column tile, stream) blocks, so a block reads its W_down
  slice once for every row of the step; the slice and the norm gain load before the chain wait,
  the dots are bf16 WMMA, and the last of a tile's blocks sums the streams in ascending order.
- form S (9..16 rows): as G, but the norm's scale is applied after the dot, so N never sits in
  LDS and one block holds every row.
- kernel B3 (both forms, lr 320): the up product as WMMA over d with W_up's exact quarter
  scales, and the mix in each lane; W_up loads before the chain wait.
From 17 rows the tiled path (now chained) stays faster.

The new forms are not byte-identical to the kernels they replace: the bf16 WMMA dots sum in
another order and S scales after the dot. Against an fp64 host reference, d is as close as the
per-row kernels' at 1..7 rows and closer than the tiled path's at 8..16 (mean error 0.13-0.14 %
of the row's RMS against 0.17 %, max 1.2-1.4 % against 1.3-2.0 %). The selftest's decode-forms
case now holds d to that reference (no further from it than the two-grid form) and x to the
two-grid form within rounding up to 16 rows, and stays byte for byte above.

Flash-Next on 2x R9700, sampled at temperature 1, 25k prompt, 500 tokens, two rounds of
1/2/4/8/16 streams: MTP depth 3 174/291/458/657/851 -> 207/339/493/647/843 tok/s; with depth 5
and the adaptive window 191/331/493/661/897 -> 218/355/494/662/893.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mici81andClaude Opus 5.5 authored and StillDeadcode committed 2026-11-05 09:48:37 +01:00
1 parent aeaf6a4580
commit b0a58b5dbf
16 files changed
+1563 -98

No files matched your search

+2 -2
View File
@@ -322,7 +322,7 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla
void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n,
long hc, long irow, long hrow, long stream, long nblocks, long nthreads,
long drain, long acq, long gate, long gate_ctr, long stage = 0);
long drain, long acq, long gate, long gate_ctr, long stage = 0, long chain = 0);
// The same with the MoE gather as its prologue: y is produced, not read, from the routed experts'
// rows `ye` [M*top_k][ye_ld] summed to token order by weights `ew` [M][ew_ld] and `sorted`
// [M*top_k], with the shared arm `sh` [M][sh_ld] and its gate `sg` folded when both are non-zero.
@@ -335,7 +335,7 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld,
long top_k, long sig, long stream, long nblocks, long nthreads,
long drain, long acq, long inv, long gate, long gate_ctr,
long stage = 0);
long stage = 0, long chain = 0);
// r4d_ar_hc_write and r4d_ar_gather_hc_write on the rotated 6-bit wire (r4d_ar_oneshot_2rank_wht6's
// format, loc_pack and scratch split): byte-identical to all_reduce on that wire then hc_write,
// with `ye` non-zero preceded by moe_gather. Gather operands as r4d_ar_gather_hc_write; its slot
+5 -2
View File
@@ -18,6 +18,7 @@
* with a 60-second timeout and a named error.
*/
#include "r4d_chain.h"
#include "r4d_args.h"
#include "r4d.h"
#include "r4d_ar_shards.h"
@@ -1715,7 +1716,8 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) {
sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L, (long)ye_ld, (long)ew_ld, (long)sh_ld,
(long)sg_ld, (long)top_k, (long)sig, (long)(uintptr_t)s, nblocks, cfgv.nthreads,
cfgv.drain, cfgv.acq, has_inv ? (long)(uintptr_t)a->scratch : 0L, early,
early ? in->gate_ctr : 0L, in->my_stage);
early ? in->gate_ctr : 0L, in->my_stage,
r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M) ? 1L : 0L);
if (rc != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
@@ -1844,7 +1846,8 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) {
in->my_seq, in->slot16, r4d_addr(y), r4d_addr(inj), r4d_addr(h),
(long)M, (long)n, (long)hc, (long)irow, (long)hrow, (long)(uintptr_t)s,
nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, early,
early ? in->gate_ctr : 0L, in->my_stage));
early ? in->gate_ctr : 0L, in->my_stage,
r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M) ? 1L : 0L));
return early ? RAD_LINK_ENDED : RAD_OK;
}
+51 -7
View File
@@ -18,6 +18,7 @@
// * Fine-grained memory (hipDeviceMallocFinegrained) is uncached and posted straight to the
// fabric, so system-scope release/acquire skip the L2 writeback. The drain/acq fences are
// selectable (default drain=1/acq=0 on fine-grained).
#include "r4d_chain.h"
#include "r4d.h"
#include "r4d_ar_seq.h"
#include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the rotated wire
@@ -147,7 +148,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
//
// n is a multiple of eight, so a word never straddles a row and the block that reduces it owns
// every stream element behind it.
__global__ void r4d_ar_hc_write_kernel(
__device__ __forceinline__ void r4d_ar_hc_write_kernel_body(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
@@ -209,6 +210,26 @@ __global__ void r4d_ar_hc_write_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
__global__ void r4d_ar_hc_write_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate,
unsigned int* gate_ctr, long stage) {
r4d_ar_hc_write_kernel_body(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, gate, gate_ctr, stage);
}
__global__ void r4dchain_ar_hc_write(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate,
unsigned int* gate_ctr, long stage) {
r4d_chain_wait();
r4d_ar_hc_write_kernel_body(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, gate, gate_ctr, stage);
r4d_chain_done();
}
// The same write with the MoE gather as its prologue. The routed experts' rows go back to token
// order, y[t][i] = sum over t's slots, ascending, of w[t][j] * y_expert[slot][i] rounded to bf16,
// with the shared arm folded in as moe_gather does; the word is pushed to the peer and kept as this
@@ -238,7 +259,7 @@ __global__ void r4d_ar_gather_inv_kernel(int* __restrict__ inv, const int* __res
}
template <bool INV>
__global__ void r4d_ar_gather_hc_write_kernel(
__device__ __forceinline__ void r4d_ar_gather_hc_write_kernel_body(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
@@ -326,6 +347,28 @@ __global__ void r4d_ar_gather_hc_write_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <bool INV>
__global__ void r4d_ar_gather_hc_write_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G,
const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) {
r4d_ar_gather_hc_write_kernel_body<INV>(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, G, inv, gate, gate_ctr, stage);
}
template <bool INV>
__global__ void r4dchain_ar_gather_hc_write(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G,
const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) {
r4d_chain_wait();
r4d_ar_gather_hc_write_kernel_body<INV>(y4, peer_base, my_base, peer_flags, my_flags, seq_ctrs, inj, h, n16, n, hc, irow, hrow, slot_stride16, drain, acq, nbw, G, inv, gate, gate_ctr, stage);
r4d_chain_done();
}
// The IPC handle goes into a caller-owned buffer of R4D_AR_HANDLE_BYTES so this stays a C ABI.
static_assert(sizeof(hipIpcMemHandle_t) <= R4D_AR_HANDLE_BYTES, "ipc handle larger than the ABI buffer");
@@ -420,7 +463,7 @@ int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, lon
void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n,
long hc, long irow, long hrow, long stream_i, long nblocks, long nthreads,
long drain, long acq, long gate, long gate_ctr, long stage) {
long drain, long acq, long gate, long gate_ctr, long stage, long chain) {
hipStream_t st = (hipStream_t)stream_i;
if (n <= 0 || M <= 0 || n % 8) throw std::runtime_error("ar_hc_write: n must be a positive multiple of 8");
if (hc < 1 || hrow % 8) throw std::runtime_error("ar_hc_write: the streams must be whole 16B words");
@@ -436,7 +479,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m
if (nt < 64) nt = 64;
if (nt > 1024) nt = 1024;
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
r4d_ar_hc_write_kernel<<<nb, nt, 0, st>>>(
(chain ? r4dchain_ar_hc_write : r4d_ar_hc_write_kernel)<<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw,
@@ -448,7 +491,8 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
long n, long hc, long irow, long hrow, long ye, long ew, long sorted,
long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld,
long top_k, long sig, long stream_i, long nblocks, long nthreads,
long drain, long acq, long inv, long gate, long gate_ctr, long stage) {
long drain, long acq, long inv, long gate, long gate_ctr, long stage,
long chain) {
hipStream_t st = (hipStream_t)stream_i;
if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1;
if (top_k < 1 || top_k > R4D_ARG_SLOTS) return -2;
@@ -488,13 +532,13 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
G.top_k = (int)top_k; G.T = (int)(M * top_k); G.sig = (int)sig;
if (by_inv) {
r4d_ar_gather_inv_kernel<<<1, 1024, 0, st>>>((int*)inv, (const int*)sorted, G.T);
r4d_ar_gather_hc_write_kernel<true><<<nb, nt, 0, st>>>(
(chain ? r4dchain_ar_gather_hc_write<true> : r4d_ar_gather_hc_write_kernel<true>)<<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G,
(const int*)inv, (long long*)gate, (unsigned int*)gate_ctr, stage);
} else {
r4d_ar_gather_hc_write_kernel<false><<<nb, nt, 0, st>>>(
(chain ? r4dchain_ar_gather_hc_write<false> : r4d_ar_gather_hc_write_kernel<false>)<<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G,
+15
View File
@@ -83,3 +83,18 @@ __device__ __forceinline__ void r4d_chain_done() {
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
}
#endif /* __HIP__ */
/* The launchers given a chained form here take it only at steps of up to 32 token rows: above that
* the waiting blocks hold room a wide predecessor needs. Flash-Next on 2x R9700 at MTP depth 5 with
* the adaptive window, sampled: 32 against 64 rows 214/349/494/654/890 -> 218/355/494/662/893 tok/s
* at 1/2/4/8/16 streams. */
constexpr long long kR4dChainMaxRows = 32;
inline bool r4d_chain_rows_ok(long long rows) { return rows <= kR4dChainMaxRows; }
/* A launcher that takes no RadArgs reads its row's `chain` here; the plugin
* ABI entry sets it around the launch only, so a direct C call never chains. */
inline thread_local bool g_r4d_chain_arg = false;
struct R4dChainArg {
explicit R4dChainArg(bool on) { g_r4d_chain_arg = on; }
~R4dChainArg() { g_r4d_chain_arg = false; }
};
+55 -10
View File
@@ -36,6 +36,7 @@
#include "r4d_ar_seq.h" // the all-reduce sequence step the fused all-reduce + norm takes
#include "r4d_fp8_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_common.h" // r4d_act_threads: the workgroup width, shared with the int8 path
#include "r4d_fwht.h" // the in-register rotation the `_had_` forms put before the absmax
#include "r4d_q8.h" // the 8-bit codes: E4M3, or int8 for an int8 trunk linear
@@ -215,7 +216,7 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
// The launcher sizes the workgroup to the row's groups (capped at r4d_act_threads' width) and the
// kernel reads the width from blockDim, so a narrow row does not leave most waves idle.
template <int ACT, bool ROT = false, bool I8 = false>
__global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
__device__ __forceinline__ void gated_quant_fp8_kernel_body(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld,
uint32_t q_ld, uint32_t s_ld) {
@@ -251,6 +252,24 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int ACT, bool ROT = false, bool I8 = false>
__global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld,
uint32_t q_ld, uint32_t s_ld) {
gated_quant_fp8_kernel_body<ACT, ROT, I8>(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld);
}
template <int ACT, bool ROT = false, bool I8 = false>
__global__ __launch_bounds__(1024) void r4dchain_gated_quant_fp8(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t gu_ld, uint32_t y_ld,
uint32_t q_ld, uint32_t s_ld) {
r4d_chain_wait();
gated_quant_fp8_kernel_body<ACT, ROT, I8>(gu, y, q, s, n, nkb, gu_ld, y_ld, q_ld, s_ld);
r4d_chain_done();
}
// -------------------------------------------------- gate . x -> quant, two source buffers
//
// The same epilogue with the gate in a separate buffer. For gated attention, `x` is the attention
@@ -267,7 +286,7 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
// and the absmax, as gated_quant_fp8_kernel's ROT, for an out projection stored rotated: the codes
// are had_quant_act_i8g's over `y`.
template <int ACT, bool I8 = false, bool ROT = false>
__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
__device__ __forceinline__ void gate_quant_fp8_kernel_body(
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld,
uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) {
@@ -313,6 +332,24 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int ACT, bool I8 = false, bool ROT = false>
__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld,
uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) {
gate_quant_fp8_kernel_body<ACT, I8, ROT>(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld);
}
template <int ACT, bool I8 = false, bool ROT = false>
__global__ __launch_bounds__(1024) void r4dchain_gate_quant_fp8(
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld,
uint32_t x_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld) {
r4d_chain_wait();
gate_quant_fp8_kernel_body<ACT, I8, ROT>(g, x, y, q, s, n, nkb, g_ld, x_ld, y_ld, q_ld, s_ld);
r4d_chain_done();
}
// -------------------------------------------------------- all-reduce -> rmsnorm -> quant
//
// The same norm with the tensor-parallel all-reduce that always precedes it folded in (o_proj,
@@ -808,7 +845,7 @@ extern "C" int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long
// projection; `rot` alone pairs with a rotated four-bit expert, which reads E4M3.
static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, int mode,
int gu_ld, int y_ld, int q_ld, int s_ld, RadStream stream,
bool rot, bool i8 = false) {
bool rot, bool i8 = false, bool chain = false) {
int emit_rc = RAD_OK;
if (!gu || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
@@ -824,7 +861,8 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n,
// there is no cross-row reduction and the rotation is wave-local (r4d_fwht.h).
const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave;
#define R4D_GQ_R(a, R, I) \
emit_rc = R4D_EMIT(stream, (gated_quant_fp8_kernel<a, R, I>), dim3((uint32_t)M), dim3(thr), \
emit_rc = R4D_EMIT(stream, (chain ? &r4dchain_gated_quant_fp8<a, R, I> \
: &gated_quant_fp8_kernel<a, R, I>), dim3((uint32_t)M), dim3(thr), \
0, (const uint16_t*)gu, (uint16_t*)y, (uint8_t*)q, \
(float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)gu_ld, (uint32_t)y_ld, \
(uint32_t)q_ld, (uint32_t)s_ld)
@@ -888,11 +926,15 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in
// A wave a group, capped at r4d_act_threads' width, as gated_quant_fp8 above.
const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave;
#define R4D_GTQ_I(a, I) \
emit_rc = rot ? R4D_EMIT(stream, (gate_quant_fp8_kernel<a, true, true>), dim3((uint32_t)M), \
dim3(thr), 0, (const uint16_t*)g, (const uint16_t*)x, (uint16_t*)y, \
(uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)g_ld, \
(uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, (uint32_t)s_ld) \
: R4D_EMIT(stream, (gate_quant_fp8_kernel<a, I>), dim3((uint32_t)M), dim3(thr), 0, \
emit_rc = rot ? R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_gate_quant_fp8<a, true, true> \
: &gate_quant_fp8_kernel<a, true, true>), \
dim3((uint32_t)M), dim3(thr), 0, (const uint16_t*)g, \
(const uint16_t*)x, (uint16_t*)y, (uint8_t*)q, (float*)s, \
(uint32_t)n, (uint32_t)nkb, (uint32_t)g_ld, (uint32_t)x_ld, \
(uint32_t)y_ld, (uint32_t)q_ld, (uint32_t)s_ld) \
: R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_gate_quant_fp8<a, I> \
: &gate_quant_fp8_kernel<a, I>), dim3((uint32_t)M), \
dim3(thr), 0, \
(const uint16_t*)g, (const uint16_t*)x, \
(uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, \
(uint32_t)g_ld, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
@@ -1124,7 +1166,9 @@ static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot, boo
if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED);
const int e = gated_quant_fp8_launch(r4d_addr(gu), y ? r4d_addr(y) : 0, r4d_addr(q),
r4d_addr(sc), (int)M, (int)K, mode, (int)gp, (int)yp,
(int)qp, (int)sp, stream, rot, q->dtype == RAD_I8);
(int)qp, (int)sp, stream, rot, q->dtype == RAD_I8,
/* decode heights: its rows are tokens or routed slots */
r4d_geti_or(a, "chain", 0) != 0 && M <= 1024);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -1190,6 +1234,7 @@ static int rad_gate_quant(const RadArgs* a, RadStream stream, bool rot) {
if (gp < 0 || xp < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
const int mode = act_mode(a, 1); /* sigmoid: gated attention */
if (mode < 0) return R4D_NO(RAD_E_UNSUPPORTED);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0 && M <= 1024);
const int e = gate_quant_fp8_emit(r4d_addr(g), r4d_addr(x), y ? r4d_addr(y) : 0,
r4d_addr(q), r4d_addr(sc), (int)M, (int)K, mode,
(int)gp, (int)xp, (int)yp, (int)qp, (int)sp, stream,
@@ -32,6 +32,7 @@
#include "r4d_gdn_wmma.h"
#include "r4d_common.h"
#include "r4d_gdn_conv_tap.h"
#include "r4d_chain.h"
#include "r4d_q8.h" // the 8-bit codes the folded quantiser writes: E4M3 or int8
#include "r4d_fwht.h" // NORM 3: had_quant_act_i8g's rotation before the int8 codes
#include <cstdlib>
@@ -218,8 +219,7 @@ __device__ __forceinline__ void ru_conv_rewrite(unsigned short* sp, const unsign
template <int ABF16, int NORM, int VS, int NT, int ANC, int STG = 0, int SDT = 0,
int CV = 0>
__global__ __launch_bounds__(RU_V / VS * 2)
void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
__device__ __forceinline__ void r4d_gdn_recurrent_update_kernel_body(const unsigned short* __restrict__ q,
const unsigned short* __restrict__ k,
const unsigned short* __restrict__ v,
const void* __restrict__ av,
@@ -239,8 +239,7 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
long zg_pitch,
const float* __restrict__ nw, float neps, int nact,
int H, int Hg, float scale, float sp_thr,
const RuConv cv)
{
const RuConv cv) {
using ST = typename ru_state<SDT>::T;
constexpr int NR = RU_V / VS; // v rows this workgroup owns
constexpr int THR = NR * 2;
@@ -732,6 +731,62 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int ABF16, int NORM, int VS, int NT, int ANC, int STG = 0, int SDT = 0,
int CV = 0>
__global__ __launch_bounds__(RU_V / VS * 2)
void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
const unsigned short* __restrict__ k,
const unsigned short* __restrict__ v,
const void* __restrict__ av,
const void* __restrict__ bv, long ab_stride,
const float* __restrict__ A_log,
const float* __restrict__ dt_bias,
typename ru_state<SDT>::T* __restrict__ state,
long st_slot, long st_head,
unsigned short* __restrict__ o,
unsigned char* __restrict__ oq,
float* __restrict__ os, long oq_pitch,
long os_ld,
const int* __restrict__ cu,
const int* __restrict__ sidx, long sidx_stride,
const int* __restrict__ naccept,
const unsigned short* __restrict__ zg,
long zg_pitch,
const float* __restrict__ nw, float neps, int nact,
int H, int Hg, float scale, float sp_thr,
const RuConv cv) {
r4d_gdn_recurrent_update_kernel_body<ABF16, NORM, VS, NT, ANC, STG, SDT, CV>(q, k, v, av, bv, ab_stride, A_log, dt_bias, state, st_slot, st_head, o, oq, os, oq_pitch, os_ld, cu, sidx, sidx_stride, naccept, zg, zg_pitch, nw, neps, nact, H, Hg, scale, sp_thr, cv);
}
template <int ABF16, int NORM, int VS, int NT, int ANC, int STG = 0, int SDT = 0,
int CV = 0>
__global__ __launch_bounds__(RU_V / VS * 2)
void r4dchain_gdn_recurrent_update(const unsigned short* __restrict__ q,
const unsigned short* __restrict__ k,
const unsigned short* __restrict__ v,
const void* __restrict__ av,
const void* __restrict__ bv, long ab_stride,
const float* __restrict__ A_log,
const float* __restrict__ dt_bias,
typename ru_state<SDT>::T* __restrict__ state,
long st_slot, long st_head,
unsigned short* __restrict__ o,
unsigned char* __restrict__ oq,
float* __restrict__ os, long oq_pitch,
long os_ld,
const int* __restrict__ cu,
const int* __restrict__ sidx, long sidx_stride,
const int* __restrict__ naccept,
const unsigned short* __restrict__ zg,
long zg_pitch,
const float* __restrict__ nw, float neps, int nact,
int H, int Hg, float scale, float sp_thr,
const RuConv cv) {
r4d_chain_wait();
r4d_gdn_recurrent_update_kernel_body<ABF16, NORM, VS, NT, ANC, STG, SDT, CV>(q, k, v, av, bv, ab_stride, A_log, dt_bias, state, st_slot, st_head, o, oq, os, oq_pitch, os_ld, cu, sidx, sidx_stride, naccept, zg, zg_pitch, nw, neps, nact, H, Hg, scale, sp_thr, cv);
r4d_chain_done();
}
// Non-temporal hint on the state load and store (TH_LOAD_NT / TH_STORE_NT): no result changes;
// chosen per launch because its cost and saving land in different kernels. In isolation it makes
// this kernel 43.8% slower (DRAM-write bound), but no state survives the 64 MB last-level cache
@@ -763,6 +818,14 @@ static bool ru_anchor() {
#define RU_NT_MB 16
// `oq_i8` picks the folded quantiser's codes: E4M3 (0) or int8 (1); see the kernel's epilogue.
/* The chained form (r4d_chain.h) for this thread's launch: set by the plugin ABI entries below from
* the row's `chain`, around their launch only, so the C entry point never chains. */
static thread_local bool g_ru_chain = false;
struct RuChainScope {
explicit RuChainScope(bool on) { g_ru_chain = on; }
~RuChainScope() { g_ru_chain = false; }
};
static int ru_update_launch(
const void* q, const void* k, const void* v, const void* a, const void* b,
long ab_stride, int ab_is_bf16, const void* A_log, const void* dt_bias, void* state,
@@ -788,7 +851,8 @@ static int ru_update_launch(
dim3 grid(N, H, vs), blk(RU_V / vs * 2);
// Every switch is a template parameter; the nested pick macros enumerate the instantiations.
#define RU_LAUNCH(AB, NM, VSC, NTC, ANCC, STGC, SDTC) \
hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<AB, NM, VSC, NTC, ANCC, STGC, SDTC>), \
hipLaunchKernelGGL((g_ru_chain ? &r4dchain_gdn_recurrent_update<AB, NM, VSC, NTC, ANCC, STGC, SDTC> \
: &r4d_gdn_recurrent_update_kernel<AB, NM, VSC, NTC, ANCC, STGC, SDTC>), \
grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)q, (const unsigned short*)k, \
(const unsigned short*)v, a, b, ab_stride, \
@@ -928,7 +992,8 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
else 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>), \
hipLaunchKernelGGL((g_ru_chain ? &r4dchain_gdn_recurrent_update<1, NM, 1, NTC, ANCC, 0, SDTC, CVC> \
: &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, \
@@ -1051,6 +1116,7 @@ extern "C" int r4d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) {
/* Slot and head strides come from the tensor, so a cache with padded slots is served too
* (see the header); the engine's own state cache is dense ([n_states, H, V, K] per layer). */
const RuChainScope chain_scope(r4d_geti_or(a, "chain", 0) != 0);
return R4D_RAW(ru_update_launch(
q->data, k->data, v->data, ta->data, tb->data, (long)ab_stride, ab_is_bf16,
alog->data, dtb->data, state->data,
@@ -1171,6 +1237,7 @@ static int gdn_conv_recurrent_entry(const RadArgs* a, RadStream s, bool had) {
cv.ctr = ru_conv_ctr(s, o->data);
if (!cv.ctr) return R4D_NO(RAD_E_NOMEM);
const RuChainScope chain_scope(r4d_geti_or(a, "chain", 0) != 0);
return ru_conv_recurrent_launch(
cv, ta->data, tb->data, (long)ab_stride, alog->data, dtb->data, state->data,
(long)state->stride[0], (long)state->stride[1], o->data, oq ? oq->data : nullptr,
+1007 -35
View File
File diff suppressed because it is too large. Load diff
+89 -6
View File
@@ -42,6 +42,7 @@
#include "r4d_fp8_wmma.h"
#include "r4d_plugin.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_gemm_args.h"
#include "r4d_moe_sort.h"
#include "r4d_moe_gather.h"
@@ -677,8 +678,7 @@ constexpr uint32_t moe_waves(uint32_t ntl, int w4, bool es, bool al, uint32_t fk
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4 = 0,
bool ES = false, bool AL = false, bool SK = false, uint32_t FK = kFK, bool UW = false,
bool RS = false>
__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS))
void moe_gemm_q_kernel(
__device__ __forceinline__ void moe_gemm_q_kernel_body(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
@@ -1431,6 +1431,36 @@ void moe_gemm_q_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4 = 0,
bool ES = false, bool AL = false, bool SK = false, uint32_t FK = kFK, bool UW = false,
bool RS = false>
__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS))
void moe_gemm_q_kernel(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
uint16_t* __restrict__ Y, const uint32_t* __restrict__ map,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
moe_gemm_q_kernel_body<MT, NTL, WGM, WGN, W4, ES, AL, SK, FK, UW, RS>(Aq, As, c_even, c_odd, c_2, c_3, sorted, off, Y, map, T, N, n_expert, top_k, a_ld, as_ld, y_ld, mode, tab);
}
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4 = 0,
bool ES = false, bool AL = false, bool SK = false, uint32_t FK = kFK, bool UW = false,
bool RS = false>
__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS))
void r4dchain_moe_gemm_q(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
uint16_t* __restrict__ Y, const uint32_t* __restrict__ map,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
r4d_chain_wait();
moe_gemm_q_kernel_body<MT, NTL, WGM, WGN, W4, ES, AL, SK, FK, UW, RS>(Aq, As, c_even, c_odd, c_2, c_3, sorted, off, Y, map, T, N, n_expert, top_k, a_ld, as_ld, y_ld, mode, tab);
r4d_chain_done();
}
/* ================================================================== moe_gemm_q, the down decode form
*
* The sorted-operand projection at decode: one block per run tile, G column tiles per block.
@@ -1463,7 +1493,7 @@ void moe_gemm_q_kernel(
* Sorted operand only: a run's activation rows are [rs, re) of `Aq` with no gather. Every row in a
* run is a placed slot (the scatter fills exactly [0, off[n_expert])), so `sorted` is not read. */
template <int W4>
__global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel(
__device__ __forceinline__ void moe_down_dec_kernel_body(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ off, uint16_t* __restrict__ Y,
@@ -1769,6 +1799,28 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int W4>
__global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ off, uint16_t* __restrict__ Y,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
moe_down_dec_kernel_body<W4>(Aq, As, c_even, c_odd, c_2, c_3, off, Y, T, N, n_expert, G, a_ld, as_ld, y_ld, mode, tab);
}
template <int W4>
__global__ __launch_bounds__(4 * kWave) void r4dchain_moe_down_dec(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ off, uint16_t* __restrict__ Y,
uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G,
uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) {
r4d_chain_wait();
moe_down_dec_kernel_body<W4>(Aq, As, c_even, c_odd, c_2, c_3, off, Y, T, N, n_expert, G, a_ld, as_ld, y_ld, mode, tab);
r4d_chain_done();
}
/* One or a few routed rows at I4 with BF16 scales per 128 K (signed or a 16-entry codebook).
* A block owns one sorted row and 64 columns;
* the two halves of each wave read the same activation row and their own eight K bytes directly
@@ -2848,6 +2900,9 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
* rows take the aligned 32-row form; r4d_moe_decode_band has the crossover. */
const uint32_t ny = (uint32_t)(N / 64);
const int form = g_moe_prefill_form;
/* The chained forms (r4d_chain.h) where the row resolved with `chain`, at decode heights. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 &&
r4d_chain_rows_ok(a_sorted ? (T + top_k - 1) / top_k : M);
if ((form == 0 && r4d_moe_decode_band(T, n_expert)) || form == 2) {
/* The decode grid is (tile, run) wide (the kernel's ES note); decode has one tile of rows,
* which alone would give only N/64 workgroups. */
@@ -2861,7 +2916,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
if (dn_dec && g2 > 0) {
const unsigned slots = (unsigned)(std::min(T, n_expert) + (T + 15) / 16);
const unsigned groups = (unsigned)((N + 64 * g2 - 1) / (64 * g2));
emit_rc = R4D_EMIT(stream, (moe_down_dec_kernel<W4>),
emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_moe_down_dec<W4> : &moe_down_dec_kernel<W4>),
dim3(slots + 1u, groups), dim3(4 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)off->data, (uint16_t*)Y->data,
@@ -2878,6 +2933,9 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) {
const bool rs = n_expert <= (long long)kMaxExpert;
auto pick = [&](auto fk) {
constexpr uint32_t F = decltype(fk)::value;
if (ch)
return rs ? &r4dchain_moe_gemm_q<1, 4, 1, 4, W4, true, false, false, F, true, true>
: &r4dchain_moe_gemm_q<1, 4, 1, 4, W4, true, false, false, F, true, false>;
return rs ? &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, true>
: &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, false>;
};
@@ -3404,7 +3462,7 @@ struct RgGeom {
/* `lg` is neither const nor __restrict__: every block writes it and the last one reads it back. */
template <uint32_t MAXOWN, uint32_t NW>
__global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel(
__device__ __forceinline__ void router_gemm_topk_scatter_kernel_body(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ W,
const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate,
int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted,
@@ -3472,6 +3530,28 @@ __global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel(
scatter_small_place(sorted, off, cnt, g.M * g.top_k, g.n_local, sl);
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <uint32_t MAXOWN, uint32_t NW>
__global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ W,
const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate,
int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted,
int32_t* __restrict__ off, int32_t* __restrict__ cnt, unsigned int* __restrict__ ctr,
RgGeom g, Protect prot) {
router_gemm_topk_scatter_kernel_body<MAXOWN, NW>(A, W, Wg, lg, gate, ids, w, sorted, off, cnt, ctr, g, prot);
}
template <uint32_t MAXOWN, uint32_t NW>
__global__ __launch_bounds__(NW * kWave) void r4dchain_router_gemm_topk_scatter(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ W,
const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate,
int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted,
int32_t* __restrict__ off, int32_t* __restrict__ cnt, unsigned int* __restrict__ ctr,
RgGeom g, Protect prot) {
r4d_chain_wait();
router_gemm_topk_scatter_kernel_body<MAXOWN, NW>(A, W, Wg, lg, gate, ids, w, sorted, off, cnt, ctr, g, prot);
r4d_chain_done();
}
/* The arrival counter belongs to the op instance and is taken at init, not on the launch path.
*
* It must persist between launches, zeroed (the last block resets it; a non-zero start would rank
@@ -3645,9 +3725,12 @@ extern "C" int r4d_rad_router_gemm_topk_scatter(const RadArgs* a, RadStream stre
g.sk = (uint32_t)cr.sk; g.tpb = (uint32_t)tpb;
g.nrb = (uint32_t)nrb; g.skg = wg ? (uint32_t)cg.sk : 0u;
const dim3 grid((unsigned)(nrb + (wg ? 1 : 0)), (unsigned)((M + 15) / 16));
/* The chained form (r4d_chain.h) where the row resolved with `chain`. */
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && r4d_chain_rows_ok(M);
#define R4D_RG_L(OWN, NWV) \
emit_rc = R4D_EMIT(stream, (router_gemm_topk_scatter_kernel<OWN, NWV>), grid, \
emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_router_gemm_topk_scatter<OWN, NWV> \
: &router_gemm_topk_scatter_kernel<OWN, NWV>), grid, \
dim3((NWV) * kWave), lds, \
(const uint16_t*)x->data, (const uint16_t*)wr->data, \
wg ? (const uint16_t*)wg->data : (const uint16_t*)nullptr, \
+32 -2
View File
@@ -19,6 +19,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_common.h"
#include "rad_yarn.h"
#include <hip/hip_bf16.h>
@@ -67,7 +68,7 @@ enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4
* writes that element and the head's v element into the cache at the token's slot, as E4M3 with
* kv_store_fp8's arithmetic or as bf16 like kv_store_bf16 (see the store at the end). */
template <int HD, int KV = QK_KV_NONE>
__global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
__device__ __forceinline__ void r4d_qk_norm_rope_gate_kernel_body(
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K,
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO,
__hip_bfloat16* __restrict__ GO,
@@ -274,6 +275,32 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int HD, int KV = QK_KV_NONE>
__global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K,
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO,
__hip_bfloat16* __restrict__ GO,
const void* __restrict__ WQ, const void* __restrict__ WK,
const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows,
int nq, int nkv, int rot, float eps, float wadd,
int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) {
r4d_qk_norm_rope_gate_kernel_body<HD, KV>(QG, K, QO, KO, GO, WQ, WK, CS, POS, cs_rows, nq, nkv, rot, eps, wadd, qg_pitch, k_pitch, cs_f32, pos_i64, w_f32, kvs);
}
template <int HD, int KV = QK_KV_NONE>
__global__ __launch_bounds__(256) void r4dchain_qk_norm_rope_gate(
const __hip_bfloat16* __restrict__ QG, const __hip_bfloat16* __restrict__ K,
__hip_bfloat16* __restrict__ QO, __hip_bfloat16* __restrict__ KO,
__hip_bfloat16* __restrict__ GO,
const void* __restrict__ WQ, const void* __restrict__ WK,
const void* __restrict__ CS, const void* __restrict__ POS, long cs_rows,
int nq, int nkv, int rot, float eps, float wadd,
int qg_pitch, int k_pitch, int cs_f32, int pos_i64, int w_f32, QkKvStore kvs) {
r4d_chain_wait();
r4d_qk_norm_rope_gate_kernel_body<HD, KV>(QG, K, QO, KO, GO, WQ, WK, CS, POS, cs_rows, nq, nkv, rot, eps, wadd, qg_pitch, k_pitch, cs_f32, pos_i64, w_f32, kvs);
r4d_chain_done();
}
// ============================================================ the cos/sin table
//
// The fused kernel reads a precomputed table instead of theta, and this fills it: one launch per
@@ -376,7 +403,10 @@ static int qk_body(const RadArgs* args, RadStream stream, const QkKvStore& kvs)
const int nh = (int)(nq + nkv);
// One block per (token, head), 256 threads, one element per lane. The width is fixed at 256, not
// fitted to the head count, so the sum of squares matches r4d_rmsnorm_bf16 (see the kernel).
#define R4D_QKG_L(H) emit_rc = R4D_EMIT(stream, (r4d_qk_norm_rope_gate_kernel<H, KVF>), \
/* The chained form (r4d_chain.h) where the row resolved with `chain`. */
const bool ch = r4d_geti_or(args, "chain", 0) != 0 && r4d_chain_rows_ok(M);
#define R4D_QKG_L(H) emit_rc = R4D_EMIT(stream, (ch ? &r4dchain_qk_norm_rope_gate<H, KVF> \
: &r4d_qk_norm_rope_gate_kernel<H, KVF>), \
dim3((int)M, nh), dim3(256), 0, (const __hip_bfloat16*)r4d_p(qg), \
(const __hip_bfloat16*)r4d_p(k), (__hip_bfloat16*)r4d_wp(qo), (__hip_bfloat16*)r4d_wp(ko), \
(__hip_bfloat16*)r4d_wp(go), r4d_p(wq), r4d_p(wk), r4d_p(cs), r4d_p(po), (long)cs_rows, \
+24 -2
View File
@@ -30,6 +30,7 @@
#include "r4d_args.h"
#include "rad_yarn.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_common.h" // r4d_wave_sum
#include <hip/hip_runtime.h>
@@ -54,7 +55,7 @@ __device__ __forceinline__ int qbk_comp(int mode, int i, int s0, int s1, int s2)
return i < s0 ? 0 : (i < s0 + s1 ? 1 : 2);
}
__global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
__device__ __forceinline__ void qsa_block_key_kernel_body(
const uint16_t* __restrict__ k, const float* __restrict__ w,
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out,
@@ -124,6 +125,26 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
((__hip_bfloat16*)out)[(size_t)orow * o_ld + t] = __float2bfloat16(res);
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
__global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
const uint16_t* __restrict__ k, const float* __restrict__ w,
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out,
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale,
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) {
qsa_block_key_kernel_body(k, w, page, bpos, out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn);
}
__global__ __launch_bounds__(kMaxN) void r4dchain_qsa_block_key(
const uint16_t* __restrict__ k, const float* __restrict__ w,
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out,
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale,
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) {
r4d_chain_wait();
qsa_block_key_kernel_body(k, w, page, bpos, out, n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn);
r4d_chain_done();
}
} // namespace
// k [M*ratio][n] bf16, `k_ld` elements a row (0 = n)
@@ -144,7 +165,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
if (!o_ld) o_ld = n;
/* n threads rounded up to whole waves for the block reduction (extra threads contribute 0). */
const int thr = ((n + 31) / 32) * 32;
return R4D_EMIT(stream, qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0,
return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_block_key : &qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0,
(const uint16_t*)k, (const float*)w, (const int32_t*)page,
(const int32_t*)bpos, (uint16_t*)out, n, ratio, rot, eps, wadd, theta, rscale,
pos0, k_ld, o_ld, mode, s0, s1, s2, bstep, mc, yarn);
@@ -217,6 +238,7 @@ extern "C" int r4d_rad_qsa_block_key(const RadArgs* a, RadStream stream) {
if (!rad_yarn_valid(yarn) ||
(yarn.factor != 0.0f && (rot <= 0 || r4d_getf(a, "scale", 1.0) != 1.0)))
return R4D_NO(RAD_E_INVAL);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
return r4d_qsa_block_key_bf16_emit(
r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o),
(int)M, (int)n, (int)ratio, (int)rot,
+24 -2
View File
@@ -20,6 +20,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_common.h"
#include "r4d_gdn_wmma.h"
@@ -242,7 +243,7 @@ constexpr long long kMxWavesTarget = 4096;
constexpr long long kMxMinTiles = 4;
template <int HEADS>
__global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel(
__device__ __forceinline__ void qsa_score_mx_kernel_body(
const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk,
const int32_t* __restrict__ bt, const int32_t* __restrict__ cu,
const int32_t* __restrict__ nc, float* __restrict__ out,
@@ -334,6 +335,26 @@ __global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <int HEADS>
__global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel(
const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk,
const int32_t* __restrict__ bt, const int32_t* __restrict__ cu,
const int32_t* __restrict__ nc, float* __restrict__ out,
int M, int nb, int nseq, int tpw, int q_ld, int bk_ld, int bt_ld, int out_ld, int vec) {
qsa_score_mx_kernel_body<HEADS>(q, bk, bt, cu, nc, out, M, nb, nseq, tpw, q_ld, bk_ld, bt_ld, out_ld, vec);
}
template <int HEADS>
__global__ __launch_bounds__(kMxWaves * kWave) void r4dchain_qsa_score_mx(
const unsigned short* __restrict__ q, const unsigned short* __restrict__ bk,
const int32_t* __restrict__ bt, const int32_t* __restrict__ cu,
const int32_t* __restrict__ nc, float* __restrict__ out,
int M, int nb, int nseq, int tpw, int q_ld, int bk_ld, int bt_ld, int out_ld, int vec) {
r4d_chain_wait();
qsa_score_mx_kernel_body<HEADS>(q, bk, bt, cu, nc, out, M, nb, nseq, tpw, q_ld, bk_ld, bt_ld, out_ld, vec);
r4d_chain_done();
}
/* Form override for tests (r4d_selftest compares the two): 0 = automatic, 1 = scalar,
* 2 = matrix. Like r4d_gemm_fp8a8_pin_mw. */
int g_qsa_form = 0;
@@ -374,7 +395,7 @@ static int r4d_qsa_score_bf16_emit(long q, long bk, long bt, long cu, long nc, l
const unsigned gx = (unsigned)((tiles + tpw * kMxWaves - 1) / (tpw * kMxWaves));
const int vec = (out_ld % 4 == 0) && ((out & 15) == 0);
#define RAD_QSA_MX(H) \
emit_rc = R4D_EMIT(stream, (qsa_score_mx_kernel<H>), dim3(gx, (unsigned)qt), \
emit_rc = R4D_EMIT(stream, (g_r4d_chain_arg ? &r4dchain_qsa_score_mx<H> : &qsa_score_mx_kernel<H>), dim3(gx, (unsigned)qt), \
dim3(kMxWaves * kWave), 0, (const unsigned short*)q, \
(const unsigned short*)bk, \
(const int32_t*)bt, (const int32_t*)cu, (const int32_t*)nc, \
@@ -461,6 +482,7 @@ extern "C" int r4d_rad_qsa_score(const RadArgs* a, RadStream stream) {
const long long qp = r4d_row_pitch(q), kp = r4d_row_pitch(bk);
const long long tp = r4d_row_pitch(bt), op = r4d_row_pitch(o);
if (qp < 0 || kp < 0 || tp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
return r4d_qsa_score_bf16_emit(r4d_addr(q), r4d_addr(bk), r4d_addr(bt), r4d_addr(cu),
r4d_addr(nc), r4d_addr(o),
(int)M, (int)n, (int)heads, (int)nb, (int)nseq,
+26 -2
View File
@@ -20,6 +20,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include "r4d_launch.h" // R4D_DYN_LDS
#include "r4d_common.h" // the DPP wave scans
@@ -129,7 +130,7 @@ __device__ __forceinline__ void counts_before(const uint32_t* wsum, int lane, in
* entirely in the query's past when b * ratio + ratio - 1 <= pos. At decode this equals the
* sequence's complete count. */
template <bool Signed>
__global__ __launch_bounds__(kThreads) void qsa_select_kernel(
__device__ __forceinline__ void qsa_select_kernel_body(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu,
@@ -294,6 +295,28 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
template <bool Signed>
__global__ __launch_bounds__(kThreads) void qsa_select_kernel(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu,
int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused,
int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, int cap) {
qsa_select_kernel_body<Signed>(score, bt, nc, pos, cu, sel, nsel, seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap);
}
template <bool Signed>
__global__ __launch_bounds__(kThreads) void r4dchain_qsa_select(
const float* __restrict__ score, const int32_t* __restrict__ bt,
const int32_t* __restrict__ nc, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu,
int32_t* __restrict__ sel, int32_t* __restrict__ nsel, int32_t* __restrict__ seqused,
int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, int cap) {
r4d_chain_wait();
qsa_select_kernel_body<Signed>(score, bt, nc, pos, cu, sel, nsel, seqused, nb, topk, ratio, nseq, s_ld, t_ld, o_ld, cap);
r4d_chain_done();
}
/* ===================================================== the wide-launch path, for a prefill chunk
*
* Without the key cache the kernel above reads every key from global memory five times, and its
@@ -1148,7 +1171,7 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long
/* Never more than the table width. */
int cap = (M <= kCacheMaxM) ? lds_cap_of() : 0;
if (cap > nb) cap = nb;
return R4D_EMIT(stream, qsa_select_kernel<Signed>, dim3((unsigned)M), dim3(kThreads),
return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_select<Signed> : &qsa_select_kernel<Signed>, dim3((unsigned)M), dim3(kThreads),
(size_t)cap * sizeof(uint32_t), (const float*)score, (const int32_t*)bt,
(const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu,
(int32_t*)sel, (int32_t*)nsel,
@@ -1168,6 +1191,7 @@ enum { QL_SCORE = 0, QL_BT = 1, QL_NC = 2, QL_POS = 3, QL_CU = 4, QL_SEL = 5, QL
QL_SEQ = 7 };
extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) {
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
const RadTensor* sc = r4d_opt(a, QL_SCORE);
const RadTensor* bt = r4d_opt(a, QL_BT);
const RadTensor* nc = r4d_opt(a, QL_NC);
+22 -2
View File
@@ -22,6 +22,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include <hip/hip_runtime.h>
#include <cstdint>
@@ -30,7 +31,7 @@ namespace {
constexpr int kThreads = 256;
__global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel(
__device__ __forceinline__ void qsa_tail_store_kernel_body(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx,
uint16_t* __restrict__ state,
@@ -59,6 +60,24 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel(
for (int d = (int)threadIdx.x; d < n; d += kThreads) state[dst + d] = k[src + d];
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
__global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx,
uint16_t* __restrict__ state,
int T, int n, int ring, int seqs, int slots, int k_ld, int s_slot, int s_row, int sidx_ld) {
qsa_tail_store_kernel_body(k, pos, cu, sidx, state, T, n, ring, seqs, slots, k_ld, s_slot, s_row, sidx_ld);
}
__global__ __launch_bounds__(kThreads) void r4dchain_qsa_tail_store(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx,
uint16_t* __restrict__ state,
int T, int n, int ring, int seqs, int slots, int k_ld, int s_slot, int s_row, int sidx_ld) {
r4d_chain_wait();
qsa_tail_store_kernel_body(k, pos, cu, sidx, state, T, n, ring, seqs, slots, k_ld, s_slot, s_row, sidx_ld);
r4d_chain_done();
}
} // namespace
// k [T][n] bf16, `k_ld` elements a row (0 = n)
@@ -75,7 +94,7 @@ static int r4d_qsa_tail_store_bf16_emit(long k, long pos, long cu, long sidx, lo
if (!k_ld) k_ld = n;
if (!s_row) s_row = n;
if (!sidx_ld) sidx_ld = 1;
return R4D_EMIT(stream, qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0,
return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_tail_store : &qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0,
(const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu,
(const int32_t*)sidx, (uint16_t*)state, T, n, ring, seqs, slots, k_ld, s_slot,
s_row, sidx_ld);
@@ -113,6 +132,7 @@ extern "C" int r4d_rad_qsa_tail_store(const RadArgs* a, RadStream stream) {
const long long kp = r4d_row_pitch(k);
if (kp < 0) return R4D_NO(RAD_E_STRIDE);
if (k->dtype != RAD_BF16 || st->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
return r4d_qsa_tail_store_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(sx),
r4d_addr(st), (int)T, (int)n, (int)ring, (int)seqs,
(int)st->shape[0], (int)kp, (int)st->stride[0],
+30 -2
View File
@@ -21,6 +21,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_chain.h"
#include <hip/hip_runtime.h>
#include <cstdint>
@@ -32,7 +33,7 @@ constexpr int kThreads = 128;
* row constraint on the declared seqs (rad-convert declares 256, which must still resolve). */
constexpr int kMaxSeq = 256;
__global__ __launch_bounds__(kThreads) void qsa_work_kernel(
__device__ __forceinline__ void qsa_work_kernel_body(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const uint16_t* __restrict__ state,
const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt,
@@ -113,6 +114,32 @@ __global__ __launch_bounds__(kThreads) void qsa_work_kernel(
}
}
/* The plain and chained forms (r4d_chain.h): every block leaves through the wrapper. */
__global__ __launch_bounds__(kThreads) void qsa_work_kernel(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const uint16_t* __restrict__ state,
const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt,
uint16_t* __restrict__ stage, int32_t* __restrict__ page, int32_t* __restrict__ bpos,
int32_t* __restrict__ nc,
int n, int ratio, int ring, int seqs, int max_work, int k_ld, int s_slot, int s_row,
int sidx_ld, int bt_ld, int g_ld, const int32_t* __restrict__ rope, int rplane,
int bstep) {
qsa_work_kernel_body(k, pos, cu, state, sidx, bt, stage, page, bpos, nc, n, ratio, ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, rope, rplane, bstep);
}
__global__ __launch_bounds__(kThreads) void r4dchain_qsa_work(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const uint16_t* __restrict__ state,
const int32_t* __restrict__ sidx, const int32_t* __restrict__ bt,
uint16_t* __restrict__ stage, int32_t* __restrict__ page, int32_t* __restrict__ bpos,
int32_t* __restrict__ nc,
int n, int ratio, int ring, int seqs, int max_work, int k_ld, int s_slot, int s_row,
int sidx_ld, int bt_ld, int g_ld, const int32_t* __restrict__ rope, int rplane,
int bstep) {
r4d_chain_wait();
qsa_work_kernel_body(k, pos, cu, state, sidx, bt, stage, page, bpos, nc, n, ratio, ring, seqs, max_work, k_ld, s_slot, s_row, sidx_ld, bt_ld, g_ld, rope, rplane, bstep);
r4d_chain_done();
}
} // namespace
// k [T][n] bf16, this step's raw index keys
@@ -140,7 +167,7 @@ static int r4d_qsa_work_bf16_emit(long k, long pos, long cu, long state, long si
if (!s_row) s_row = n;
if (!g_ld) g_ld = n;
if (!sidx_ld) sidx_ld = 1;
return R4D_EMIT(stream, qsa_work_kernel, dim3((unsigned)max_work), dim3(kThreads), 0,
return R4D_EMIT(stream, g_r4d_chain_arg ? &r4dchain_qsa_work : &qsa_work_kernel, dim3((unsigned)max_work), dim3(kThreads), 0,
(const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu,
(const uint16_t*)state, (const int32_t*)sidx, (const int32_t*)bt,
(uint16_t*)stage, (int32_t*)page, (int32_t*)bpos, (int32_t*)nc, n, ratio,
@@ -211,6 +238,7 @@ extern "C" int r4d_rad_qsa_work(const RadArgs* a, RadStream stream) {
const long long bp2 = r4d_row_pitch(bt), sp = r4d_row_pitch(st);
if (kp < 0 || bp2 < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE);
if (k->dtype != RAD_BF16 || tl->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
const R4dChainArg chain_arg(r4d_geti_or(a, "chain", 0) != 0);
return r4d_qsa_work_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(tl),
r4d_addr(sx), r4d_addr(bt), r4d_addr(st), r4d_addr(pg),
r4d_addr(bp), r4d_addr(nc), (int)n, (int)ratio, (int)ring,
+15
View File
@@ -11154,6 +11154,21 @@ extern "C" int rad_kernel_chain(int i) {
"dflash_select_bf16", "dflash_tree_bf16",
/* the weight read beside a collective (its blocks add before reading, r4d_prefetch.hip) */
"prefetch",
/* Flash-Next at decode heights: the MoE block */
"router_gemm_topk_scatter_bf16", "moe_gemm_fp8a8", "moe_gemm_fp8a8_mod4", "gated_quant_fp8",
/* ...and the rest of a delta-net layer */
"hc_read_bf16", "hc_read_e4m3", "gdn_recurrent_update_k128_v128_bf16_fp32state",
"gdn_conv_recurrent_update_k128_v128_bf16", "ar_hc_write", "ar_gather_hc_write",
/* the four-bit routed experts and their rotated quantiser */
"moe_gemm_w4a8", "moe_gemm_w4a8_mod4", "gated_had_quant_fp8", "gated_had_quant_i8g",
/* ...and an attention layer: the indexer, the norm/rope/gate, the quantiser before o_proj
* and the gqa6 decode rows (their split-KV decode and merge already have chained forms) */
"qk_norm_rope_gate", "qsa_work_bf16", "qsa_block_key_bf16", "qsa_tail_store_bf16",
"qsa_score_bf16", "qsa_select_i32", "gate_quant_fp8",
"attn_decode_h256_gqa6_fp8kv", "attn_decode_h256_gqa6_fp8v4", "attn_decode_h256_gqa6_k6v4",
"attn_decode_h256_gqa6_bf16kv", "attn_decode_h256_gqa6_bs4_fp8kv",
"attn_decode_h256_gqa6_bs4_bf16kv", "attn_decode_gq_h256_gqa6_bs4_fp8kv",
"attn_decode_gq_h256_gqa6_bs4_bf16kv",
};
for (const char* p : kChained)
if (std::strcmp(k->name, p) == 0) return 1;
+93 -18
View File
@@ -20276,15 +20276,21 @@ 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 two-grid
* form, 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. */
/* The gated residual's read at its decode kernels: the launcher's rule against the two-grid form,
* 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.
*
* Up to sixteen rows at this shape the rule serves decode forms G (1..8) and S (9..16) with kernel
* B3: bf16 WMMA dots, S scaling after the dot. Byte for byte they match neither the per-row kernels
* nor the tiled ones, so there d is held to an fp64 host reference - no further from it than the
* two-grid form's d - the inject gains must match byte for byte, and x must stay within rounding of
* the two-grid form's. Above sixteen rows both forms are the tiled path's and match byte for byte. */
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 two-grid form", (long long)M,
i8 ? "int8" : "E4M3");
const bool level = M <= 16;
const std::string nm = fmt("hc_read_e4m3 decode kernels at M=%lld, %s codes: the rule %s the "
"two-grid form", (long long)M, i8 ? "int8" : "E4M3",
level ? "as exact as" : "byte-identical to");
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; }
@@ -20359,6 +20365,7 @@ static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) {
}
struct Out { std::vector<uint8_t> x, inj, q, qs, rq, rs; std::vector<const void*> fns; };
Out out[2];
std::vector<uint8_t> dsv[2]; /* d: the scratch's first M x lr bf16 values */
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);
@@ -20379,19 +20386,87 @@ static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) {
};
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);
if (a.scratch) {
dsv[form].resize((size_t)(M * lr * 2));
st_memcpy(dsv[form].data(), a.scratch, dsv[form].size(), hipMemcpyDeviceToHost);
}
}
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;
std::string bad;
if (!level) {
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";
} else {
if (out[0].inj != out[1].inj) bad += " inj";
if (dsv[0].empty()) bad += " (no scratch for d)";
/* d against fp64: N unrounded, the dot over the decoded codes and their group scales. The
* error of each form as a fraction of the row's RMS of d, max and mean over every row. */
const int64_t G = r4d_hc8::down_group(HN);
double emax[2] = { 0, 0 }, esum[2] = { 0, 0 };
for (int64_t r0 = 0; r0 < M && !dsv[0].empty(); ++r0) {
std::vector<double> N((size_t)HN);
for (int64_t c = 0; c < hc; ++c) {
double ss = 0;
for (int64_t j = 0; j < n; ++j) {
const double v = h_bf16(hh[(size_t)(r0 * HN + c * n + j)]);
ss += v * v;
}
const double sc = 1.0 / std::sqrt(ss / (double)n + 1e-6);
for (int64_t j = 0; j < n; ++j)
N[(size_t)(c * n + j)] = h_bf16(hh[(size_t)(r0 * HN + c * n + j)]) * sc
* ((double)wg[(size_t)(c * n + j)] + 1.0);
}
std::vector<double> dref((size_t)lr);
double ssd = 0;
for (int64_t j = 0; j < lr; ++j) {
const uint8_t* row = down.data() + j * dld;
const float* gsc = (const float*)(row + HN);
double dot = 0;
for (int64_t kk = 0; kk < HN; ++kk)
dot += (double)h_e4m3(row[kk]) * (double)gsc[kk / G] * N[(size_t)kk];
const double z = dot / (double)hc;
dref[(size_t)j] = z / (1.0 + std::exp(-z));
ssd += dref[(size_t)j] * dref[(size_t)j];
}
const double rms = std::sqrt(ssd / (double)lr) + 1e-30;
for (int f = 0; f < 2; ++f) {
const uint16_t* df = (const uint16_t*)dsv[f].data();
for (int64_t j = 0; j < lr; ++j) {
const double e = std::fabs(h_bf16(df[r0 * lr + j]) - dref[(size_t)j]) / rms;
emax[f] = std::max(emax[f], e);
esum[f] += e;
}
}
}
const double cnt = (double)(M * lr);
if (esum[0] > esum[1] * 1.05 + 1e-6 * cnt || emax[0] > emax[1] * 1.10 + 1e-4)
bad += fmt(" d (rule %.5f / %.4f, two-grid %.5f / %.4f of RMS, mean / max)",
esum[0] / cnt, emax[0], esum[1] / cnt, emax[1]);
/* x: within rounding of the two-grid form's, as a fraction of the row's RMS. */
const uint16_t* x0 = (const uint16_t*)out[0].x.data();
const uint16_t* x1 = (const uint16_t*)out[1].x.data();
double xmax = 0, xsum = 0;
for (int64_t r0 = 0; r0 < M; ++r0) {
double ss = 0;
for (int64_t j = 0; j < n; ++j) { const double v = h_bf16(x1[r0 * n + j]); ss += v * v; }
const double rms = std::sqrt(ss / (double)n) + 1e-30;
for (int64_t j = 0; j < n; ++j) {
const double e = std::fabs(h_bf16(x0[r0 * n + j]) - h_bf16(x1[r0 * n + j])) / rms;
xmax = std::max(xmax, e);
xsum += e;
}
}
if (xsum / (double)(M * n) > 0.005 || xmax > 0.15)
bad += fmt(" x (%.5f mean, %.4f max of RMS)", xsum / (double)(M * n), xmax);
}
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")
@@ -33602,9 +33677,9 @@ 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 served decode kernels against the two-grid form: 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 })
/* The served decode kernels against the two-grid form: each row count of form G (1 to 8),
* form S at 12 and 16 rows, and the tiled up-mix at both of its row tiles. */
for (int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 32, 33, 64 })
for (bool i8 : { false, true }) hc_decode_forms(pl, m, i8);
}
if (sel("hc_read_bf16")) {