Merge main into laya-arch-plugin

This commit is contained in:
Brandon Bertelsen committed 2026-10-29 13:45:18 -04:00
commit ec243c2a7d
189 files changed
+11212 -7060

No files matched your search

+1
View File
@@ -198,6 +198,7 @@ set(R4D_UNITS
"r4d_lora_bf16|"
"r4d_dflash_conv_t2_g16_bf16|"
"r4d_dflash_select_bf16|"
"r4d_dflash_tree_bf16|"
# Routed MoE: router, scatter, the grouped block-scaled fp8 GEMM and gather, in one unit because
# the other three only feed the GEMM.
"r4d_moe|"
+32 -13
View File
@@ -82,6 +82,10 @@ struct R4DArgs {
// The engine's chained launch (RadKernelChainFn, r4d_chain.h): the decode path launches its
// chained forms. fill_paged sets it from the resolved `chain` parameter.
int chain;
// A tree verify (attn_paged_qrow_tree, docs/OPS.md): RadBatch::spec_parent, one int32 a query
// row, -2 for an ordinary causal row, else the row's parent's index within its sequence's rows
// (-1 for the block's first). Read only by the O_TREE instances; null elsewhere.
const int* spec_parent;
};
// Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook
@@ -129,6 +133,9 @@ long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a);
// ...with q at R4DArgs::q_ld (attn_paged_qrow).
int r4d_attn_decode_h256_gqa2_qld_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_qld_bf16kv (const R4DArgs* a, hipStream_t stream);
// ...and a tree verify's mask from R4DArgs::spec_parent (attn_paged_qrow_tree).
int r4d_attn_decode_h256_gqa2_qld_tree_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_qld_tree_bf16kv (const R4DArgs* a, hipStream_t stream);
// The geometry the attention kernels above are compiled for, so a caller can check a model
// before the first launch.
void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows);
@@ -291,18 +298,22 @@ void r4d_ar_ipc_enable_peer(long peer);
// VRAM. Zeroed; the address is valid on every card and the CPU. Startup-only.
long r4d_ar_host_alloc(long size);
void r4d_ar_host_free(long p);
// `stage`, the last argument of every 2-rank kernel below: 0, or a host-mailbox instance's mirror
// of its slots in this card's VRAM (same layout), which the reader's push check fills as it reads
// the slot so the reduce reads VRAM instead of the link a second time (r4d_ar_seq.h).
// Exact sum, fp32 accumulate, bf16 / fp16 / fp32 payload (dtype 0 / 1 / 2).
void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long inp, long out, long n_elem,
long dtype, long stream, long nblocks, long nthreads, long drain,
long acq);
long acq, long stage = 0);
// Same topology, with the wire payload Walsh-Hadamard rotated and quantised to 6 bits per element
// in groups of 64 (plus a bf16 scale per group). Lossy; bf16 / fp16 payload only. loc_pack is this
// rank's own packed copy, so the reduce folds exactly the bytes it sent.
void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long loc_pack, long slot_stride_bytes,
long scale_off_bytes, long inp, long out, long n_elem, long dtype,
long stream, long nblocks, long nthreads, long drain, long acq);
long stream, long nblocks, long nthreads, long drain, long acq,
long stage = 0);
// The exact all-reduce of `y` [M][n] bf16 with hc_write as its epilogue: h[r][c*n + i] +=
// inj[r][c] * y[r][i] over the reduced y, byte-identical to all_reduce then hc_write. `irow` and
// `hrow` are the pitches of inj [M][hc] and h [M][hc*n] in elements; y is tight. A non-zero `gate`
@@ -311,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 drain, long acq, long gate, long gate_ctr, long stage = 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.
@@ -323,7 +334,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, long nblocks, long nthreads,
long drain, long acq, long inv, long gate, long gate_ctr);
long drain, long acq, long inv, long gate, long gate_ctr,
long stage = 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
@@ -336,7 +348,7 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, l
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, long nblocks, long nthreads, long drain, long acq,
long gate, long gate_ctr);
long gate, long gate_ctr, long stage = 0);
int r4d_ar_max_blocks(void); // the two 2-rank kernels
void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems); // rotated-6-bit payload only
@@ -349,7 +361,7 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo
long seq_ctrs, long slot_stride16, long inp, long out, long n_elem,
long dtype, long rank, long row_elems, long stream, long nblocks,
long nthreads, long drain, long acq, long dpitch,
long spitch);
long spitch, long stage = 0);
// ---- all-reduce: one-shot, push, 4 or 8 ranks over P2P -------------------------------------
// The same algorithm at width (r4d_ar_oneshot_Nrank_exact.hip). Peer arguments are in ascending
@@ -703,8 +715,8 @@ void r4d_moe_gemm_pin_down_dec(int pin);
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
// passes pipelined from eight rows), 1 the two-grid form (A, then the up-mix in a second launch;
// the tiled up-mix's passes unpipelined). 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
@@ -745,6 +757,13 @@ int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws,
int a_ld, int sa_ld, int w_ld, int sw_ld,
int q_ld, int s_ld, int y_ld, long stream);
int r4d_gemm_fp8a8_gated_nt_m16_max_m(void);
// The same fold at any M (`gemm_nt_q_gated_wide`): past the narrow tile's 64 rows it takes the gated
// prefill tile, whose accumulators are the unfused prefill GEMM's, so its bytes are the pair's.
int r4d_gemm_fp8a8_gated_nt_wide(long a, long ascale, long wq, long ws,
long q, long s, long y, int act,
int M, int K, int nout,
int a_ld, int sa_ld, int w_ld, int sw_ld,
int q_ld, int s_ld, int y_ld, long stream);
// The narrow GEMM with a bias: `bias` bf16 [N], added to each output column's f32 accumulator before
// its one rounding, and C written at row pitch `c_ld` (0 = N), so C may be a column slice of a wider
// buffer. Never split. M up to r4d_gemm_fp8a8_nt_m16_max_m(); K a multiple of 128, N of 16.
@@ -799,7 +818,7 @@ int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long q, long s,
int r4d_gated_had_quant_i8g(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, long stream);
// The activation is rounded to bf16 before the product, matching the unfused `sigmoid` then `mul`
// pair with a bf16 buffer between them.
// pair with a bf16 buffer between them; `mode` 2 is the plain product (`mul` + quantiser).
// The same epilogue with the gate in a different buffer from what it scales, as in gated
// attention: `x` is the attention output and the gate a column slice of the [q|gate] projection.
// A row is then a (token, head) pair; both sources are a fixed stride apart and the scale plane
@@ -821,7 +840,7 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long wp = 0);
long loc_pack, long loc_scale_off, long wp = 0, long stage = 0);
int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void);
// Its rotated int8 form, as r4d_rmsnorm_had_quant_i8g: the reduction and the norm unchanged, the
// norm's pass quantised by had_quant_act_i8g's rule. No post-norm.
@@ -831,7 +850,7 @@ int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off);
long loc_pack, long loc_scale_off, long stage = 0);
// The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of
// the reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8
@@ -840,7 +859,7 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags
long seq_ctrs, long slot_stride16, long x, long res, long w, long wp,
long sc, int sc_f32, long y, long q, long s, int M, int n, float eps,
float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq);
int drain, int acq, long stage = 0);
// ...and at four ranks, on the wide family's transport: r4d_ar_oneshot_4rank_exact's IPC
// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, the
// engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h), and, with
@@ -913,7 +932,7 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags,
long x, long residual, long wgain, long out_bf16, long q, long s,
int M, int K, int had, float eps, float wadd,
long stream, int nblocks, int nthreads, int drain, int acq,
int wire = 0);
int wire = 0, long stage = 0);
// An elementwise gated product, then the same Hadamard and int8 quantiser. Mode 0 is silu(a)*b
// (down_proj's input, vLLM's silu_and_mul); mode 1 is sigmoid(a)*b (o_proj's input, since
// Qwen3_5Attention computes attn_output * sigmoid(gate)). Strides are in elements and may be 0 for
+30 -12
View File
@@ -99,6 +99,8 @@ int rv_barrier(int world) {
struct ArInst {
int rank = 0, world = 0;
long my_scratch = 0, my_flags = 0, my_seq = 0, locpack = 0;
/* A 2-rank host-mailbox instance's VRAM mirror of its slots, 0 otherwise (r4d_ar_seq.h). */
long my_stage = 0;
long peer_scratch[R4D_MAX_PEERS] = { 0 };
long peer_flags [R4D_MAX_PEERS] = { 0 };
long slot_bytes = 0; /* per-slot capacity, 16-byte aligned */
@@ -350,6 +352,17 @@ 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));
/* A host mailbox is read over the link past every cache, so the 2-rank kernels' push check
* copies what it reads into this VRAM mirror for the reduce, crossing the link once
* (r4d_ar_seq.h). Coarse-grained: only this rank's kernels touch it, each block its own words.
* The wide family has no push check and reads its slots once. Host-memory slots free the same
* VRAM over P2P, so the mirror keeps the footprint where the P2P instance has it. */
long stg = 0;
if (host && world == 2) {
R4D_TRY("ar_ipc_alloc(stage)",
stg = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 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 f32 scales 1/32 of
* it, laid out from half the slot; a row padded to whole 512-element chunks
@@ -365,6 +378,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
in->my_flags = fl;
in->my_seq = sq;
in->locpack = lp;
in->my_stage = stg;
in->gate_ctr = sq + 2L * maxb * 4; /* the word after the sequence counters (r4d_ar_seq.h) */
{
@@ -475,6 +489,7 @@ void release(ArInst* in) {
}
r4d_ar_ipc_free(in->my_seq);
r4d_ar_ipc_free(in->locpack);
r4d_ar_ipc_free(in->my_stage);
delete in;
}
@@ -799,7 +814,7 @@ extern "C" int r4d_rad_ar_gather_2rank(const RadArgs* a, RadStream s) {
r4d_ar_gather_2rank(in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags,
in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank,
(long)row, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain,
c.acq, (long)dpitch, (long)spitch));
c.acq, (long)dpitch, (long)spitch, in->my_stage));
return RAD_OK;
}
@@ -869,7 +884,8 @@ extern "C" int r4d_rad_ar_oneshot_2rank_exact(const RadArgs* a, RadStream s) {
r4d_ar_oneshot_2rank_exact(c.in->peer_scratch[0], c.in->my_scratch,
c.in->peer_flags[0], c.in->my_flags, c.in->my_seq,
c.in->slot16, c.inp, c.out, c.numel, c.in->dtype,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq));
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq,
c.in->my_stage));
return RAD_OK;
}
@@ -911,7 +927,8 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) {
r4d_ar_oneshot_2rank_exact(c.in->peer_scratch[0], c.in->my_scratch,
c.in->peer_flags[0], c.in->my_flags, c.in->my_seq,
c.in->slot16, c.inp, c.out, c.numel, c.in->dtype,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq));
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq,
c.in->my_stage));
return RAD_OK;
}
@@ -928,7 +945,8 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) {
c.in->peer_flags[0], c.in->my_flags, c.in->my_seq,
c.in->locpack, c.in->slot_bytes, c.in->slot_bytes / 2,
c.inp, c.out, c.numel, c.in->dtype,
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq));
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq,
c.in->my_stage));
return RAD_OK;
}
@@ -1283,7 +1301,7 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) {
r4d_addr(q), r4d_addr(sc),
(int)M, (int)K, (int)had, eps, wadd,
(long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq,
wire));
wire, in->my_stage));
return RAD_OK;
}
@@ -1404,7 +1422,7 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32,
(int)rp, (int)yp, (int)qp, (int)sp,
(long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire,
in->locpack, in->slot_bytes / 2)
in->locpack, in->slot_bytes / 2, in->my_stage)
: r4d_ar_rmsnorm_quant_fp8(
in->peer_scratch[0], in->my_scratch,
in->peer_flags[0], in->my_flags, in->my_seq,
@@ -1412,7 +1430,7 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32,
(int)rp, (int)yp, (int)qp, (int)sp,
(long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire,
in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0);
in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0, in->my_stage);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -1491,7 +1509,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)M,
(int)K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (long)(uintptr_t)s, nblocks, cfgv.drain,
cfgv.acq);
cfgv.acq, in->my_stage);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -1672,7 +1690,7 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) {
r4d_addr(ew), r4d_addr(so), 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, R4D_AR_WHT6_FUSED_THREADS, cfgv.drain, cfgv.acq,
early, early ? in->gate_ctr : 0L);
early, early ? in->gate_ctr : 0L, in->my_stage);
if (rc != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
@@ -1687,7 +1705,7 @@ 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);
early ? in->gate_ctr : 0L, in->my_stage);
if (rc != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
@@ -1803,7 +1821,7 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) {
in->locpack, in->slot_bytes, in->slot_bytes / 2, r4d_addr(y), r4d_addr(inj),
r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, (long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS,
cfgv.drain, cfgv.acq, early, early ? in->gate_ctr : 0L);
cfgv.drain, cfgv.acq, early, early ? in->gate_ctr : 0L, in->my_stage);
if (rc != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
@@ -1816,7 +1834,7 @@ 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));
early ? in->gate_ctr : 0L, in->my_stage));
return early ? RAD_LINK_ENDED : RAD_OK;
}
+8 -4
View File
@@ -60,7 +60,7 @@ __global__ void r4d_ar_gather_2rank_kernel(
const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4,
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq,
unsigned int nbw) {
unsigned int nbw, long stage) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
@@ -68,6 +68,7 @@ __global__ void r4d_ar_gather_2rank_kernel(
const int slot = (int)s_slot;
int4* ps = peer_base + (size_t)slot * slot_stride16;
const int4* ms = my_base + (size_t)slot * slot_stride16;
const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h)
const int w = (n16 + nb - 1) / nb;
const int start = b * w;
@@ -116,8 +117,10 @@ __global__ void r4d_ar_gather_2rank_kernel(
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
for (int k = start + tid; k < end; k += nt)
h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k);
});
ms = r4d_archk_moved(ms, md);
// Place the peer's slice, now staged in this rank's scratch.
{
@@ -136,7 +139,8 @@ __global__ void r4d_ar_gather_2rank_kernel(
void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long inp, long out, long n_elem,
long dtype, long rank, long row_elems, long stream_i, long nblocks,
long nthreads, long drain, long acq, long dpitch, long spitch) {
long nthreads, long drain, long acq, long dpitch, long spitch,
long stage) {
hipStream_t st = (hipStream_t)stream_i;
const int esize = (dtype == 2) ? 4 : 2;
const long nbytes = (long)n_elem * esize;
@@ -177,5 +181,5 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo
r4d_ar_gather_2rank_kernel<<<nb, nt, 0, st>>>(
(const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out,
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16,
(int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, (int)acq, nbw);
(int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, (int)acq, nbw, stage);
}
+18 -8
View File
@@ -125,7 +125,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
int4* peer_base, const int4* my_base,
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
int M, int K, int slot_stride16, int drain, int acq,
float eps, float wadd, float rnorm, unsigned int nbw) {
float eps, float wadd, float rnorm, unsigned int nbw, long stage) {
constexpr int VPL = HAD / 32, NW = THR / 32;
constexpr int MAXB = R4D_ARN_MAXVALS / VPL;
extern __shared__ float lds[];
@@ -146,6 +146,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
const unsigned int sq = s_seq;
int4* ps = peer_base + (size_t)s_slot * slot_stride16;
const int4* ms = my_base + (size_t)s_slot * slot_stride16;
const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h)
// WIRE == 6 only. The slot is split as in the standalone compressed all-reduce: packed symbols
// from the base, bf16 group scales from halfway. Chunk indices are global over the [M, K]
@@ -263,7 +264,8 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) {
if constexpr (WIRE == 0) {
const int wpr = K >> 3;
for (int k = r0 * wpr + tid; k < r1 * wpr; k += THR) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
for (int k = r0 * wpr + tid; k < r1 * wpr; k += THR)
h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k);
} else {
for (int ci = wave; ci < cpb; ci += NW) {
const int c = c00 + ci;
@@ -271,25 +273,32 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4);
#pragma unroll
for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4)
h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16),
h += r4d_archk_u4(r4d_archk_keep((const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16), md),
cd + (unsigned)(w4 * ARN_WV + lane * 4));
if constexpr (ARN_NWORD % 4 >= 2) {
const uint2 u = *(const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8);
const uint2 u =
r4d_archk_keep((const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8), md);
const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2);
h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u);
}
if constexpr (ARN_NWORD % 2 == 1)
h += r4d_archk_mix(*(const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4),
h += r4d_archk_mix(
r4d_archk_keep((const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4), md),
cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane));
#pragma unroll
for (int t = 0; t < ARN_ITERS; ++t) {
const int gl = t * ARN_GPW + gw;
if (lig == 0) h += r4d_archk_mix(m_sc[c * ARN_CG + gl], R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl));
if (lig == 0)
h += r4d_archk_mix(r4d_archk_keep(&m_sc[c * ARN_CG + gl], md),
R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl));
}
}
}
});
ms = r4d_archk_moved(ms, md);
m_pay = r4d_archk_moved(m_pay, md);
m_sc = r4d_archk_moved(m_sc, md);
// The peer's rows are now in my scratch, in the same [M, K] layout as X.
const __hip_bfloat16* P = (const __hip_bfloat16*)ms;
@@ -475,7 +484,8 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags,
long seq_ctrs, long slot_stride16,
long x, long residual, long wgain, long out_bf16, long q, long s,
int M, int K, int had, float eps, float wadd,
long stream, int nblocks, int nthreads, int drain, int acq, int wire) {
long stream, int nblocks, int nthreads, int drain, int acq, int wire,
long stage) {
if (K % 16) throw std::runtime_error("r4d ar_ln_had_quant_i8: K must be a multiple of 16");
if (M < 1) throw std::runtime_error("r4d ar_ln_had_quant_i8: M must be positive");
if (had < 2 || (had & (had - 1))) throw std::runtime_error(
@@ -509,7 +519,7 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags,
(__hip_bfloat16*)residual, (const __hip_bfloat16*)wgain, (__hip_bfloat16*)out_bf16, \
(signed char*)q, (float*)s, (int4*)peer_scratch, (const int4*)my_scratch, \
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, M, K, (int)slot_stride16, \
drain, acq, eps, wadd, rn, (unsigned)nbw)
drain, acq, eps, wadd, rn, (unsigned)nbw, stage)
#define R4D_ARN_T(H, W, R) switch (thr) { \
case 128: R4D_ARN_LAUNCH(H, 128, W, R); break; \
case 256: R4D_ARN_LAUNCH(H, 256, W, R); break; \
+22 -13
View File
@@ -64,7 +64,7 @@ template <typename T, int LANES>
__global__ void r4d_ar_oneshot_2rank_exact_kernel(
const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4,
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
int n16, int slot_stride16, int drain, int acq, unsigned int nbw) {
int n16, int slot_stride16, int drain, int acq, unsigned int nbw, long stage) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
@@ -72,6 +72,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
const int slot = (int)s_slot;
int4* ps = peer_base + (size_t)slot * slot_stride16;
const int4* ms = my_base + (size_t)slot * slot_stride16;
const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h)
const int w = (n16 + nb - 1) / nb; // 16B words per block
const int start = b * w;
@@ -121,8 +122,10 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
for (int k = start + tid; k < end; k += nt)
h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k);
});
ms = r4d_archk_moved(ms, md);
// Reduce the chunk, 4x unrolled: out = local input + peer input (staged in local scratch).
{
int k = start + tid;
@@ -149,7 +152,7 @@ __global__ void r4d_ar_hc_write_kernel(
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) {
unsigned int* gate_ctr, long stage) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
@@ -158,6 +161,7 @@ __global__ void r4d_ar_hc_write_kernel(
const int slot = (int)s_slot;
int4* ps = peer_base + (size_t)slot * slot_stride16;
const int4* ms = my_base + (size_t)slot * slot_stride16;
const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h)
const int w = (n16 + nb - 1) / nb; // 16B words per block
const int start = b * w;
@@ -189,8 +193,10 @@ __global__ void r4d_ar_hc_write_kernel(
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
for (int k = start + tid; k < end; k += nt)
h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k);
});
ms = r4d_archk_moved(ms, md);
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
const int wpr = n >> 3; // 16B words a row
@@ -237,7 +243,7 @@ __global__ void r4d_ar_gather_hc_write_kernel(
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) {
const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
__shared__ int s_i[R4D_ARG_ROWS * R4D_ARG_SLOTS];
@@ -249,6 +255,7 @@ __global__ void r4d_ar_gather_hc_write_kernel(
const int slot = (int)s_slot;
int4* ps = peer_base + (size_t)slot * slot_stride16;
const int4* ms = my_base + (size_t)slot * slot_stride16;
const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h)
const int w = (n16 + nb - 1) / nb; // 16B words per block
const int start = b * w;
@@ -304,8 +311,10 @@ __global__ void r4d_ar_gather_hc_write_kernel(
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
for (int k = start + tid; k < end; k += nt)
h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k);
});
ms = r4d_archk_moved(ms, md);
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
for (int k = start + tid; k < end; k += nt) {
@@ -411,7 +420,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 drain, long acq, long gate, long gate_ctr, long stage) {
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");
@@ -431,7 +440,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m
(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,
(long long*)gate, (unsigned int*)gate_ctr);
(long long*)gate, (unsigned int*)gate_ctr, stage);
}
int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
@@ -439,7 +448,7 @@ 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 drain, long acq, long inv, long gate, long gate_ctr, long stage) {
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;
@@ -483,13 +492,13 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
(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);
(const int*)inv, (long long*)gate, (unsigned int*)gate_ctr, stage);
} else {
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,
nullptr, (long long*)gate, (unsigned int*)gate_ctr);
nullptr, (long long*)gate, (unsigned int*)gate_ctr, stage);
}
return (int)hipGetLastError();
}
@@ -544,7 +553,7 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl
long my_flags, long seq_ctrs, long slot_stride16,
long inp, long out, long n_elem, long dtype,
long stream_i, long nblocks, long nthreads,
long drain, long acq) {
long drain, long acq, long stage) {
hipStream_t st = (hipStream_t)stream_i;
const int esize = (dtype == 2) ? 4 : 2;
const long nbytes = (long)n_elem * esize;
@@ -569,7 +578,7 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl
#define L(T, LN) r4d_ar_oneshot_2rank_exact_kernel<T, LN><<<nb, nt, 0, st>>>( \
(const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \
(int)slot_stride16, (int)drain, (int)acq, nbw)
(int)slot_stride16, (int)drain, (int)acq, nbw, stage)
if (dtype == 0) L(__hip_bfloat16, 8);
else if (dtype == 1) L(__half, 8);
else if (dtype == 2) L(float, 4);
+19 -10
View File
@@ -219,26 +219,27 @@ __device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigne
template <int CG = CHUNK_GROUPS>
__device__ __forceinline__ void wht6_rehash_chunk(unsigned int& h, int c, int n_groups, int lane,
int lig, int gw, const uint4* m_pay,
const unsigned short* m_sc) {
const unsigned short* m_sc, long md) {
using Ch = Wht6Chunk<CG>;
if constexpr (Ch::U4) {
#pragma unroll
for (int u = 0; u < Ch::NW / 4; ++u) {
const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane;
h += r4d_archk_u4(m_pay[o], 4u * (unsigned)o);
h += r4d_archk_u4(r4d_archk_keep(&m_pay[o], md), 4u * (unsigned)o);
}
} else {
const unsigned int* mp = reinterpret_cast<const unsigned int*>(m_pay);
#pragma unroll
for (int u = 0; u < Ch::NW; ++u) {
const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane;
h += r4d_archk_mix(mp[o], (unsigned)o);
h += r4d_archk_mix(r4d_archk_keep(&mp[o], md), (unsigned)o);
}
}
#pragma unroll
for (int t = 0; t < Ch::ITERS; ++t) {
const int g = c * CG + t * GPW + gw;
if (lig == 0 && g < n_groups) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g);
if (lig == 0 && g < n_groups)
h += r4d_archk_mix(r4d_archk_keep(&m_sc[g], md), R4D_ARCHK_U16 + (unsigned)g);
}
}
@@ -295,6 +296,11 @@ struct Wht6Slot {
uint4* p_pay; unsigned short* p_sc; // the peer's scratch: payload, bf16 scales
const uint4* m_pay; const unsigned short* m_sc; // this rank's scratch, which the peer filled
uint4* l_pay; float* l_sc; // this rank's own half, local only
// Onto the host mailbox's VRAM mirror once the check has passed (r4d_ar_seq.h).
__device__ __forceinline__ void moved(long md) {
m_pay = r4d_archk_moved(m_pay, md);
m_sc = r4d_archk_moved(m_sc, md);
}
};
__device__ __forceinline__ Wht6Slot wht6_slot(char* peer_scratch, const char* my_scratch,
char* loc_pack, int slot, long slot_stride_bytes,
@@ -316,15 +322,16 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel(
const T* __restrict__ in, char* peer_scratch, const char* my_scratch, char* loc_pack,
T* __restrict__ out, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
int n_groups, int n_chunks, long slot_stride_bytes, long scale_off_bytes, int drain, int acq,
unsigned int nbw) {
unsigned int nbw, long stage) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
const int lane = tid & (WAVE - 1), wid = tid / WAVE, nwarp = nt / WAVE;
const int lig = lane & (LPG - 1), gw = lane / LPG;
__shared__ unsigned int s_seq, s_slot;
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
const unsigned int s = s_seq;
const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot,
slot_stride_bytes, scale_off_bytes);
Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot,
slot_stride_bytes, scale_off_bytes);
const long md = r4d_archk_md(stage, my_scratch); // the host mailbox's VRAM mirror
const int cpb = (n_chunks + nb - 1) / nb; // block b owns chunks [c0,c1)
const int c0 = b * cpb; int c1 = c0 + cpb; if (c1 > n_chunks) c1 = n_chunks;
@@ -341,8 +348,9 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel(
wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq);
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) {
for (int c = c0 + wid; c < c1; c += nwarp)
wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc);
wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc, md);
});
w.moved(md);
const auto st = [&](long off, const float* v) {
#pragma unroll
@@ -366,7 +374,8 @@ static void r4d_ar_wht6_launch(int64_t peer_scratch, int64_t my_scratch, int64_t
int64_t my_flags, int64_t seq_ctrs, int64_t loc_pack,
int64_t slot_stride_bytes, int64_t scale_off_bytes, int64_t inp,
int64_t out, int64_t n_elem, int64_t dtype, int64_t stream_i,
int64_t nblocks, int64_t nthreads, int64_t drain, int64_t acq) {
int64_t nblocks, int64_t nthreads, int64_t drain, int64_t acq,
int64_t stage = 0) {
hipStream_t st = (hipStream_t)stream_i;
if (dtype != 0 && dtype != 1) throw std::runtime_error("pack ar: only bf16/fp16 payloads");
if (n_elem % GROUP != 0) throw std::runtime_error("pack ar: n_elem not a multiple of GROUP");
@@ -378,7 +387,7 @@ static void r4d_ar_wht6_launch(int64_t peer_scratch, int64_t my_scratch, int64_t
(const T*)inp, (char*)peer_scratch, (const char*)my_scratch, (char*)loc_pack, (T*)out, \
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n_groups, n_chunks, \
(long)slot_stride_bytes, (long)scale_off_bytes, (int)drain, (int)acq, \
(unsigned)R4D_AR_MAX_BLOCKS)
(unsigned)R4D_AR_MAX_BLOCKS, (long)stage)
if (dtype == 0) LF(__hip_bfloat16);
else LF(__half);
#undef LF
+11 -8
View File
@@ -11,10 +11,11 @@
void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long loc_pack, long slot_stride_bytes,
long scale_off_bytes, long inp, long out, long n_elem, long dtype,
long stream, long nblocks, long nthreads, long drain, long acq) {
long stream, long nblocks, long nthreads, long drain, long acq,
long stage) {
r4d_ar_wht6_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs, loc_pack,
slot_stride_bytes, scale_off_bytes, inp, out, n_elem, dtype, stream, nblocks,
nthreads, drain, acq);
nthreads, drain, acq, stage);
}
// Block cap of both all-reduce kernels (the flag array is sized from it).
@@ -74,7 +75,7 @@ __global__ void r4d_ar_hc_write_wht6_kernel(
const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n, int hc,
long irow, long hrow, int n_groups, int n_chunks, long slot_stride_bytes,
long scale_off_bytes, int drain, int acq, unsigned int nbw, R4dArGather G, int rows_max,
long long* gate, unsigned int* gate_ctr) {
long long* gate, unsigned int* gate_ctr, long stage) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
const int lane = tid & (WAVE - 1), wid = tid / WAVE, nwarp = nt / WAVE;
const int lig = lane & (LPG - 1), gw = lane / LPG;
@@ -83,8 +84,9 @@ __global__ void r4d_ar_hc_write_wht6_kernel(
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
const unsigned int s = s_seq;
const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot,
slot_stride_bytes, scale_off_bytes);
Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot,
slot_stride_bytes, scale_off_bytes);
const long md = r4d_archk_md(stage, my_scratch); // the host mailbox's VRAM mirror
const int cpb = (n_chunks + nb - 1) / nb; // block b owns chunks [c0,c1)
const int c0 = b * cpb; int c1 = c0 + cpb; if (c1 > n_chunks) c1 = n_chunks;
@@ -147,8 +149,9 @@ __global__ void r4d_ar_hc_write_wht6_kernel(
wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq);
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) {
for (int c = c0 + wid; c < c1; c += nwarp)
wht6_rehash_chunk<CG>(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc);
wht6_rehash_chunk<CG>(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc, md);
});
w.moved(md);
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
for (int c = c0 + wid; c < c1; c += nwarp)
@@ -161,7 +164,7 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo
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 gate, long gate_ctr) {
long gate, long gate_ctr, long stage) {
hipStream_t st = (hipStream_t)stream_i;
if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1;
if ((M * n) % GROUP) return -1;
@@ -207,7 +210,7 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, \
(unsigned short*)h, (int)n, (int)hc, irow, hrow, n_groups, n_chunks, slot_stride_bytes, \
scale_off_bytes, (int)drain, (int)acq, (unsigned)R4D_AR_MAX_BLOCKS, G, rows_max, \
(long long*)gate, (unsigned int*)gate_ctr)
(long long*)gate, (unsigned int*)gate_ctr, stage)
if (gather) LF(true, kWht6FusedCG);
else LF(false, kWht6FusedCG);
#undef LF
+24
View File
@@ -197,3 +197,27 @@ __device__ __forceinline__ void r4d_archk_wait(unsigned int* my_flags, unsigned
__builtin_amdgcn_s_sleep(2);
}
}
// ---- The host mailbox's one read. A host twin's slots are pinned host memory (r4d_ar_entry.hip),
// which the card reads past every cache over its own link, so reading the slot for the check and
// again for the reduce crosses the link twice: at --p2p off a prefill all-reduce's reads doubled
// (#323). Such an instance also has a mirror of its slots in this rank's VRAM, `md` bytes from
// them (`stage` - my_scratch; 0 over P2P, where the slots are VRAM already). The re-hash reads each
// word through r4d_archk_keep, which also stores it into the mirror, and once the check passes the
// kernel moves its slot pointers onto the mirror (r4d_archk_moved) for the reduce. Only this block
// writes and reads its words of the mirror, and the check's barriers order the two; a failed try's
// copy is overwritten by the next.
template <typename V>
__device__ __forceinline__ V r4d_archk_keep(const V* p, long md) {
const V v = *p;
if (md) *reinterpret_cast<V*>(reinterpret_cast<uintptr_t>(p) + md) = v;
return v;
}
template <typename V>
__device__ __forceinline__ const V* r4d_archk_moved(const V* p, long md) {
return reinterpret_cast<const V*>(reinterpret_cast<uintptr_t>(p) + md);
}
// The offset of an instance's mirror from its slots, from the launcher's `stage` (0: none).
__device__ __forceinline__ long r4d_archk_md(long stage, const void* my_scratch) {
return stage ? stage - (long)reinterpret_cast<uintptr_t>(my_scratch) : 0;
}
+86 -5
View File
@@ -64,6 +64,10 @@
// Neither changes the arithmetic.
#define O_QLD 134217728
#define O_KVREP 268435456
// TREE: a tree verify (attn_paged_qrow_tree; R4DArgs::spec_parent). A row whose entry is not -2
// sees, inside its sequence's query block, only itself and its ancestors, and its window is
// measured from the block's first position plus its depth. Compiled in only where a row asks.
#define O_TREE 536870912
__host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; }
__host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) {
int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits;
@@ -112,6 +116,7 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
static_assert(!V4 || (OPT & O_F16), "fp8_v4 widens to f16");
constexpr int QLD = (OPT & O_QLD) ? 1 : 0;
constexpr int KVREP = (OPT & O_KVREP) ? 1 : 0;
constexpr int TREE = (OPT & O_TREE) ? 1 : 0;
typedef DT16<F16> D;
typedef typename D::frag frag16;
@@ -177,6 +182,16 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
if (t_lo >= ntl) return;
const int t_hi = min(t_lo + tps, ntl);
// TREE: the block's parents staged once, so each row's walk below reads LDS rather than a
// chain of dependent global loads. Every early return above is uniform across the block.
__shared__ int s_tpar[TREE ? 64 : 1];
if constexpr (TREE) {
if (a.spec_parent) {
for (int r = tid; r < qlen && r < 64; r += NTHR) s_tpar[r] = a.spec_parent[qoff + r];
__syncthreads();
}
}
const int row = warp * 16 + c;
const int qi = row / GQA, hi = row - qi * GQA;
const bool live = (qi < qlen);
@@ -214,8 +229,28 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
const int klimit = cz ? pos
: ((WIN && a.window > 0) ? min(ctx - 1, pos + a.window - 1)
: ctx - 1);
const int wlo = (WIN && a.window > 0) ? (pos - a.window + 1 > 0
? pos - a.window + 1 : 0) : 0;
// A tree verify's row (TREE): a bit per row of the block for itself and each ancestor, and
// its depth, from which its window is measured. Parents precede children, so the walk ends.
const int tbase = ctx - qlen;
uint64_t tmask = 0;
int tdep = 0;
bool trow = false;
if (TREE && a.spec_parent && qrow < 64) {
int pj = s_tpar[qrow];
if (pj != -2) {
trow = true;
tmask = 1ull << qrow;
for (int at = qrow; pj >= 0 && pj < at; ) {
tmask |= 1ull << pj;
++tdep;
at = pj;
pj = s_tpar[pj];
}
}
}
const int wpos = (TREE && trow) ? tbase + tdep : pos;
const int wlo = (WIN && a.window > 0) ? (wpos - a.window + 1 > 0
? wpos - a.window + 1 : 0) : 0;
float m_ref = -3.0e38f;
float off = PSHIFT + 3.0e38f;
float l_i = 0.0f;
@@ -482,10 +517,13 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul;
const int kbase = k0 + mt * 16 + 8 * h;
if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo))) {
if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo)) ||
(TREE && wave_any(trow && kbase + 7 >= tbase))) {
#pragma unroll
for (int e = 0; e < 8; ++e)
sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo))
sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo) &&
(!TREE || !trow || kbase + e < tbase ||
((tmask >> (kbase + e - tbase)) & 1ull)))
? sc[e] : -INFINITY;
}
float smax = sc[0];
@@ -1004,12 +1042,55 @@ void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile,
// target were worse than 2x). At three waves (an 8-row verify) more workgroups only add
// contention (+9 %). The split count already moves with the batch, so the merge sees no new
// partition.
//
// Except that a three-wave workgroup reads the step's depth (r4d_decode_depth): past
// kVerifyMinFrom it keeps at least kVerifySplitsMin segments, what 128 gives one sequence of two
// KV heads, and past kVerifyDeepFrom it targets 512 workgroups (at most kVerifyDeepMax segments).
// At depth the 128 target starves an 8-row verify, each segment walking 2-18k tokens. Qwen3.8-27B
// at TP2 on the R9700, k6_v4, speculation 7, ms a decode step, forced segment counts
// (RADIANCE_TUNE=attn_paged:splits), the 128 target (16-21 at x3-x4, 10 at x6) -> 64: x3 45k
// 27.83 -> 27.56, 90k 32.61 -> 31.79, 180k 42.31 -> 40.47; x4 45k 29.96 -> 29.48, 90k 36.03 ->
// 34.89, 180k 48.74 -> 46.26; x6 45k 37.39 -> 36.11, 90k 47.74 -> 44.70. Deeper still two
// sequences want 128 (90k 26.73 -> 26.36, 180k 33.00 -> 32.01) and one 256 (180k 25.25 -> 24.93,
// 90k level), while four stay at 64 (128: 180k 45.94 vs 46.32, 90k 35.06 vs 35.00) and six lose at
// 128 (90k 44.91 vs 44.70): about 512 workgroups. Shallow the minimum costs up to half a percent
// (1k: x2 20.98 -> 21.01, x4 24.01 -> 24.15, x6 28.71 -> 28.86; x4 16k 25.80 -> 25.85), hence
// the floor. The kernel benchmark above (+9 % at x2) did not carry to the server. 64 is also the
// vectorised merge's limit and the count one sequence already splits at.
// Served against the 128 target, ms a decode step: x1 90k 22.07 -> 22.03, 180k 25.35 -> 24.88;
// x2 90k 26.83 -> 26.36, 180k 33.18 -> 31.99; x3 180k 42.41 -> 40.33; x4 90k 36.20 -> 34.96. A
// plain decode, the 4-row short block (16k x16 38.94 -> 38.90) and a verify up to 16k (1k x1-x8)
// keep their segment count. Greedy output is unchanged.
static constexpr int kVerifySplitsMin = 64;
static constexpr int kVerifyMinFrom = 16384;
static constexpr int kVerifyDeepFrom = 65536;
static constexpr int kVerifyDeepMax = 256;
// The deepest context the step can reach. At issue the block table is the step's: its width moves
// with the batch's longest sequence, rounded up (core/sched/batch.cpp, bound_bucket), while
// `max_ctx` is the declared bound, the model's context. Declare passes no table (max_blocks 0), so
// the scratch is sized at the declared bound, the deepest the law can be asked for; the law grows
// with depth, so an issue never needs more.
static inline int r4d_decode_depth(const R4DArgs* a) {
if (a->max_blocks > 0 && a->block_size > 0) {
const long long t = (long long)a->max_blocks * a->block_size;
if (t < a->max_ctx) return (int)t;
}
return a->max_ctx;
}
static inline int r4d_decode_splits(const R4DArgs* a, int tile) {
if (a->splits > 0) return a->splits;
const int tiles = (a->max_ctx + tile - 1) / tile;
const int units = std::max(1, a->kv_heads * a->num_seqs);
const int gqa = a->kv_heads > 0 ? std::max(1, a->q_heads / a->kv_heads) : 1;
int s = (a->q_len * gqa <= 32 ? 256 : 128) / units;
int s = 256 / units;
if (a->q_len * gqa > 32) {
const int depth = r4d_decode_depth(a);
s = (depth > kVerifyDeepFrom ? 512 : 128) / units;
if (s > kVerifyDeepMax) s = kVerifyDeepMax;
if (depth > kVerifyMinFrom && s < kVerifySplitsMin) s = kVerifySplitsMin;
}
const int cap = tiles / 2;
if (s > cap) s = cap;
if (s > tiles) s = tiles;
+13 -8
View File
@@ -280,8 +280,11 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad
/* Split-KV partial buffer size at declare time, from the band's upper bound. Declare passes
* parameters and no tensors, so parameters come first and tensors are the fallback (see the
* h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs, because
* S * floor(128 / (kv_heads * S)) is not monotone in S. */
* h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs and every
* query length up to the band's: S * floor(128 / (kv_heads * S)) is not monotone in S, and the
* split law's targets (r4d_decode_splits: 256 workgroups at q_len * gqa <= 32; above, 128 to 16384
* tokens deep and more past it) can give a shorter query more splits: at gqa 8 a 4-row step needs
* 1.6x the partials of the band bound 5. */
/* `row` is a token's bytes in a (block, head) page, 0 for the 16-bit and E4M3 caches' 2 * head_dim
* (fill_paged_row). */
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = 0) {
@@ -298,17 +301,19 @@ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row =
const long long gqa = r4d_geti_or(a, "gqa", 1);
r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head);
r.num_seqs = (int)max_seqs;
r.q_len = (int)r4d_geti_or(a, "q_len", 1);
const long long q_hi = std::max(1LL, r4d_geti_or(a, "q_len", 1));
r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0);
r.block_size = (int)r4d_geti_or(a, "block_size", 16);
r.splits = sp;
if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL);
int64_t worst = 0;
for (long long n = 1; n <= max_seqs; ++n) {
r.num_seqs = (int)n;
const int64_t need = GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r);
if (need > worst) worst = need;
}
for (long long q = 1; q <= q_hi; ++q)
for (long long n = 1; n <= max_seqs; ++n) {
r.q_len = (int)q;
r.num_seqs = (int)n;
const int64_t need = GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r);
if (need > worst) worst = need;
}
return worst;
}
const int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim);
+7
View File
@@ -45,6 +45,13 @@ extern "C" int r4d_attn_decode_h256_gqa2_qld_fp8kv(const R4DArgs* a, hipStream_t
extern "C" int r4d_attn_decode_h256_gqa2_qld_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD, 1>(a, s);
}
// ...and a tree verify's mask (O_TREE, attn_paged_qrow_tree), again its own instances.
extern "C" int r4d_attn_decode_h256_gqa2_qld_tree_fp8kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_TREE, 0>(a, s);
}
extern "C" int r4d_attn_decode_h256_gqa2_qld_tree_bf16kv(const R4DArgs* a, hipStream_t s) {
return r4d_decode_launch_win<B_HEAD_DIM, B_GQA, B_OPT | O_QLD | O_TREE, 1>(a, s);
}
// ---- prefill ---------------------------------------------------------------------------------
// The h256/gqa6 prefill option set but at K prefetch 4 (P_OPT there is 3954187); O_KWIDE is valid
+40 -9
View File
@@ -301,9 +301,12 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) {
* row with "invalid argument". q_len is the band's upper bound, since the region is sized once
* for the worst step.
*
* The size is the maximum over every sequence count up to max_seqs: S * splits(S) is not monotone
* in S (at kv_heads 2 the h256 law gives 60 at twelve sequences and 63 at nine, and the h128 law's
* step-up doubles splits at one count only). The laws are closed forms, so the sweep is cheap. */
* The size is the maximum over every sequence count up to max_seqs and every query length up to
* the band's: S * splits(S) is not monotone in S (at kv_heads 2 the h256 law gives 60 at twelve
* sequences and 63 at nine, and the h128 law's step-up doubles splits at one count only), and the
* h256 law's targets (r4d_decode_splits: 256 workgroups at q_len * gqa <= 32; above, 128 to 16384
* tokens deep and more past it) can give a shorter query more splits (at gqa 6 and 16384 tokens, 5
* rows a sequence need 1.67x the band bound 6's). The laws are closed forms, so the sweep is cheap. */
// Per-geometry byte counts over the shared partial layout, so one sweep serves all.
// which: 0 = h256/gqa6, 1 = h128/gqa4, 2 = h256/gqa2 (Gemma 4 windowed).
static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) {
@@ -332,7 +335,7 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo
r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head) * rep;
r.kv_rep = rep;
r.num_seqs = (int)max_seqs;
r.q_len = (int)r4d_geti_or(a, "q_len", 1);
const long long q_hi = std::max(1LL, r4d_geti_or(a, "q_len", 1));
r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0);
r.block_size = (int)r4d_geti_or(a, "block_size", 16);
r.splits = sp;
@@ -340,11 +343,13 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo
* for a launch that later picks more, so refuse. */
if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL);
int64_t worst = 0;
for (long long n = 1; n <= max_seqs; ++n) {
r.num_seqs = (int)n;
const int64_t need = decode_scratch_bytes_of(&r, which);
if (need > worst) worst = need;
}
for (long long q = 1; q <= q_hi; ++q)
for (long long n = 1; n <= max_seqs; ++n) {
r.q_len = (int)q;
r.num_seqs = (int)n;
const int64_t need = decode_scratch_bytes_of(&r, which);
if (need > worst) worst = need;
}
return worst;
}
@@ -517,6 +522,32 @@ extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_bf16(const RadArgs* a, RadStre
return r4d_attn_decode_h256_gqa2_qld_bf16kv(&r, (hipStream_t)s);
}
/* ...under attn_paged_qrow_tree: the same, with the tree verify's mask from `spec_parent` (operand
* 8, one int32 a query row; docs/OPS.md). Causal only, as the op is. */
static int tree_operand(const RadArgs* a, R4DArgs* r) {
const RadTensor* tp = a->n_t > 8 ? r4d_opt(a, 8) : nullptr;
if (!tp || !tp->data) return R4D_NO(RAD_E_INVAL);
if (tp->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE);
if (r4d_numel(tp) < r4d_q_total(*r)) return R4D_NO(RAD_E_SHAPE);
if (r->causal != 1 || r->causal_seq) return R4D_NO(RAD_E_UNSUPPORTED);
r->spec_parent = (const int*)tp->data;
return RAD_OK;
}
extern "C" int r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2, 0, 1, true);
if (rc == RAD_OK) rc = tree_operand(a, &r);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_qld_tree_fp8kv(&r, (hipStream_t)s);
}
extern "C" int r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) {
R4DArgs r;
int rc = decode_common(a, &r, 256, 2, 0, 1, true);
if (rc == RAD_OK) rc = tree_operand(a, &r);
if (rc != RAD_OK) return rc;
return r4d_attn_decode_h256_gqa2_qld_tree_bf16kv(&r, (hipStream_t)s);
}
/* Head_dim 128 at 8 queries per kv head, any window, causal or not, q_len up to 16, under
* attn_paged_qrow: the gqa-4 kernel with each kv head mapped onto two query groups
* (R4DArgs::kv_rep = 2), the 31B's DFlash drafter's attention over a cache that holds each kv head
+81 -12
View File
@@ -194,6 +194,9 @@ struct AttnArgs {
int* tinfo; /* [tile] = (first row, positions) */
float qscale; /* softmax scale * log2(e) */
int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split;
/* A tree verify (attn_paged_qrow_tree): RadBatch::spec_parent, one a query row; read only by
* the TREE instances. */
const int* tpar;
};
/* Tile `tile` of a ragged batch: its sequence and which BQ-position slice of that sequence's query
@@ -240,7 +243,7 @@ __device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int*
/* ------------------------------------------------------------------ the attention kernel */
/* The body; attn_kernel and its chained form r4dchain_attn_window (r4d_chain.h) wrap it below,
* since its blocks return early. */
template <int HD, int GQA, bool KV8>
template <int HD, int GQA, bool KV8, bool TREE = false>
__device__ __forceinline__ void attn_body(AttnArgs A) {
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, RW = R / kWaves, BQ = R / GQA;
constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */
@@ -284,6 +287,17 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
}
if (npos <= 0) return; /* uniform across the block */
/* TREE: the sequence's first rows' parents staged once (a tree block is at most 64 rows), so
* each row's walk below reads LDS rather than a chain of dependent global loads. */
__shared__ int s_tpar[TREE ? 64 : 1];
if constexpr (TREE) {
if (A.tpar) {
const int nst = imin(qlen, 64);
for (int r = tid; r < nst; r += kThreads) s_tpar[r] = A.tpar[tokb + r];
__syncthreads();
}
}
const int tok0 = tokb + pfirst;
const int qbase = ctx - qlen + pfirst; /* absolute position of the tile's first query */
const int plast = qbase + npos - 1;
@@ -293,7 +307,10 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
int hi = causal ? plast + 1 : ctx;
if (!causal && window > 0) hi = imin(hi, plast + window);
hi = imin(imin(hi, ctx), A.max_blocks * 16);
const int lo = window > 0 ? imax(0, qbase - window + 1) : 0;
/* A tree row's window is measured from the block's first position plus its depth, which can
* be below its own position, so a tree launch starts every tile at the block's first. */
const int tbase = ctx - qlen;
const int lo = window > 0 ? imax(0, ((TREE && A.tpar) ? tbase : qbase) - window + 1) : 0;
const int lo_a = lo & ~(BK - 1);
const int nkt = hi > lo_a ? (hi - lo_a + BK - 1) / BK : 0;
const int per = (nkt + A.n_split - 1) / A.n_split;
@@ -306,6 +323,11 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
float qf[RW][NC][4], o[RW][NC][4], m[RW], l[RW];
int pos[RW];
bool val[RW];
/* TREE: each row's ancestors inside the block (a bit per row of the block, itself included),
* whether it is a tree row at all, and the position its window is measured from. */
uint64_t tm[RW];
int wq[RW];
bool tr[RW];
#pragma unroll
for (int i = 0; i < RW; ++i) {
const int r = wave * RW + i, p = r / GQA, g = r - p * GQA;
@@ -313,6 +335,28 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
pos[i] = qbase + p;
m[i] = -__builtin_inff();
l[i] = 0.0f;
tm[i] = 0;
wq[i] = pos[i];
tr[i] = false;
if constexpr (TREE) {
const int rel = pfirst + p; /* the row within its sequence's rows */
if (A.tpar && val[i] && rel < 64) {
int pj = s_tpar[rel];
if (pj != -2) {
uint64_t mk = 1ull << rel;
int dep = 0;
for (int at = rel; pj >= 0 && pj < at; ) {
mk |= 1ull << pj;
++dep;
at = pj;
pj = s_tpar[pj];
}
tr[i] = true;
tm[i] = mk;
wq[i] = tbase + dep;
}
}
}
const uint16_t* qp = A.q + (long long)(tok0 + p) * A.q_rs + (long long)(kh * GQA + g) * A.q_hs;
const float qs = A.qscale * kds; /* k_descale folds into the query */
#pragma unroll
@@ -391,7 +435,10 @@ __device__ __forceinline__ void attn_body(AttnArgs A) {
}
const int pq = pos[i];
bool vis = kok && (causal ? kk <= pq : true);
if (window > 0) vis = vis && (pq - kk < window) && (causal || kk - pq < window);
if constexpr (TREE)
if (tr[i] && vis && kk >= tbase) vis = ((tm[i] >> (kk - tbase)) & 1ull) != 0;
const int wpq = TREE ? wq[i] : pq;
if (window > 0) vis = vis && (wpq - kk < window) && (causal || kk - wpq < window);
const float sv = vis ? sc[0] : -__builtin_inff();
const float mn = __builtin_fmaxf(m[i], wave_max(sv));
if (mn == -__builtin_inff()) return; /* nothing visible yet: uniform */
@@ -974,12 +1021,14 @@ static constexpr int64_t scratch_need() {
/* The plain kernels and their chained forms (r4dchain*, RadKernelChainFn): the chained ones wait
* for the kernels before them on the queue in their prologue and count themselves in at the end. */
template <int HD, int GQA, bool KV8>
__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { attn_body<HD, GQA, KV8>(A); }
template <int HD, int GQA, bool KV8>
template <int HD, int GQA, bool KV8, bool TREE = false>
__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) {
attn_body<HD, GQA, KV8, TREE>(A);
}
template <int HD, int GQA, bool KV8, bool TREE = false>
__global__ __launch_bounds__(kThreads) void r4dchain_attn_window(AttnArgs A) {
r4d_chain_wait();
attn_body<HD, GQA, KV8>(A);
attn_body<HD, GQA, KV8, TREE>(A);
r4d_chain_done();
}
template <int HD, int GQA>
@@ -991,10 +1040,15 @@ __global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) {
r4d_chain_done();
}
template <int HD, int GQA, bool KV8>
template <int HD, int GQA, bool KV8, bool TREE = false>
static int launch_attn(const RadArgs* a, RadStream stream) {
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2;
if (!a || a->n_t < 8) return RAD_E_INVAL;
if (!a || a->n_t < (TREE ? 9 : 8)) return RAD_E_INVAL;
/* attn_paged_qrow_tree's ninth operand: one int32 a query row (docs/OPS.md). Causal only. */
const RadTensor* tp = TREE ? rad_arg_in(a, 8) : nullptr;
if (TREE && (!tp || !tp->data)) return RAD_E_INVAL;
if (TREE && tp->dtype != RAD_I32) return RAD_E_DTYPE;
if (TREE && rad_args_geti_or(a, "causal", 1) != 1) return RAD_E_UNSUPPORTED;
const RadTensor* q = rad_arg_in(a, 0);
const RadTensor* kv = rad_arg_in(a, 1);
const RadTensor* bt = rad_arg_in(a, 2);
@@ -1028,6 +1082,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
if (!head_view(q, qh, HD, &rows, &q_rs, &q_hs) || !head_view(o, qh, HD, &orows, &o_rs, &o_hs))
return RAD_E_SHAPE;
if (orows < rows) return RAD_E_SHAPE;
if (TREE && rad_tensor_numel(tp) < rows) return RAD_E_SHAPE;
const int64_t n_seq = rad_tensor_numel(su);
if (rows == 0) return RAD_OK;
if (n_seq <= 0 || n_seq > (1 << 24)) return RAD_E_SHAPE;
@@ -1081,7 +1136,8 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
qmax_w = rad_args_geti_or(a, "q_len", rows);
if (qmax_w <= 0 || qmax_w > rows) qmax_w = rows;
}
const bool shaped = qmax_w >= kWmmaMinQ && rows >= n_seq * (kWmmaMinQ / 2);
/* Never a tree: its verify blocks are decode-sized, and only the scalar kernel reads one. */
const bool shaped = !TREE && qmax_w >= kWmmaMinQ && rows >= n_seq * (kWmmaMinQ / 2);
const bool aligned = rad_ptr_aligned(q->data, 16) && rad_ptr_aligned(o->data, 16) &&
(q_rs | q_hs | o_rs | o_hs) % 8 == 0;
if (shaped && aligned) {
@@ -1159,16 +1215,17 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
A.causal = (int)causal;
A.window = (int)window;
A.n_split = (int)ns;
A.tpar = TREE ? (const int*)tp->data : nullptr;
hipStream_t s = (hipStream_t)stream;
/* The chained forms where the row resolved with `chain` (launches chain), at decode heights
* only: the 31B's full layers at a verify. */
const bool chain = rad_args_geti_or(a, "chain", 0) != 0 && rows <= 64;
if (chain)
R4D_KLAUNCH(R4D_KNAME(r4dchain_attn_window<HD, GQA, KV8>),
R4D_KLAUNCH(R4D_KNAME(r4dchain_attn_window<HD, GQA, KV8, TREE>),
dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A);
else
R4D_KLAUNCH(R4D_KNAME(attn_kernel<HD, GQA, KV8>),
R4D_KLAUNCH(R4D_KNAME(attn_kernel<HD, GQA, KV8, TREE>),
dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A);
if (ns > 1) {
if (chain)
@@ -1198,6 +1255,18 @@ R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8)
R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8)
#undef R4D_WIN_DEF
/* attn_paged_qrow_tree: the scalar kernel with a tree verify's mask (TREE). */
#define R4D_WIN_TREE_DEF(HD, G) \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, false, true>(a, s); \
} \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true, true>(a, s); \
}
R4D_WIN_TREE_DEF(256, 1) R4D_WIN_TREE_DEF(256, 2) R4D_WIN_TREE_DEF(256, 4) R4D_WIN_TREE_DEF(256, 8)
R4D_WIN_TREE_DEF(512, 1) R4D_WIN_TREE_DEF(512, 2) R4D_WIN_TREE_DEF(512, 4) R4D_WIN_TREE_DEF(512, 8)
#undef R4D_WIN_TREE_DEF
/* Called at declare with no tensors. Partials are capped at kPartBudget (tile, head, split)
* triples for any batch, so the size is a constant. */
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*) { return r4d_win::scratch_need<128>(); }
+259
View File
@@ -0,0 +1,259 @@
// DFlash2's candidate lattice grown best-first into a tree (rad_drafter_tree), one workgroup per
// sequence. docs/OPS.md, `dflash_tree`, is the contract; libref's ref_dflash_tree the reference.
//
// The selector (r4d_dflash_select_bf16.hip) walks one path: at each position the candidate with the
// best edge score after the previous pick. A tree keeps more than one way forward where the walk is
// unsure. Node 0 is the anchor. Expanding a node at lattice position l with token t scores every
// candidate c at l + 1 exactly as the walk scores it after t,
//
// score[c] = unary[l+1, c] + sum_r pred[t][r] * hp[l+1][r] * succ[cand[l+1, c]][r]
//
// and pushes each valid candidate as a child with log probability parent + log_softmax(score/temp)
// over the valid candidates. Each round takes the untaken child with the largest log probability
// (ties to the one pushed first), until `nodes` are taken; the taken nodes, in order, are the
// proposal, each with its parent's node index. A parent is always taken before its child.
//
// The same latency-kernel shape as the walk: `nodes` expansions of K dot products of R each, and a
// reduction over a frontier of at most nodes * K entries per round, all in LDS.
#include <hip/hip_runtime.h>
#include "r4d_gdn_args.h"
#include "r4d_dflash_conv_body.h" // r4d_bf2f, r4d_u16
#include "r4d_common.h" // r4d_wave_sum
#include "r4d_chain.h"
#define DTR_THREADS 256
#define DTR_WAVE 32
#define DTR_WAVES (DTR_THREADS / DTR_WAVE)
#define DTR_MAX_K 32 // the entry point rejects more
#define DTR_MAX_R 512
#define DTR_MAX_N 63 // nodes and steps: the node table and the frontier below
#define DTR_FRONT (DTR_MAX_N * DTR_MAX_K)
// cand [rows, cand_ld] i32 row = s * steps + l
// unary [rows, cand_ld] f32
// hp [rows, hp_ld] bf16 (null: ones, the bigram form)
// anchor [M * anchor_stride] i32
// pred, succ [vocab, R] bf16
// tok, par [M, out_ld] i32 the taken nodes' tokens and parents, nodes a row
__device__ __forceinline__ void r4d_dflash_tree_body(
const int* __restrict__ cand, const float* __restrict__ unary,
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ,
int* __restrict__ tok_out, int* __restrict__ par_out, int steps, int K, int R, int V, int N,
float inv_temp, int cand_ld, int hp_ld, int out_ld, int anchor_stride)
{
const int s = blockIdx.x;
const int tid = threadIdx.x;
const int lane = tid & (DTR_WAVE - 1);
const int wave = tid / DTR_WAVE;
__shared__ float sa[DTR_MAX_R];
__shared__ float ssc[DTR_MAX_K];
// the frontier: every child pushed so far, in push order; a taken one's lp becomes -inf
__shared__ float f_lp[DTR_FRONT];
__shared__ int f_tok[DTR_FRONT];
__shared__ short f_par[DTR_FRONT];
__shared__ short f_l[DTR_FRONT];
__shared__ int n_front;
// the taken nodes, node 0 the anchor
__shared__ int n_tok[DTR_MAX_N + 1];
__shared__ int n_l[DTR_MAX_N + 1];
__shared__ float n_lp[DTR_MAX_N + 1];
// the round's reduction
__shared__ float r_lp[DTR_WAVES];
__shared__ int r_ix[DTR_WAVES];
__shared__ int take;
constexpr int CPW = (DTR_MAX_K + DTR_WAVES - 1) / DTR_WAVES;
if (tid == 0) {
n_tok[0] = anchor[(long)s * anchor_stride];
n_l[0] = -1;
n_lp[0] = 0.0f;
n_front = 0;
}
__syncthreads();
// Push node n's children: every valid candidate at its next position. Uniform across the block.
auto expand = [&](int n) {
const int l = n_l[n] + 1;
if (l >= steps) return;
const long row = (long)s * steps + l;
const int pid = n_tok[n];
const bool pid_ok = pid >= 0 && pid < V;
const r4d_u16* __restrict__ prow = pred + (long)(pid_ok ? pid : 0) * R;
if (!pid_ok) {
for (int r = tid; r < R; r += DTR_THREADS) sa[r] = 0.0f;
} else if (hp) {
const r4d_u16* __restrict__ hrow = hp + row * hp_ld;
for (int r = tid; r < R; r += DTR_THREADS) sa[r] = r4d_bf2f(prow[r]) * r4d_bf2f(hrow[r]);
} else {
for (int r = tid; r < R; r += DTR_THREADS) sa[r] = r4d_bf2f(prow[r]);
}
__syncthreads();
#pragma unroll
for (int i = 0; i < CPW; ++i) {
const int c = wave + i * DTR_WAVES;
if (c < K) {
const long at = row * cand_ld + c;
const int cid = cand[at];
const bool ok = cid >= 0 && cid < V;
const r4d_u16* __restrict__ srow = succ + (long)(ok ? cid : 0) * R;
float acc = 0.0f;
#pragma unroll 8
for (int r = lane; r < R; r += DTR_WAVE) acc += sa[r] * r4d_bf2f(srow[r]);
acc = r4d_wave_sum(ok ? acc : 0.0f);
if (lane == 0) ssc[c] = ok ? (acc + unary[at]) * inv_temp : -INFINITY;
}
}
__syncthreads();
// log_softmax over the valid candidates and the push, in c order, by one thread (K <= 32)
if (tid == 0) {
float mx = -INFINITY;
for (int c = 0; c < K; ++c) mx = fmaxf(mx, ssc[c]);
if (mx > -INFINITY) {
float sum = 0.0f;
for (int c = 0; c < K; ++c) if (ssc[c] > -INFINITY) sum += expf(ssc[c] - mx);
const float lse = mx + logf(sum);
int f = n_front;
for (int c = 0; c < K && f < DTR_FRONT; ++c) {
if (!(ssc[c] > -INFINITY)) continue;
f_lp[f] = n_lp[n] + (ssc[c] - lse);
f_tok[f] = cand[row * cand_ld + c];
f_par[f] = (short)n;
f_l[f] = (short)l;
++f;
}
n_front = f;
}
}
__syncthreads();
};
expand(0);
for (int j = 1; j <= N; ++j) {
// the round: the largest untaken log probability, the earliest pushed among equals
float best = -INFINITY;
int bix = -1;
const int nf = n_front;
for (int f = tid; f < nf; f += DTR_THREADS) {
const float v = f_lp[f];
if (v > best) { best = v; bix = f; } // ascending f: the first of equals stays
}
for (int d = DTR_WAVE / 2; d > 0; d >>= 1) {
const float ov = __shfl_xor(best, d);
const int oi = __shfl_xor(bix, d);
if (ov > best || (ov == best && oi >= 0 && (bix < 0 || oi < bix))) { best = ov; bix = oi; }
}
if (lane == 0) { r_lp[wave] = best; r_ix[wave] = bix; }
__syncthreads();
if (tid == 0) {
float b = -INFINITY;
int bi = -1;
for (int w = 0; w < DTR_WAVES; ++w)
if (r_lp[w] > b || (r_lp[w] == b && r_ix[w] >= 0 && (bi < 0 || r_ix[w] < bi))) {
b = r_lp[w]; bi = r_ix[w];
}
int t, p, l;
float lp;
if (bi < 0 || !(b > -INFINITY)) {
// a dry frontier: token 0 under the last node, never expanded
t = 0; p = j - 1; l = steps; lp = -INFINITY;
} else {
t = f_tok[bi]; p = f_par[bi]; l = f_l[bi]; lp = f_lp[bi];
f_lp[bi] = -INFINITY;
}
n_tok[j] = t; n_l[j] = l; n_lp[j] = lp;
tok_out[(long)s * out_ld + (j - 1)] = t;
par_out[(long)s * out_ld + (j - 1)] = p;
take = (bi >= 0 && b > -INFINITY) ? 1 : 0;
}
__syncthreads();
if (take && j < N) expand(j);
}
}
__global__ __launch_bounds__(DTR_THREADS) void r4d_dflash_tree_kernel(
const int* __restrict__ cand, const float* __restrict__ unary,
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ,
int* __restrict__ tok, int* __restrict__ par, int steps, int K, int R, int V, int N,
float inv_temp, int cand_ld, int hp_ld, int out_ld, int anchor_stride) {
r4d_dflash_tree_body(cand, unary, hp, anchor, pred, succ, tok, par, steps, K, R, V, N, inv_temp,
cand_ld, hp_ld, out_ld, anchor_stride);
}
__global__ __launch_bounds__(DTR_THREADS) void r4dchain_dflash_tree(
const int* __restrict__ cand, const float* __restrict__ unary,
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ,
int* __restrict__ tok, int* __restrict__ par, int steps, int K, int R, int V, int N,
float inv_temp, int cand_ld, int hp_ld, int out_ld, int anchor_stride) {
r4d_chain_wait();
r4d_dflash_tree_body(cand, unary, hp, anchor, pred, succ, tok, par, steps, K, R, V, N, inv_temp,
cand_ld, hp_ld, out_ld, anchor_stride);
r4d_chain_done();
}
// ============================================================== the plugin ABI entry point
enum { DT_CAND = 0, DT_UNARY, DT_HP, DT_ANCHOR, DT_PRED, DT_SUCC, DT_TOK, DT_PAR };
static long long dt_plane(const RadTensor* t, uint32_t dtype, long long width, long long rows) {
if (!t || !t->data || t->rank != 2) return -1;
if (t->dtype != dtype) return -1;
if (t->shape[1] < width || t->shape[0] < rows) return -1;
const long long pitch = r4d_row_pitch(t);
return (pitch >= width) ? pitch : -1;
}
extern "C" int r4d_rad_dflash_tree(const RadArgs* a, RadStream st) {
const RadTensor* cand = r4d_opt(a, DT_CAND);
const RadTensor* un = r4d_opt(a, DT_UNARY);
const RadTensor* hp = r4d_opt(a, DT_HP);
const RadTensor* anc = r4d_opt(a, DT_ANCHOR);
const RadTensor* pr = r4d_opt(a, DT_PRED);
const RadTensor* sc = r4d_opt(a, DT_SUCC);
const RadTensor* tok = r4d_opt(a, DT_TOK);
const RadTensor* par = r4d_opt(a, DT_PAR);
if (!cand || !un || !anc || !pr || !sc || !tok || !par) return R4D_NO(RAD_E_INVAL);
const long long steps = r4d_geti_or(a, "steps", 0);
const long long K = r4d_geti_or(a, "top_k", 0);
const long long R = r4d_geti_or(a, "rank", 0);
const long long V = r4d_geti_or(a, "n_vocab", 0);
const long long N = r4d_geti_or(a, "nodes", steps);
const double temp = rad_args_getf_or(a, "temp", 1.0);
/* M from the output plane, as dflash_select: the parameter is the band's bound. */
if (tok->rank != 2 || par->rank != 2) return R4D_NO(RAD_E_SHAPE);
const long long M = tok->shape[0];
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || V <= 0 || N <= 0) return R4D_NO(RAD_E_INVAL);
if (K > DTR_MAX_K || R < DTR_WAVE || R > DTR_MAX_R || (R % DTR_WAVE) || N > DTR_MAX_N ||
steps > DTR_MAX_N || !(temp > 0.0))
return R4D_NO(RAD_E_SHAPE);
const long long rows = M * steps;
const long long cand_ld = dt_plane(cand, RAD_I32, K, rows);
const long long un_ld = dt_plane(un, RAD_F32, K, rows);
const long long out_ld = dt_plane(tok, RAD_I32, N, M);
const long long par_ld = dt_plane(par, RAD_I32, N, M);
const bool has_hp = hp && hp->data;
const long long hp_ld = has_hp ? dt_plane(hp, RAD_BF16, R, rows) : 0;
if (cand_ld < 0 || un_ld < 0 || hp_ld < 0 || out_ld < 0 || par_ld < 0) return R4D_NO(RAD_E_SHAPE);
if (cand_ld != un_ld || out_ld != par_ld) return R4D_NO(RAD_E_STRIDE);
if (pr->dtype != RAD_BF16 || sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(pr) || !r4d_contig(sc)) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(pr) < V * R || r4d_numel(sc) < V * R) return R4D_NO(RAD_E_SHAPE);
const long long astr = r4d_geti_or(a, "anchor_stride", 1);
if (anc->dtype != RAD_I32 && anc->dtype != RAD_U32) return R4D_NO(RAD_E_DTYPE);
if (astr < 1 || !r4d_contig(anc)) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(anc) < (M - 1) * astr + 1) return R4D_NO(RAD_E_SHAPE);
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
hipLaunchKernelGGL((ch ? r4dchain_dflash_tree : r4d_dflash_tree_kernel), dim3((unsigned)M),
dim3(DTR_THREADS), 0, (hipStream_t)st,
(const int*)cand->data, (const float*)un->data,
has_hp ? (const r4d_u16*)hp->data : nullptr, (const int*)anc->data,
(const r4d_u16*)pr->data, (const r4d_u16*)sc->data,
(int*)tok->data, (int*)par->data, (int)steps, (int)K, (int)R, (int)V, (int)N,
(float)(1.0 / temp), (int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr);
return R4D_RAW((int)hipGetLastError());
}
+25 -1
View File
@@ -413,6 +413,9 @@ extern "C" int r4d_fuse_router_sigmoid_topk_scatter(const RadParam* p, int n_p,
* The gated attention's gate is a sigmoid, so nothing issues this row with silu and the shim's
* `mode` defaults to 1.
*
* `act` none is the plain product: the chain is `mul` then `quant_act_fp8`, and the kernel rounds
* the bf16 product once, exactly as mul_bf16 does. The product is TMP(0) or `out_bf16`.
*
* TMP(0) is act(gate), an [M, n] bf16 plane the fusion never writes. `out_bf16` is an operand: the
* kernel stores the product there when asked and takes the codes over those bytes.
*/
@@ -423,7 +426,28 @@ extern "C" int r4d_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t pres
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
/* The shim (r4d_fused_quant_fp8.hip) defaults this row's `mode` to 1 (sigmoid). */
if (!act_is(p, n_p, "sigmoid", "sigmoid")) return RAD_E_UNSUPPORTED;
const bool none = act_is(p, n_p, "sigmoid", "none");
if (!none && !act_is(p, n_p, "sigmoid", "sigmoid")) return RAD_E_UNSUPPORTED;
const int16_t mid = RAD_FUSE_HAS(present, 4) ? (int16_t)4 : RAD_FUSE_TMP(0);
if (none) {
switch (step) {
case 0: {
/* gate * x, rounded to bf16 once: mul_bf16's store. */
Step s(out, "mul");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype");
return s.wire({ 0, 1, mid }); /* a, b, y */
}
case 1: {
Step s(out, "quant_act_fp8");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group")
.mirror(p, n_p, "dtype");
return s.wire({ mid, 2, 3 }); /* x, q, scale */
}
default:
return RAD_E_NOTFOUND;
}
}
switch (step) {
case 0: {
+50 -28
View File
@@ -245,6 +245,9 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
// then contiguous, the gate a fixed stride apart, and the scale plane [T * n_head, head_dim / 128]
// is byte-identical to the [T, n_head * head_dim / 128] the out projection reads. Replaces three
// launches (sigmoid, multiply, quantise) per attention layer.
//
// ACT 2 is the product with no activation: the unfused pair is `mul` then the quantiser, so the
// gate is not rounded on its own and the product is rounded once, as mul_bf16 does.
template <int ACT, bool I8 = false>
__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
@@ -270,13 +273,18 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
}
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float gv = bf2f(gb[j]);
// The activation is rounded to bf16 before the multiply, unlike gated_quant_fp8:
// the unfused reference here is `sigmoid` then `mul` with a bf16 buffer between
// them (silu_mul_bf16 keeps f32). Skipping the round trip changes the output.
const uint16_t ab =
f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv)));
const uint16_t h = f2bf(bf2f(ab) * bf2f(xb[j]));
uint16_t h;
if (ACT == 2) {
h = f2bf(bf2f(gb[j]) * bf2f(xb[j]));
} else {
const float gv = bf2f(gb[j]);
// The activation is rounded to bf16 before the multiply, unlike gated_quant_fp8:
// the unfused reference here is `sigmoid` then `mul` with a bf16 buffer between
// them (silu_mul_bf16 keeps f32). Skipping the round trip changes the output.
const uint16_t ab =
f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv)));
h = f2bf(bf2f(ab) * bf2f(xb[j]));
}
if (yr) yr[c0 + j] = h;
v[j] = bf2f(h);
}
@@ -382,8 +390,8 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) {
// 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.
// 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.
// padded and a chunk's elements are found by (row, chunk in row). Without it, for a row of whole
// chunks, the flat chunk index gives the element offset.
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(
@@ -393,7 +401,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags,
unsigned int* seq_ctrs, char* loc_pack, long loc_scale_off, int M, uint32_t n, uint32_t nkb,
float eps, float wadd, uint32_t r_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld,
int slot_stride16, int drain, int acq, unsigned int nbw) {
int slot_stride16, int drain, int acq, unsigned int nbw, long stage) {
__shared__ float lds[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
const int b = (int)blockIdx.x, nb = (int)gridDim.x;
@@ -412,14 +420,15 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); /* device-resident, replay-safe */
const unsigned int sq = s_seq;
int4* const ps = peer_base + (size_t)s_slot * slot_stride16;
const int4* const ms = my_base + (size_t)s_slot * slot_stride16;
const int4* ms = my_base + (size_t)s_slot * slot_stride16;
const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h)
/* The slot is split as in the standalone compressed all-reduce: packed symbols from the base,
* bf16 group scales from half way up. Group indices are global over the [M][n] message. */
char* const p_pay = (char*)ps;
const char* const m_pay = (const char*)ms;
const char* m_pay = (const char*)ms;
unsigned short* const p_sc =
(unsigned short*)((char*)ps + (size_t)(slot_stride16 >> 1) * 16);
const unsigned short* const m_sc =
const unsigned short* m_sc =
(const unsigned short*)((const char*)ms + (size_t)(slot_stride16 >> 1) * 16);
/* This rank's own packed half, laid out like the peer slot (symbols from the base, scales from
* `loc_scale_off`) and indexed by global chunk and group, so blocks never overlap. */
@@ -538,7 +547,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
const int wpr = (int)(n >> 3);
const int4* const m4 = (const int4*)ms;
for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR)
h += r4d_archk_u4(m4[k], 4u * (unsigned)k);
h += r4d_archk_u4(r4d_archk_keep(&m4[k], md), 4u * (unsigned)k);
} else {
for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) {
const int c = c00 + ci;
@@ -546,24 +555,33 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
const unsigned int cd = (unsigned)c * (ARQ_CBYTES / 4);
#pragma unroll
for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4)
h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16),
cd + (unsigned)(w4 * ARQ_WV) + lane * 4u);
h += r4d_archk_u4(
r4d_archk_keep((const uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16), md),
cd + (unsigned)(w4 * ARQ_WV) + lane * 4u);
if constexpr (ARQ_NWORD % 4 >= 2) {
const uint2 u = *(const uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8);
const uint2 u = r4d_archk_keep(
(const uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8), md);
const unsigned int e = cd + (unsigned)((ARQ_NWORD & ~3) * ARQ_WV) + lane * 2u;
h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u);
}
if constexpr (ARQ_NWORD % 2 == 1)
h += r4d_archk_mix(*(const unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + lane * 4),
cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane);
h += r4d_archk_mix(
r4d_archk_keep((const unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV +
lane * 4), md),
cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane);
#pragma unroll
for (int t = 0; t < ARQ_ITERS; ++t) {
const int g = c * ARQ_CG + t * ARQ_GPW + gw;
if (lig == 0) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g);
if (lig == 0)
h += r4d_archk_mix(r4d_archk_keep(&m_sc[g], md),
R4D_ARCHK_U16 + (unsigned)g);
}
}
}
});
ms = r4d_archk_moved(ms, md);
m_pay = r4d_archk_moved(m_pay, md);
m_sc = r4d_archk_moved(m_sc, md);
if constexpr (WIRE == 6) {
/* Reduce: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate,
@@ -840,7 +858,7 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in
if (!g || !x || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 4) return -3;
if (mode != 0 && mode != 1) return -5;
if (mode < 0 || mode > 2) return -5;
if (!g_ld) g_ld = n;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
@@ -857,7 +875,8 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in
(uint32_t)s_ld)
#define R4D_GTQ(a) do { if (i8) R4D_GTQ_I(a, true); else R4D_GTQ_I(a, false); } while (0)
if (mode == 0) R4D_GTQ(0);
else R4D_GTQ(1);
else if (mode == 1) R4D_GTQ(1);
else R4D_GTQ(2);
#undef R4D_GTQ
#undef R4D_GTQ_I
if (emit_rc != RAD_OK) return -4;
@@ -889,7 +908,8 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long wp, bool hi8) {
long loc_pack, long loc_scale_off, long wp, bool hi8,
long stage) {
if (!x || !w || !q || !s) return -1;
if (wp && !res) return -10; // a post-norm needs the stream
if (hi8 && wp) return -11;
@@ -928,7 +948,7 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
(unsigned int*)my_flags, (unsigned int*)seq_ctrs, (char*)loc_pack, \
(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)
(uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw, stage)
#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)
@@ -962,11 +982,11 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long wp) {
long loc_pack, long loc_scale_off, long wp, long stage) {
return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs,
slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32,
r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq,
wire, loc_pack, loc_scale_off, wp, false);
wire, loc_pack, loc_scale_off, wp, false, stage);
}
// The same with had_quant_act_i8g's quantiser on the norm's pass (no post-norm).
@@ -976,11 +996,12 @@ extern "C" int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch,
int M, int n, float eps, float wadd, int w_f32,
int r_ld, int y_ld, int q_ld, int s_ld, long stream,
int nblocks, int nthreads, int drain, int acq,
int wire, long loc_pack, long loc_scale_off) {
int wire, long loc_pack, long loc_scale_off,
long stage) {
return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs,
slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32,
r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq,
wire, loc_pack, loc_scale_off, 0, true);
wire, loc_pack, loc_scale_off, 0, true, stage);
}
// ============================================================== the plugin ABI entry points
@@ -1046,6 +1067,7 @@ static int act_mode(const RadArgs* a, int dflt) {
if (!act) return (int)r4d_geti_or(a, "mode", dflt);
if (!std::strcmp(act, "silu")) return 0;
if (!std::strcmp(act, "sigmoid")) return 1;
if (!std::strcmp(act, "none")) return 2;
return -1;
}
+279 -35
View File
@@ -159,11 +159,11 @@ constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bo
if (fk == 128u)
return nt == 1u ? 16u : nt == 2u ? (full ? 16u : 12u) : nt == 3u ? 10u
: (full && mw >= 8u) ? 10u : 9u;
/* 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. */
/* The gated three-tile form pins 8 waves, not 9. At 9 waves (168 registers) its epilogue
* spills 57 registers at the full tile (48 rows) and 10 below it, 70 with the LDS-staged
* scales; the full-tile spill makes gate_up 51% slower than at 56 rows. At 8 waves (192
* registers) it spills 9 and 10. The gated form is always MW 16, four waves a SIMD a
* block, so 8 and 9 waves both hold two blocks a WGP and no occupancy is lost. */
return nt == 1u ? 12u : nt == 2u ? 10u : nt == 3u ? (gated ? 8u : 9u)
: mw == 4u ? 7u : 8u;
}
@@ -171,7 +171,7 @@ constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bo
return nt == 1u ? 16u : nt == 2u ? (full ? 10u : 12u) : nt == 3u ? (full ? 9u : 10u)
: full ? 7u : 9u;
/* 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
* registers than the 120 that 12 waves leave, and spill there. 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;
@@ -294,16 +294,15 @@ __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.
/* The fold's scales are staged through LDS one K tile ahead, beside the B tile. A fold that
* loaded its own scales after the next tile's prefetch was issued would wait for that whole
* prefetch (loads return in order), twice a tile at FK = 256. Instead each thread loads 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 stores them with the B tile at the top of
* the next pass, so a fold reads LDS. That costs two registers a thread; holding a tile's
* scales per lane (8 + 2*NT registers) spills at the decode shapes' register pins. The staged
* values are the ones a direct load reads, so results are bit-identical. A dead wave's fp8
* block scale reads as 0; 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
@@ -647,12 +646,10 @@ __device__ __forceinline__ void gemm_fp8a8_body(
const float* const w0 = (const float*)Y;
uint16_t* const cy = (uint16_t*)C;
/* 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. */
* partial plane ([nb][rows]): four rows a thread as one 16-byte load, kFinU quads in
* flight at each z. Walking the token index fastest would put consecutive threads
* `rows` floats apart, a cache line and a round trip per element. Both branches sum
* each element from 0.0f in ascending z, so they are 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
@@ -943,6 +940,185 @@ void gemm_8a8_prefill_kernel(const uint8_t* __restrict__ A, const float* __restr
}
}
// ---- the prefill tile, gated -------------------------------------------------------------------
//
// gemm_nt_q_gated at prefill row counts: the gate|up GEMM with SwiGLU and the E4M3 quantiser in the
// epilogue, so the [M, 2n] bf16 product is never written and gated_quant_fp8 never re-reads it
// (7% of a 400-token prefill step of d1-3B on gfx1200: 74 us a layer).
//
// The 8-accumulator cap (above) holds by halving the activation side: a block owns 128 output
// columns, i.e. 128 gate rows and the same 128 up rows of the weight, against 64 activation rows.
// The eight waves are kPWW over the weight and kPWA over the activation as on the prefill tile; a
// wave owns kPTW gate tiles and the kPTW up tiles of the same columns, against kGPTA activation
// tiles. Since the accumulator mapping does not depend on the weight rows, a lane holds the gate
// and the up value of the same (token, column) and the gate needs no exchange; the per-token amax
// over the block's 128 columns closes across the four weight waves through LDS.
//
// Byte-identical to gemm_8a8_prefill_kernel followed by gated_quant_fp8: the K loop, the fold
// (ws * as, one fma) and so every accumulator are the prefill tile's; the accumulator is rounded to
// bf16 as that kernel's store rounds it, and from there the arithmetic is the narrow gated
// epilogue's, which is gated_quant_fp8's.
constexpr uint32_t kGPTA = 2; // activation tiles a wave
constexpr uint32_t kGBM = kPWA * kGPTA * 16; // 64 activation rows a block
constexpr uint32_t kGTW = 2 * kPTW; // the gate tiles, then the up tiles
static_assert(kGBM * 2u <= kPWaves * kWave, "two threads stage an activation row");
__global__ __launch_bounds__(kPWaves * kWave)
void gemm_8a8_gated_prefill_kernel(const uint8_t* __restrict__ A, const float* __restrict__ Sa,
const uint8_t* __restrict__ W, const uint16_t* __restrict__ Sw,
uint8_t* __restrict__ Q, float* __restrict__ Sc,
uint16_t* __restrict__ Yb, uint32_t M, uint32_t K,
uint32_t nout, uint32_t a_ld, uint32_t sa_ld, uint32_t sw_ld,
uint32_t q_ld, uint32_t s_ld, uint32_t y_ld) {
constexpr uint32_t P = lds_pitch<kPFK>();
__shared__ __attribute__((aligned(16))) uint8_t s_a[2][kGBM * P];
__shared__ float s_as[2][kGBM];
__shared__ float s_amx[kPWW][kGBM];
const uint32_t tid = threadIdx.x, lane = tid % kWave;
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid / kWave);
const uint32_t ww = wave % kPWW, wa = wave / kPWW;
// The prefill tile's raster groups over activation bands.
uint32_t bm = blockIdx.x, bn = blockIdx.y;
if (gridDim.x > kGroupM) {
const uint32_t per = kGroupM * gridDim.y;
const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x;
const uint32_t first = (lin / per) * kGroupM, r = lin % per;
const uint32_t gm = min(gridDim.x - first, kGroupM);
bm = first + r % gm;
bn = r / gm;
}
const uint32_t m0 = bm * kGBM, c0 = bn * kBlock; // output columns [c0, c0 + 128)
const uint32_t ksuper = K / kSuperK, nkb = K / kBlock;
// Staging: two threads a row over the block's 64 rows (the first 128 threads), rows past M
// re-reading row M-1, every load issued as on the prefill tile.
const bool stager = tid < kGBM * 2u;
const uint32_t sr = (tid / 2u) % kGBM, sc = (tid % 2u) * 32u;
const uint8_t* const asrc = A + (size_t)min(m0 + sr, M - 1u) * a_ld + sc;
const float* const ssrc = Sa + (size_t)min(m0 + tid % kGBM, M - 1u) * sa_ld;
// Weight tiles: the gate rows [c0, c0+128) and the up rows [nout + c0, ...), kPTW each a wave.
const uint32_t wtg = c0 / 16u + ww * kPTW, wtu = (nout + c0) / 16u + ww * kPTW;
const uint8_t* const wsg = W + (size_t)wtg * ksuper * kTileBytes + lane * kLaneBytes;
const uint8_t* const wsu = W + (size_t)wtu * ksuper * kTileBytes + lane * kLaneBytes;
auto wsrc = [&](uint32_t i) {
return i < kPTW ? wsg + (size_t)i * ksuper * kTileBytes
: wsu + (size_t)(i - kPTW) * ksuper * kTileBytes;
};
const uint32_t arow = wa * kGPTA * 16u;
f8v raw[kGTW][kGPTA], out[kGTW][kGPTA];
#pragma unroll
for (uint32_t i = 0; i < kGTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kGPTA; ++j) out[i][j] = acc_zero();
Stage8 pa = stage8_load(asrc, stager);
Stage8 w0[kGTW], w1[kGTW];
#pragma unroll
for (uint32_t i = 0; i < kGTW; ++i) w0[i] = stage8_load(wsrc(i), true);
s_as[0][tid % kGBM] = ssrc[0];
float scn = ssrc[min(1u, nkb - 1u)];
auto tile = [&](uint32_t kb, uint32_t half, Stage8 (&cur)[kGTW], Stage8 (&nxt)[kGTW]) {
if (stager) stage8_store<kPFK>(s_a[half], sr, sc, pa);
if (half == 1u) s_as[(kb + 1u) % 2u][tid % kGBM] = scn;
lds_barrier();
const uint32_t c1 = min(kb * kBlock + (half + 1u) * kPFK, K - kPFK);
pa = stage8_load(asrc + c1, stager);
#pragma unroll
for (uint32_t i = 0; i < kGTW; ++i)
nxt[i] = stage8_load(wsrc(i) + (size_t)(c1 / kSuperK) * kTileBytes, true);
if (half == 1u) scn = ssrc[min(kb + 2u, nkb - 1u)];
#pragma unroll
for (uint32_t ks = 0; ks < kPFK / kK; ++ks) {
i2v bf[kGPTA];
#pragma unroll
for (uint32_t j = 0; j < kGPTA; ++j) bf[j] = frag<kPFK>(s_a[half], arow + j * 16u, ks * kK, lane);
#pragma unroll
for (uint32_t i = 0; i < kGTW; ++i) {
const i2v af = frag_of(cur[i], ks);
#pragma unroll
for (uint32_t j = 0; j < kGPTA; ++j)
raw[i][j] = mma8<false>(af, bf[j], (half == 0u && ks == 0u) ? acc_zero() : raw[i][j]);
}
}
};
for (uint32_t kb = 0; kb < nkb; ++kb) {
const float wg = bscale(Sw[(size_t)(c0 / kBlock) * sw_ld + kb]);
const float wu = bscale(Sw[(size_t)((nout + c0) / kBlock) * sw_ld + kb]);
tile(kb, 0u, w0, w1);
tile(kb, 1u, w1, w0);
#pragma unroll
for (uint32_t j = 0; j < kGPTA; ++j) {
const float as = s_as[kb % 2u][arow + j * 16u + frag_c(lane)];
#pragma unroll
for (uint32_t i = 0; i < kGTW; ++i) {
const float s8 = (i < kPTW ? wg : wu) * as;
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[i][j][t] = __builtin_fmaf(acc_val<false>(raw[i][j][t]), s8, out[i][j][t]);
}
}
}
// gate and up rounded to bf16 as the prefill tile stores them, silu in f32, the product
// rounded to bf16, then the per-(token, 128 columns) E4M3 quantiser.
float v[kPTW][kGPTA][8];
#pragma unroll
for (uint32_t j = 0; j < kGPTA; ++j) {
float m = 0.0f;
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
const float g = bf16_to_f32(f32_to_bf16(out[i][j][t]));
const float a = g / (1.0f + expf(-g));
const uint16_t h = f32_to_bf16(a * bf16_to_f32(f32_to_bf16(out[i + kPTW][j][t])));
v[i][j][t] = bf16_to_f32(h);
m = fmaxf(m, fabsf(v[i][j][t]));
}
// A token's 16 columns of a tile are in lanes c and c ^ 16; the other wave columns are in
// the other three weight waves. fmaxf is exact and order-free.
m = fmaxf(m, r4d_xor_lane<16>(m));
if (lane < 16u) s_amx[ww][arow + j * 16u + lane] = m;
}
__syncthreads();
#pragma unroll
for (uint32_t j = 0; j < kGPTA; ++j) {
const uint32_t r = arow + j * 16u + frag_c(lane), tok = m0 + r;
if (tok >= M) continue;
float mm = 0.0f;
#pragma unroll
for (uint32_t u = 0; u < kPWW; ++u) mm = fmaxf(mm, s_amx[u][r]);
const float sc8 = mm > 0.0f ? mm * (1.0f / 448.0f) : 1.0f;
if (ww == 0u && (lane >> 4) == 0u) Sc[(size_t)tok * s_ld + bn] = sc8;
const float inv = 1.0f / sc8;
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i) {
const uint32_t col0 = c0 + (ww * kPTW + i) * 16u + (lane >> 4) * 8u;
// The clamp is required (see r4d_q8.h): the builtin returns NaN out of range.
float qc[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) qc[t] = fminf(fmaxf(v[i][j][t] * inv, -448.0f), 448.0f);
int pk[2] = { 0, 0 };
#pragma unroll
for (uint32_t d = 0; d < 2; ++d) {
pk[d] = __builtin_amdgcn_cvt_pk_fp8_f32(qc[d * 4 + 0], qc[d * 4 + 1], pk[d], false);
pk[d] = __builtin_amdgcn_cvt_pk_fp8_f32(qc[d * 4 + 2], qc[d * 4 + 3], pk[d], true);
}
*(uint2*)(Q + (size_t)tok * q_ld + col0) = make_uint2((uint32_t)pk[0], (uint32_t)pk[1]);
if (Yb) {
uint16_t* const yr = Yb + (size_t)tok * y_ld + col0;
*(uint4*)yr = make_uint4(bf16x2_rne(v[i][j][0], v[i][j][1]), bf16x2_rne(v[i][j][2], v[i][j][3]),
bf16x2_rne(v[i][j][4], v[i][j][5]), bf16x2_rne(v[i][j][6], v[i][j][7]));
}
}
}
}
// The narrow tile's K width is kFKNarrow (256 B); 128 B loses at every wave count (see `kTPR`), and
// is used only via narrow_fk for a K that 256 does not divide.
@@ -1044,13 +1220,22 @@ uint32_t narrow_mw(uint32_t n, uint32_t m) {
inline uint32_t narrow_fk(uint32_t K) { return (K % kFKNarrow == 0u) ? kFKNarrow : 128u; }
// The split, given the narrow grid. Shared by the scratch query and the launch so they agree on the
// number of partial planes.
uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out) {
// number of partial planes. `short_unsplit` is the `gemm_nt_q_short` row's opt-in (see below).
uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out,
bool short_unsplit = false) {
*ck_out = 0;
const uint32_t mw = narrow_mw(N, M);
const uint32_t fm = mw * 16u; // the narrow tile is one M tile a wave
const uint32_t gx = (N + fm - 1) / fm; // the M grid runs over the weight rows
if (K < 512u || gx * mw >= kSplitTarget) return 1;
/* A narrow weight (N <= 512, the attention k/v projections) at more than 40 tokens: the split
* runs into a cliff there (gfx1200, cold weights: N = 512, K = 2048, M = 44..64 split 51-54 us,
* unsplit 23-26; K = 5120, M = 41..64 58-63 against 40-48), while at K >= 8192 the split still
* wins. Unsplit changes the order these outputs are summed in, so a k/v row at 41..64 tokens
* differs from the split result in its last bits; the rows are as exact either way. Hence an
* opt-in: only `gemm_nt_q_short`, whose declaration the model owns, takes it, and every other
* caller keeps the split and its bits. */
if (short_unsplit && N <= 512u && M > 40u && K <= 5120u) return 1;
const uint32_t want = (kSplitTarget + gx * mw - 1) / (gx * mw);
uint32_t ckw = ((K / want) + kBlock - 1u) / kBlock * kBlock;
if (ckw < kBlock) ckw = kBlock;
@@ -1076,7 +1261,8 @@ extern "C" int r4d_gemm_fp8a8_block(void) { return (int)kBlock; }
static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long scratch, long scratch_bytes, RadStream stream,
bool i8 = false, int split_n = 0, bool chain = false);
bool i8 = false, int split_n = 0, bool chain = false,
bool short_unsplit = false);
extern "C" int r4d_gemm_fp8a8_nt_m16(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
@@ -1111,11 +1297,11 @@ extern "C" void r4d_gemm_fp8a8_pin_nt(int nt) {
// fixes the order K partials are summed in, so a row slice of a wider linear (N rows of a
// split_n-row weight) passes the whole width to sum each output as the whole linear does: the
// slice's outputs are then the linear's to the bit.
static long m16_scratch(int M, int K, int N, int split_n) {
static long m16_scratch(int M, int K, int N, int split_n, bool short_unsplit = false) {
if (M <= 0 || K <= 0 || N <= 0 || M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0;
uint32_t ck = 0;
const uint32_t k2 = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K,
(uint32_t)M, &ck);
(uint32_t)M, &ck, short_unsplit);
return k2 > 1 ? (long)k2 * M * N * (long)sizeof(float) : 0;
}
extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) {
@@ -1135,7 +1321,7 @@ extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) {
static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long scratch, long scratch_bytes, RadStream stream, bool i8,
int split_n, bool chain) {
int split_n, bool chain, bool short_unsplit) {
int emit_rc = RAD_OK;
if (!a || !ascale || !wq || !ws || !c) return -1;
if (M <= 0 || K <= 0 || N <= 0) return -2;
@@ -1157,7 +1343,7 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
uint32_t ck = 0;
uint32_t ksplit = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K,
(uint32_t)M, &ck);
(uint32_t)M, &ck, short_unsplit);
const long need = ksplit > 1 ? (long)ksplit * M * N * (long)sizeof(float) : 0;
if (need && (!scratch || scratch_bytes < need)) { ksplit = 1; ck = 0; }
@@ -1307,7 +1493,7 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16_max_m(void) { return 64; }
static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s,
long y, int act, int M, int K, int nout, int a_ld, int sa_ld,
int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream,
bool chain);
bool chain, bool wide = false);
extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws,
long q, long s, long y, int act,
int M, int K, int nout,
@@ -1316,14 +1502,24 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws
return gemm_fp8a8_gated_launch(a, ascale, wq, ws, q, s, y, act, M, K, nout, a_ld, sa_ld,
w_ld, sw_ld, q_ld, s_ld, y_ld, stream, false);
}
/* The same fold over every row count (`gemm_nt_q_gated_wide`): past the narrow tile's 64 rows it
* takes the gated prefill tile, whose accumulators are the unfused prefill GEMM's. Opt-in by op
* name, so the narrow row above keeps its refusal. */
extern "C" int r4d_gemm_fp8a8_gated_nt_wide(long a, long ascale, long wq, long ws,
long q, long s, long y, int act,
int M, int K, int nout,
int a_ld, int sa_ld, int w_ld, int sw_ld,
int q_ld, int s_ld, int y_ld, long stream) {
return gemm_fp8a8_gated_launch(a, ascale, wq, ws, q, s, y, act, M, K, nout, a_ld, sa_ld,
w_ld, sw_ld, q_ld, s_ld, y_ld, stream, false, true);
}
/* `chain`: the chained form (r4d_rad_gemm_fp8a8_gated_m16 passes the row's parameter). */
static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s,
long y, int act, int M, int K, int nout, int a_ld, int sa_ld,
int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream,
bool chain) {
bool chain, bool wide) {
if (!a || !ascale || !wq || !ws || !q || !s) return -1;
if (M <= 0 || K <= 0 || nout <= 0) return -2;
if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return -3;
if (K % (int)kFKNarrow) return -4;
// A block emits 128 fused columns, one scale group, so nout must be a multiple of 128.
if (nout % 128) return -5;
@@ -1339,6 +1535,21 @@ static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q
if (!s_ld) s_ld = nout / 128;
if (!y_ld) y_ld = nout;
/* Past the narrow tile's rows, the gated prefill tile (gemm_8a8_gated_prefill_kernel), whose
* accumulators are the unfused prefill GEMM's. Only the wide row (`gemm_nt_q_gated_wide`) takes
* it: the narrow op refuses there, as it always has. */
if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) {
if (!wide) return -3;
if ((q_ld | y_ld) % 8 || (q & 7) || (y && (y & 15))) return -7;
const dim3 grid(((uint32_t)M + kGBM - 1) / kGBM, (uint32_t)(nout / 128), 1);
hipLaunchKernelGGL(gemm_8a8_gated_prefill_kernel, grid, dim3(kPWaves * kWave), 0,
(hipStream_t)stream, (const uint8_t*)a, (const float*)ascale,
(const uint8_t*)wq, (const uint16_t*)ws, (uint8_t*)q, (float*)s,
(uint16_t*)y, (uint32_t)M, (uint32_t)K, (uint32_t)nout, (uint32_t)a_ld,
(uint32_t)sa_ld, (uint32_t)sw_ld, (uint32_t)q_ld, (uint32_t)s_ld,
(uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -6;
}
// The fold cannot split K, so a shape the split rule would split is refused (gate_up's shape,
// N/16 = 1088, never splits).
uint32_t ck = 0;
@@ -1456,6 +1667,30 @@ extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) {
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
/* `gemm_nt_q_short`: the narrow row above with the short-prompt split rule, whose declaration the
* model owns (narrow_ksplit's `short_unsplit`). The scratch query matches it, so the split the
* launch takes is the one the arena was sized for. */
extern "C" int64_t r4d_rad_gemm_fp8a8_m16_short_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0),
K = r4d_geti_or(a, "K", 0), sn = r4d_geti_or(a, "split_n", 0);
if (M < 1 || N < 1 || K < 1) return 0;
if (M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0;
return (int64_t)m16_scratch((int)M, (int)K, (int)N, (int)sn, true);
}
extern "C" int r4d_rad_gemm_fp8a8_m16_short(const RadArgs* a, RadStream stream) {
Fp8Ops g;
int rc = fp8_ops(a, &g, 1);
if (rc != RAD_OK) return rc;
if (g.M > r4d_gemm_fp8a8_nt_m16_max_m()) return R4D_NO(RAD_E_SHAPE);
const int e = gemm_fp8a8_nt_m16_emit(
r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld,
(long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, false,
(int)r4d_geti_or(a, "split_n", 0), r4d_geti_or(a, "chain", 0) != 0, true);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
/* gemm_nt_q_bias's shim: gemm_nt_q's four operands, then the bias and C (oGemmNtQBias in
* r4d_rows.cpp). Not fp8_ops: C is operand 5 and may be a column slice of a wider buffer, which
* fp8_ops refuses for the unbiased kernels' dense store. */
@@ -1501,7 +1736,9 @@ extern "C" int r4d_rad_gemm_fp8a8_bias_m16(const RadArgs* a, RadStream s) {
* `gemm_nt_q_gated`'s (oGemmNtQGated in r4d_rows.cpp). */
enum { GG_A = 0, GG_AS = 1, GG_B = 2, GG_BS = 3, GG_Q = 4, GG_S = 5, GG_Y = 6 };
extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) {
/* The gated shim's body, for the narrow row (`wide` false: M <= 64, the fold's narrow tile) and for
* `gemm_nt_q_gated_wide` (`wide` true: the gated prefill tile past it). */
static int r4d_rad_gemm_fp8a8_gated(const RadArgs* a, RadStream s, bool wide) {
const RadTensor* x = r4d_opt(a, GG_A);
const RadTensor* xs = r4d_opt(a, GG_AS);
const RadTensor* w = r4d_opt(a, GG_B);
@@ -1522,7 +1759,6 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) {
* it. */
const long long M = q->shape[0], nout = q->shape[1], K = w->shape[1];
if (M < 1 || nout < 1 || K < 1) return R4D_NO(RAD_E_SHAPE);
if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return R4D_NO(RAD_E_SHAPE);
if (w->shape[0] != 2 * nout) return R4D_NO(RAD_E_SHAPE);
const long long nkb = (K + blk - 1) / blk;
if (wsc->shape[0] != (2 * nout + blk - 1) / blk || wsc->shape[1] != nkb)
@@ -1547,10 +1783,18 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) {
r4d_addr(x), r4d_addr(xs), r4d_addr(w), r4d_addr(wsc),
r4d_addr(q), r4d_addr(sc), y ? r4d_addr(y) : 0, 0,
(int)M, (int)K, (int)nout, (int)ap, (int)asp, (int)wp, (int)wsp,
(int)qp, (int)sp, (int)yp, (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0);
(int)qp, (int)sp, (int)yp, (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0, wide);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) {
return r4d_rad_gemm_fp8a8_gated(a, s, false);
}
extern "C" int r4d_rad_gemm_fp8a8_gated_wide(const RadArgs* a, RadStream s) {
return r4d_rad_gemm_fp8a8_gated(a, s, true);
}
/* ---- the int8 twins' shims: the same operands with i8 codes and the weight's scale plane per
* row, which fp8_ops checks at [N][K/128] when asked (FP8_OPS_ROW_SCALE). */
extern "C" int64_t r4d_rad_gemm_i8a8_m16_scratch(const RadArgs* a) {
+53 -53
View File
@@ -17,6 +17,8 @@
//
// `x` depends on all of `d`, so no workgroup can produce a channel of `x` before every column of
// `d` exists. The kernel boundary serves as the grid-wide barrier, without cooperative launch.
// For a small decode step (E4M3, hc 4, n 2560, up to seven rows), hc_read_fused_kernel runs A and
// B as one grid instead, its B blocks waiting on a ticket-ordered counter (see that kernel's note).
//
// Weight traffic, not arithmetic, decides the decomposition. At Qwen3.8-Flash-Next's shape
// (n 2560, hc 4, LR 320) each mixing matrix is 6.55 MB and there are 96 connections: 1.27 GB per
@@ -207,9 +209,10 @@ __device__ __forceinline__ float hc8_dot_down(const unsigned short* __restrict__
return acc;
}
/* hc8_dot_down for two rows of W_down at once, one read of N from LDS feeding both. A
* wave owning two columns (four rows of a decode step) read the 20 KB vector once per column, and
* kernel A's dots were LDS-bound. Each row's sum is the same fmaf sequence as hc8_dot_down's. */
/* hc8_dot_down for two rows of W_down at once, one read of N from LDS feeding both, so a wave
* owning two columns (four rows of a decode step) reads the 20 KB vector once rather than once per
* column; kernel A's dots are LDS-bound. Each row's sum is the same fmaf sequence as
* hc8_dot_down's. */
__device__ __forceinline__ float hc8_dot16n(const float* nf, uint4 c) {
float wf[16];
e4m3x8(c.x, c.y, wf);
@@ -320,9 +323,8 @@ __device__ __forceinline__ void hc8_up_load(const unsigned char* __restrict__ wr
/* RPT rows of W_up with the same quarter against RG rows of `d`: each value of `d` read from LDS
* feeds RPT products, and `d` sits in LDS as the bf16 it is, sixteen values in two 16-byte reads
* (the quarter, its group and lr are multiples of 16 by r4d_hc8::group_ok, and the base is aligned).
* Read as floats a value at a time, the dot was a chain of LDS round trips: 7.4 of the 22.8 us at
* four rows with every byte cache-resident. Each (row, r) accumulates the same fmaf sequence on the
* same values as hc8_dot_up. */
* Read as floats a value at a time, the dot would be a chain of LDS round trips. Each (row, r)
* accumulates the same fmaf sequence on the same values as hc8_dot_up. */
template <int RG, int RPT>
__device__ __forceinline__ void hc8_up_dot_rows(const unsigned short* __restrict__ sdh, long lr,
const Hc8UpQuarter* o, int q4,
@@ -373,7 +375,7 @@ __device__ __forceinline__ float wave_sum(float v) { return r4d_wave_sum(v); }
/* A barrier that orders LDS only. __syncthreads() fences at workgroup scope, which in
* WGP mode on gfx12 waits for every outstanding global load: a load issued for the next pass of a
* K loop could not stay in flight across it, and a software-pipelined loop ran as serially as the
* K loop cannot stay in flight across it, so a software-pipelined loop runs as serially as the
* plain one. Where a barrier guards only LDS tiles, this one leaves global loads in flight. */
__device__ __forceinline__ void hc_lds_barrier() {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
@@ -882,9 +884,9 @@ constexpr long kHcReadAStaticLds = (long)(kWaves * kHcMax + kHcMax) * (long)size
* Flash-Next's shape). Thread t's elements of `h` are then t + e * kThreads for e < HCP * PER, the
* stream being e / PER, so every one of them and of the norm weight can be loaded before the first
* is used: one round trip from the cache instead of one per stream for the sums of squares and
* again for N, the ten-odd dependent latencies that set the decode step's time here (the kernel
* ran 8.3 us at one row with every byte cache-resident). The sums and N take the same values in
* the same order, so the output is bit-identical to the loops below. */
* again for N. Those ten-odd dependent latencies, not bytes, set the kernel's time at decode. The
* sums and N take the same values in the same order, so the output is bit-identical to the loops
* below. */
template <bool F8, int HCP = 0, int PER = 0>
__device__ __forceinline__ void hc_read_a_body(const unsigned short* __restrict__ h, const float* __restrict__ w,
const void* __restrict__ downv, long dld,
@@ -896,7 +898,7 @@ __device__ __forceinline__ void hc_read_a_body(const unsigned short* __restrict_
unsigned xpub) {
/* 16-byte aligned, for the 16-byte LDS reads of the dots. The dynamic region starts
* after the kernel's static LDS, which in hc_read_fused_kernel is not a multiple of 16; a
* misaligned base ran the fused form's A blocks three times slower at four rows. */
* misaligned base makes the fused form's A blocks three times slower at four rows. */
extern __shared__ __attribute__((aligned(16))) unsigned short sN[]; /* [hc * n], transposed per 256-element chunk */
__shared__ float s_part[kWaves][kHcMax];
__shared__ float s_scale[kHcMax];
@@ -1289,14 +1291,14 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon
const int ipb = kBR / hc; /* channels this workgroup owns */
const long i0 = (long)bx * ipb;
/* Every load this kernel makes before its first barrier, issued together. At
* decode it is a chain of dependent latencies, not a stream of bytes (12 us at four rows with
* every byte cache-resident). `d` goes first, all of a thread's share at once (lr is at most
* two thread strides here), since loads return in order and `d` is what the barrier waits on;
* then this thread's quarter row of W_up, which does not depend on `d`; then, when one mix item
* a thread covers the block's (RG * ipb <= the thread count, always at hc 4), the hc values N
* of its channel from `h`, the norm gain and kernel A's scales. Same values, same order:
* bit-identical. */
/* Every load this kernel makes before its first barrier, issued together: at decode the
* kernel is a chain of dependent latencies, not a stream of bytes. `d` goes first, all of a
* thread's share at once (lr is at most two thread strides here), since loads return in order
* and `d` is what the barrier waits on; then this thread's quarter row of W_up, which does not
* depend on `d`; then, when one mix item a thread covers the block's (RG * ipb <= the thread
* count, always at hc 4), the hc values N of its channel from `h`, the norm gain and kernel
* A's scales. Only the issue order moves; the arithmetic sees the same values in the same
* order, so the result is bit-identical. */
constexpr int kDStage = 2;
const bool dpre = lr <= (long)kDStage * kThreads;
unsigned short dv[RG][kDStage]; /* bf16 bits; the E4M3 dot keeps them as is */
@@ -1325,7 +1327,7 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon
const bool one = RG * ipb <= kThreads;
float Npre[kHcMax];
if constexpr (WAIT) {
/* The fused form (hc_read_fused_kernel): `h` and the gain now, kernel A's half after it. */
/* The fused form (hc_read_fused_kernel): `h` and the gain here, kernel A's half after it. */
float hv[kHcMax], wv[kHcMax];
const int rl = one && tid < RG * ipb ? tid / ipb : 0, ii = tid - rl * ipb;
const long r = r0 + rl < rows ? r0 + rl : rows - 1;
@@ -1475,9 +1477,9 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon
if (r >= rows) return;
const long base = (i0 / kUpTB) * kUpTB;
const unsigned short* const xr = x + r * xrow + base;
/* A lane's four channels, read once for the amax, the codes and the rotation (it
* read the group three times, each a dependent round trip at the end of the step's chain). The
* amax is over the same 128 values and max is exact, so this is bit-identical. */
/* A lane's four channels, read once for the amax, the codes and the rotation; separate reads
* would each be a dependent round trip at the end of the step's chain. The amax is over the
* same 128 values and max is exact, so the result is bit-identical. */
static_assert(kUpTB == 4 * kWave, "a lane holds four channels of the group");
float v[4];
#pragma unroll
@@ -1598,10 +1600,9 @@ static inline int hc_up_launch(const RadTensor* up, long uld, bool f8, const uns
}
/* Rows of W_up a thread (hc_up_mix_kernel's RPT), where the wider workgroup's channels
* still divide a scale group and the width. Two, measured at Flash-Next's shape (rad-kbench, cold,
* the fused form at one, two and four rows): one row 18.4 / 18.9 / 20.6 us, two 17.0 / 17.8 /
* 20.4; four, before the bf16 dot, lost to two at every count (27.0 us at four rows, past the
* registers). */
* still divide a scale group and the width. Two: at Flash-Next's shape (cold caches, the fused
* form at one, two and four rows) two beats one at every row count, and four runs past the
* register budget and loses to two. */
constexpr int kUpRpt = 2;
static inline int hc_up_rpt(bool f8, int hc, long n) {
int rpt = f8 ? kUpRpt : 1;
@@ -1611,20 +1612,18 @@ static inline int hc_up_rpt(bool f8, int hc, long n) {
return rpt;
}
/* hc_up_mix_kernel's launch: hc_up's row group; counter slots are (rows / rg) row groups of
* n / kUpTB scale groups. */
/* ============================================================== the previous decode kernels
/* ============================================================== the two-grid decode kernels
*
* hc_read's decode kernels as they were before the one-grid form and the pipelined tiled up-mix:
* kernel A, then the up-mix kernel in a second launch, and the tiled up-mix with its K passes in
* sequence. Kept verbatim behind r4d_hc_read_pin_decode(1) so r4d_selftest can compare the
* current forms with them byte for byte and --perfhc can time both from one build. */
* hc_read's decode path as two launches: kernel A, then the up-mix kernel in a second launch, and
* the tiled up-mix with its K passes unpipelined. r4d_hc_read_pin_decode(1) selects them, so
* r4d_selftest can compare the served forms against them byte for byte and --perfhc can time both
* from one build. They are the reference for that comparison; keep them as they are. */
static int g_hc_decode_form = 0;
template <bool F8>
__global__ __launch_bounds__(kThreads)
__attribute__((amdgpu_waves_per_eu(F8 ? 9 : 1, F8 ? 9 : 16)))
void hc_read_a_prev_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w,
void hc_read_a_2grid_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w,
const void* __restrict__ downv, long dld,
const unsigned short* __restrict__ injw,
unsigned short* __restrict__ dout, unsigned short* __restrict__ inj,
@@ -1767,7 +1766,7 @@ void hc_read_a_prev_kernel(const unsigned short* __restrict__ h, const float* __
template <int RG, bool F8, bool I8 = false>
__global__ __launch_bounds__(kThreads)
void hc_up_mix_prev_kernel(const void* __restrict__ upv, long uld,
void hc_up_mix_2grid_kernel(const void* __restrict__ upv, long uld,
const unsigned short* __restrict__ dbuf,
const unsigned short* __restrict__ h, const float* __restrict__ w,
const float* __restrict__ scalein,
@@ -1877,7 +1876,7 @@ void hc_up_mix_prev_kernel(const void* __restrict__ upv, long uld,
}
}
static inline int hc_up_mix_prev_launch(const RadTensor* up, long uld, bool f8, bool i8,
static inline int hc_up_mix_2grid_launch(const RadTensor* up, long uld, bool f8, bool i8,
const unsigned short* dbuf,
const unsigned short* h, const float* w, const float* scale,
unsigned short* x, unsigned char* q, float* qs,
@@ -1892,7 +1891,7 @@ static inline int hc_up_mix_prev_launch(const RadTensor* up, long uld, bool f8,
const unsigned lds = (unsigned)(rg * lr * sizeof(float));
const void* upp = up->data;
#define HC_UPMIX_CASE3(RG_, F8_, I8_) \
emit_rc = R4D_EMIT(stream, (hc_up_mix_prev_kernel<RG_, F8_, I8_>), grid, dim3(kThreads), lds, \
emit_rc = R4D_EMIT(stream, (hc_up_mix_2grid_kernel<RG_, F8_, I8_>), grid, dim3(kThreads), lds, \
upp, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, (long)rows, (long)n, \
hc, \
(long)lr, (long)hrow, (long)xrow, (long)qrow, (long)srow, (long)rqrow, \
@@ -1914,6 +1913,8 @@ static inline int hc_up_mix_prev_launch(const RadTensor* up, long uld, bool f8,
return emit_rc;
}
/* hc_up_mix_kernel's launch: hc_up's row group; counter slots are (rows / rg) row groups of
* n / kUpTB scale groups. */
static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool i8,
const unsigned short* dbuf,
const unsigned short* h, const float* w, const float* scale,
@@ -1924,7 +1925,7 @@ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool
long long srow, long long rqrow, long long rsrow, float wadd,
RadStream stream) {
if (g_hc_decode_form == 1)
return hc_up_mix_prev_launch(up, uld, f8, i8, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr,
return hc_up_mix_2grid_launch(up, uld, f8, i8, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr,
rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd,
stream);
int emit_rc = RAD_OK;
@@ -2598,11 +2599,10 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld,
/* At the decode tile (RT 32, E4M3, lr a whole number of passes) the K loop is
* software-pipelined: a pass issues the next pass's loads before staging its own from
* registers, and the mix's operands are loaded with the first pass, where each pass waited
* on its own loads. Addresses are computed once, nothing branches and the barriers order LDS
* only (hc_lds_barrier), so the waits stay partial. 17.8 -> 16.6 us at 32 rows (rad-kbench,
* cold): the kernel is bound less by memory than by its staging, barriers and WMMA. The staged
* values are the loop's own, in the same order: bit-identical. */
* registers, and the mix's operands are loaded with the first pass. Addresses are computed
* once, nothing branches and the barriers order LDS only (hc_lds_barrier), so the waits stay
* partial; the kernel is bound less by memory than by its staging, barriers and WMMA. The
* staged values are the loop's own, in the same order: bit-identical. */
constexpr int kAPer = RT * (kTKT / 8) / kThreads, kBPer = NT * (kTKT / 8) / kThreads;
constexpr int kNPer = RT * NT / kThreads;
constexpr bool kPipe = F8 && RT == 32 && kAPer == 1 && kBPer * kThreads == NT * (kTKT / 8)
@@ -2767,10 +2767,10 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld,
/* The rotated codes need a whole wave per row, while the codes below use kThreads / RT threads
* per row, so the rotation walks the tile's rows a wave at a time first. */
/* Both finishers below load what they read before using any of it -- the
* rotation every row of the wave's, the codes a thread's four-channel runs -- where they
* walked rows and channels a dependent load at a time; the codes' amax is over the same 128
* values. The tail of this kernel is one block's chain, so these were its links. Bit-identical. */
/* Both finishers below load what they read before using any of it (the rotation every row
* of the wave's, the codes a thread's four-channel runs) rather than one dependent load at a
* time, since the tail of this kernel is one block's latency chain. The codes' amax is over
* the same 128 values, so the result is bit-identical. */
if (rq) {
const long gb = (i0 / kUpTB) * kUpTB;
constexpr int kRPW = (RT + kWaves - 1) / kWaves; /* rows a wave */
@@ -2819,11 +2819,11 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld,
}
}
/* The tiled up-mix as it was before its K passes were pipelined (see the previous decode
* kernels above; r4d_hc_read_pin_decode(1)). */
/* The tiled up-mix with its K passes unpipelined, for r4d_hc_read_pin_decode(1) (see the
* two-grid decode kernels above). */
template <int RT, int NT, bool F8, bool I8 = false>
__global__ __launch_bounds__(kThreads)
void hc_up_mix_tiled_prev_kernel(const void* __restrict__ upv, long uld,
void hc_up_mix_tiled_2grid_kernel(const void* __restrict__ upv, long uld,
const unsigned short* __restrict__ dbuf,
const unsigned short* __restrict__ h, const float* __restrict__ w,
const float* __restrict__ scalein,
@@ -3246,7 +3246,7 @@ static inline void hc_up_mix_tiled_launch(int rt, bool f8, bool i8, const void*
rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd)
#define HC_UM_CASE3(RT_, F8_, I8_) \
do { \
if (g_hc_decode_form == 1) HC_UM_K((hc_up_mix_tiled_prev_kernel<RT_, kTNT, F8_, I8_>)); \
if (g_hc_decode_form == 1) HC_UM_K((hc_up_mix_tiled_2grid_kernel<RT_, kTNT, F8_, I8_>)); \
else HC_UM_K((hc_up_mix_tiled_kernel<RT_, kTNT, F8_, I8_>)); \
} while (0)
#define HC_UM_CASE(RT_, F8_) \
@@ -4812,7 +4812,7 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) {
inj ? (unsigned short*)inj->data : nullptr, scale, (long)rows, (long)n, (int)hc, \
(long)lr, (long)ta, (long)hrow, (long)irow, eps, wadd)
if (g_hc_decode_form == 1)
emit_rc = f8 ? HC_READ_A(hc_read_a_prev_kernel<true>) : HC_READ_A(hc_read_a_prev_kernel<false>);
emit_rc = f8 ? HC_READ_A(hc_read_a_2grid_kernel<true>) : HC_READ_A(hc_read_a_2grid_kernel<false>);
else if (pre) emit_rc = HC_READ_A((hc_read_a_kernel<true, 4, 10>));
else emit_rc = f8 ? HC_READ_A(hc_read_a_kernel<true>) : HC_READ_A(hc_read_a_kernel<false>);
#undef HC_READ_A
+154 -8
View File
@@ -614,6 +614,52 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
}
}
// The same rotary at prefill row counts with each (token, pair) angle computed once. rope_kernel
// gives every (head, pair) its own thread, which recomputes powf and the accurate sincosf for every
// head; the angle depends on the token and the pair alone, so at 32 heads 31 of 32 evaluations are
// repeats (q at 408 tokens: ~50 us on gfx1200). Here a thread owns one pair of one token and turns
// that pair in every head. Byte-identical: the angle, cos and sin are rope_kernel's expressions on
// the same inputs, and each head's two stores are its.
__global__ __launch_bounds__(kThreads) void rope_rows_kernel(
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos, uint32_t M,
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, uint32_t nfreq, int den, int gptj,
float theta, float rscale, uint32_t row_pitch,
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn, RadLlama3 l3) {
const uint32_t half = rot / 2;
const uint32_t rpb = kThreads / half; // rows a block; half <= kThreads
const uint32_t m = blockIdx.x * rpb + threadIdx.x / half, i = threadIdx.x % half;
if (threadIdx.x >= rpb * half || m >= M) return;
const float div = rscale != 0.0f ? rscale : 1.0f;
const float p0 = (float)pos[m] / div;
const int sec[3] = { s0, s1, s2 };
float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den);
float p = p0;
if (plane) {
uint32_t j = i;
const int c = rope_comp(mode, i, sec, n_sec, &j);
p = (float)pos[(size_t)c * plane + m] / div;
if (mode == 4)
inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c]));
}
inv = yarn.frequency(inv, (int)i);
inv = l3.frequency(inv);
if (i >= nfreq) inv = 0.0f;
const float ang = p * inv;
float c, s;
sincosf(ang, &s, &c);
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
const uint32_t i0 = gptj ? 2 * i : i;
const uint32_t i1 = gptj ? 2 * i + 1 : i + half;
uint16_t* __restrict__ row = qkv + (size_t)m * row_pitch;
for (uint32_t h = 0; h < n_rope_heads; ++h) {
uint16_t* __restrict__ hd = row + (size_t)h * head_dim;
const float x0 = bf16_to_f32(hd[i0]), x1 = bf16_to_f32(hd[i1]);
hd[i0] = f32_to_bf16(x0 * c - x1 * s);
hd[i1] = f32_to_bf16(x0 * s + x1 * c);
}
}
// ---------------------------------------------------------------------------- kv_store
// ref_kv_store. The paged layout every kernel in this project shares:
//
@@ -952,20 +998,65 @@ extern "C" int r4d_scatter_rows_u8(long v, long idx, long x, int M, int n, int d
(RadStream)(uintptr_t)stream);
}
// Short rows (n <= 256: per-head q/k norms at head_dim 64..256): a wave a row, eight rows a block.
// rmsnorm_kernel gives such a row a whole workgroup of 256+ threads, most of them idle, and at a
// prefill step's T x heads rows (13,000 at 408 tokens x 32 heads) the launch is bound by workgroup
// dispatch: ~48 us for 1.7 MB on gfx1200.
//
// Byte-identical to rmsnorm_kernel at any width it is launched at. There, with n no wider than the
// block, thread i holds element i alone; each wave's 32 squares are summed by r4d_wave_sum and the
// wave sums are added in wave order from 0.f (block_sum), the waves past the row adding exact
// zeros. Here lane l holds elements l + 32c of the row, chunk c summed by the same r4d_wave_sum,
// and the chunk sums added in the same order. The scale and the store are rmsnorm_kernel's.
constexpr uint32_t kShortNormMax = 256;
template <bool WF32>
__global__ __launch_bounds__(256) void rmsnorm_short_kernel(
const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y,
uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld, uint32_t M) {
const uint32_t lane = threadIdx.x & (kWave - 1);
const uint32_t m = blockIdx.x * (256u / kWave) + threadIdx.x / kWave;
if (m >= M) return;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
constexpr uint32_t NC = kShortNormMax / kWave;
float v[NC];
float ss = 0.0f;
#pragma unroll
for (uint32_t c = 0; c < NC; ++c) {
const uint32_t i = lane + c * kWave;
v[c] = i < n ? bf16_to_f32(xr[i]) : 0.0f;
if (c * kWave < n) {
float q = 0.0f;
q += v[c] * v[c];
ss += r4d_wave_sum(q);
}
}
const float s = rsqrtf(ss / (float)n + eps);
#pragma unroll
for (uint32_t c = 0; c < NC; ++c) {
const uint32_t i = lane + c * kWave;
if (i >= n) continue;
const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]);
yr[i] = f32_to_bf16(v[c] * s * (g + wadd) * mult);
}
}
// `w_f32` selects an f32 or bf16 gain; a null `w` is a gain of one. `mult` scales the row before
// its single rounding.
/* `chain`: the chained form, at decode heights (r4d_rad_rmsnorm passes the row's resolved
* parameter; every other caller none). */
* parameter; every other caller none). `rows_form`: the caller declared `rmsnorm_rows` and the
* short-row form may be taken (rmsnorm_short_kernel); every other caller keeps rmsnorm_kernel. */
static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd,
float mult, int w_f32, int x_ld, int y_ld, long stream,
bool chain);
bool chain, bool rows_form = false);
extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float eps, float wadd,
float mult, int w_f32, int x_ld, int y_ld, long stream) {
return rmsnorm_mult_launch(x, w, y, M, n, eps, wadd, mult, w_f32, x_ld, y_ld, stream, false);
}
static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd,
float mult, int w_f32, int x_ld, int y_ld, long stream,
bool chain) {
bool chain, bool rows_form) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!x_ld) x_ld = n;
@@ -977,6 +1068,23 @@ static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps,
const int thr = r4d_act_threads(M, n);
// A drafter's 256-row head norm at 256 threads is exactly a full card; step past the cliff.
const bool ch = chain && M <= 64;
/* Short rows at more rows than the card has waves: a wave a row (rmsnorm_short_kernel, the
* same bytes). Below that the per-row workgroups already fill the part. Opt-in by op name, so
* every other caller's launch is the one it had. */
if (rows_form && n <= (int)kShortNormMax && M >= 1024 && !ch) {
/* Eight waves a block, stepped past the cliff r4d_cliff_rows names for the card's wave
* count (on the 32-CU part 1024 rows are 1024 waves: 17 us against 7 at 3264). */
const dim3 grid(r4d_cliff_rows(((uint32_t)M + 7u) / 8u, 1, 8));
if (w_f32)
hipLaunchKernelGGL((rmsnorm_short_kernel<true>), grid, dim3(256), 0, (hipStream_t)stream,
(const uint16_t*)x, (const void*)w, (uint16_t*)y, (uint32_t)n, eps,
wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M);
else
hipLaunchKernelGGL((rmsnorm_short_kernel<false>), grid, dim3(256), 0, (hipStream_t)stream,
(const uint16_t*)x, (const void*)w, (uint16_t*)y, (uint32_t)n, eps,
wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
#define R4D_RN_T(wf, T) \
hipLaunchKernelGGL((ch ? r4dchain_rmsnorm<wf, T> : rmsnorm_kernel<wf, T>), \
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), \
@@ -1180,7 +1288,7 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
int gptj, float theta, float rscale, int row_pitch, int mode,
const int* sec, int n_sec, int plane, RadYarn yarn, long stream,
int nfreq = -1, RadLlama3 l3 = RadLlama3{}) {
int nfreq = -1, RadLlama3 l3 = RadLlama3{}, bool rows_form = false) {
if (!qkv || !pos) return -1;
if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2;
if (rot <= 0 || rot > head_dim || (rot & 1)) return -3;
@@ -1190,6 +1298,19 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
const uint32_t gy = (pairs + kThreads - 1) / kThreads;
const int s0 = n_sec > 0 ? sec[0] : 0, s1 = n_sec > 1 ? sec[1] : 0, s2 = n_sec > 2 ? sec[2] : 0;
if (nfreq < 0) nfreq = rot / 2;
/* Prefill rows with at least four heads: one angle a (token, pair), every head turned with it
* (rope_rows_kernel, the same bytes). Decode rows keep a thread a (head, pair), which spreads a
* single token over the card. Opt-in by op name (`rope_rows`): every other caller's launch is
* the one it had. */
if (rows_form && M >= 64 && n_rope_heads >= 4 && rot / 2 <= (int)kThreads) {
const uint32_t rpb = kThreads / (uint32_t)(rot / 2);
hipLaunchKernelGGL(rope_rows_kernel, dim3(((uint32_t)M + rpb - 1) / rpb), dim3(kThreads), 0,
(hipStream_t)stream, (uint16_t*)qkv, (const int32_t*)pos, (uint32_t)M,
(uint32_t)head_dim, (uint32_t)n_rope_heads, (uint32_t)rot,
(uint32_t)nfreq, (int)den, gptj, theta, rscale, (uint32_t)row_pitch, mode,
s0, s1, s2, n_sec, (uint32_t)plane, yarn, l3);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
(uint32_t)n_rope_heads, (uint32_t)rot, (uint32_t)nfreq, (int)den, gptj, theta,
@@ -1696,7 +1817,9 @@ static int rmsnorm_x_f32(const float* x, const void* w, uint16_t* y, int M, int
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
/* `rows_form`: the row is `rmsnorm_rows`, which may take the short-row form (rmsnorm_short_kernel).
* Every other caller passes false and gets the launch it always had. */
static int rmsnorm_emit(const RadArgs* a, RadStream s, bool rows_form) {
const RadTensor* x = r4d_opt(a, RN_X);
const RadTensor* w = r4d_opt(a, RN_W);
const RadTensor* y = r4d_opt(a, RN_Y);
@@ -1746,7 +1869,18 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
return rmsnorm_mult_launch(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd,
(float)r4d_getf(a, "mult", 1.0),
w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s,
r4d_geti_or(a, "chain", 0) != 0) == 0 ? RAD_OK : RAD_E_DEVICE;
r4d_geti_or(a, "chain", 0) != 0, rows_form) == 0
? RAD_OK : RAD_E_DEVICE;
}
extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
return rmsnorm_emit(a, s, false);
}
/* `rmsnorm_rows`: the same norm, whose launch may take the short-row form (n <= 256 at 1024 rows
* or more, the head norms of a prefill step). Byte-identical to the row above at every width. */
extern "C" int r4d_rad_rmsnorm_rows(const RadArgs* a, RadStream s) {
return rmsnorm_emit(a, s, true);
}
/* ------------------------------------------------------------------ add_rmsnorm */
@@ -2095,7 +2229,9 @@ extern "C" int r4d_rad_gelu_mul(const RadArgs* a, RadStream s) {
enum { RP_QKV = 0, RP_POS };
extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
/* `rows_form`: the row is `rope_rows`, which may turn every head of a (token, pair) with the one
* angle it computed (rope_rows_kernel). Every other caller passes false. */
static int rope_emit(const RadArgs* a, RadStream s, bool rows_form) {
const RadTensor* qkv = r4d_opt(a, RP_QKV);
const RadTensor* pos = r4d_opt(a, RP_POS);
if (!qkv || !pos) return R4D_NO(RAD_E_INVAL);
@@ -2181,11 +2317,21 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot_l, (int)den, gptj, theta, rscale,
(int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s,
(int)nfreq, l3) == 0
(int)nfreq, l3, rows_form) == 0
? RAD_OK
: RAD_E_DEVICE;
}
extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
return rope_emit(a, s, false);
}
/* `rope_rows`: the same rotation, whose launch may compute one angle a (token, pair) and turn every
* head with it (rope_rows_kernel, the same bytes) at prefill row counts. */
extern "C" int r4d_rad_rope_rows(const RadArgs* a, RadStream s) {
return rope_emit(a, s, true);
}
/* ------------------------------------------------------------------ kv_store */
enum { KS_K = 0, KS_V, KS_SLOT, KS_CACHE };
+20
View File
@@ -175,6 +175,18 @@ int r4d_rad_attn_window_h512_gqa8_fp8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*);
/* attn_paged_qrow_tree (docs/OPS.md): the h256/gqa2 split-KV decode and the windowed kernels with a
* tree verify's mask from operand 8, `spec_parent`. */
int r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16(const RadArgs*, RadStream);
#define R4D_WIN_TREE_DECL(HD, G) \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_bf16(const RadArgs*, RadStream); \
int r4d_rad_attn_window_tree_h##HD##_gqa##G##_fp8 (const RadArgs*, RadStream);
R4D_WIN_TREE_DECL(256, 1) R4D_WIN_TREE_DECL(256, 2) R4D_WIN_TREE_DECL(256, 4) R4D_WIN_TREE_DECL(256, 8)
R4D_WIN_TREE_DECL(512, 1) R4D_WIN_TREE_DECL(512, 2) R4D_WIN_TREE_DECL(512, 4) R4D_WIN_TREE_DECL(512, 8)
#undef R4D_WIN_TREE_DECL
/* dflash_tree (r4d_dflash_tree_bf16.hip): dflash_select's lattice grown best-first into a tree. */
int r4d_rad_dflash_tree(const RadArgs*, RadStream);
/* The top-1 of a row of all-gathered (id, value) pairs, written one id a row: the vocab-sharded
* draft head's merge (r4d_pair_argmax_f32.hip). */
int r4d_rad_pair_argmax_f32(const RadArgs*, RadStream);
@@ -563,6 +575,10 @@ int r4d_rad_rope_table (const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a16_m1 (const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_m16 (const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_gated_wide(const RadArgs*, RadStream);
/* `gemm_nt_q_short`: the narrow row with the short-prompt split rule (narrow_ksplit). */
int r4d_rad_gemm_fp8a8_m16_short(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_fp8a8_m16_short_scratch(const RadArgs*);
int r4d_rad_gemm_fp8a8_bias_m16(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs*);
int r4d_rad_gemm_fp8a8_tiled(const RadArgs*, RadStream);
@@ -728,6 +744,8 @@ int r4d_rad_gather_rows_u8 (const RadArgs*, RadStream);
int r4d_rad_scatter_rows_u8 (const RadArgs*, RadStream);
int r4d_rad_scatter_rows_bf16(const RadArgs*, RadStream);
int r4d_rad_rmsnorm (const RadArgs*, RadStream);
/* The same row choosing the short-row form when it serves (`rmsnorm_rows`, rmsnorm_short_kernel). */
int r4d_rad_rmsnorm_rows (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_p (const RadArgs*, RadStream);
int r4d_rad_add (const RadArgs*, RadStream);
int r4d_rad_mul (const RadArgs*, RadStream);
@@ -787,6 +805,8 @@ int r4d_shape_moe_gather_inv(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_router_sigmoid_topk_scatter(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_gelu_mul (const RadArgs*, RadStream);
int r4d_rad_rope (const RadArgs*, RadStream);
/* The same row choosing the per-(token, pair) angles form when it serves (`rope_rows`). */
int r4d_rad_rope_rows (const RadArgs*, RadStream);
/* -- the vision tower's ops (r4d_vit_bf16.hip) -- */
int r4d_rad_layernorm (const RadArgs*, RadStream);
int r4d_rad_grid_embed (const RadArgs*, RadStream);
+7 -5
View File
@@ -308,7 +308,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags,
unsigned int* seq_ctrs, int M, uint32_t n, float eps, float wadd, uint32_t r_ld, uint32_t y_ld,
int slot_stride16, int drain, int acq, unsigned int nbw) {
int slot_stride16, int drain, int acq, unsigned int nbw, long stage) {
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
@@ -319,7 +319,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); /* device-resident, replay-safe */
const unsigned int sq = s_seq;
int4* const ps = peer_base + (size_t)s_slot * slot_stride16;
const int4* const ms = my_base + (size_t)s_slot * slot_stride16;
const int4* ms = my_base + (size_t)s_slot * slot_stride16;
const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h)
/* push my rows into the peer's slot; `x` is a tight [M][n] of bf16 */
const int wpr = (int)(n >> 3);
@@ -346,8 +347,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) {
for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR)
h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k);
});
ms = r4d_archk_moved(ms, md);
const uint16_t* __restrict__ P = (const uint16_t*)ms; /* the peer's rows, in my scratch */
const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f;
@@ -938,7 +940,7 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long
long x, long res, long w, long wp, long sc, int sc_f32,
long y, long q, long s, int M, int n, float eps, float wadd,
int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq) {
int drain, int acq, long stage) {
if (!x || !w || !q || !s) return -1;
if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1;
if (M <= 0 || n <= 0) return -2;
@@ -961,7 +963,7 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long
(const int4*)my_scratch, (unsigned int*)peer_flags, \
(unsigned int*)my_flags, (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, \
wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, drain, acq, \
(unsigned)nbw)
(unsigned)nbw, stage)
#define R4D_ARQ8(WF, RS, PO, SC) \
do { if (thr == 1024) R4D_ARQ8_T(WF, RS, PO, SC, 1024); \
else if (thr == 512) R4D_ARQ8_T(WF, RS, PO, SC, 512); \
+207 -4
View File
@@ -123,6 +123,18 @@ static const RadOperandSpec oAttnPaged[] = {
{ "cu_seqlens", RAD_OPD_IN, 1 }, /* absent = one q_len for the whole batch */
{ "out", RAD_OPD_OUT, 0 },
};
/* attn_paged_qrow with a tree verify's parents (RadBatch::spec_parent, rad_drafter_tree). */
static const RadOperandSpec oAttnPagedTree[] = {
{ "q", RAD_OPD_IN, 0 },
{ "kv_cache", RAD_OPD_IN, 0 },
{ "block_table", RAD_OPD_IN, 0 },
{ "seqused", RAD_OPD_IN, 0 },
{ "k_descale", RAD_OPD_IN, 1 },
{ "v_descale", RAD_OPD_IN, 1 },
{ "cu_seqlens", RAD_OPD_IN, 1 },
{ "out", RAD_OPD_OUT, 0 },
{ "spec_parent", RAD_OPD_IN, 0 },
};
/* attn_paged with gate_quant_fp8 folded into its merge: attn_paged's parameters plus the two of
* gate_quant_fp8's that are not implied (its `n` is `head_dim`, its rows attn_paged's (token,
@@ -700,6 +712,28 @@ static const RadOperandSpec oDflashSelect[] = {
{ "succ", RAD_OPD_WEIGHT, 0 },
{ "tokens", RAD_OPD_OUT, 0 },
};
/* dflash_tree: dflash_select's, plus the node count, the softmax temperature and the parents. */
static const RadParamSpec pDflashTree[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "steps", RAD_P_INT, RAD_REQUIRED },
{ "top_k", RAD_P_INT, RAD_REQUIRED },
{ "rank", RAD_P_INT, RAD_REQUIRED },
{ "n_vocab", RAD_P_INT, RAD_REQUIRED },
{ "anchor_stride", RAD_P_INT, RAD_OPTIONAL },
{ "nodes", RAD_P_INT, RAD_REQUIRED },
{ "temp", RAD_P_F64, RAD_OPTIONAL },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
static const RadOperandSpec oDflashTree[] = {
{ "cand", RAD_OPD_IN, 0 },
{ "unary", RAD_OPD_IN, 0 },
{ "hp", RAD_OPD_IN, 1 },
{ "anchor", RAD_OPD_IN, 0 },
{ "pred", RAD_OPD_WEIGHT, 0 },
{ "succ", RAD_OPD_WEIGHT, 0 },
{ "tokens", RAD_OPD_OUT, 0 },
{ "parents", RAD_OPD_OUT, 0 },
};
/* ------------------------------------------------------------------------------ collectives */
static const RadParamSpec pAllReduce[] = {
@@ -2894,6 +2928,11 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("rmsnorm", pRmsNorm, oRmsNorm,
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in "
"f32 after the load because forming it in bf16 first costs 0.3% per channel."),
SCHEMA("rmsnorm_rows", pRmsNorm, oRmsNorm,
"the same norm, and its launch is the same except at n <= 256 with 1024 or more rows, "
"where a wave a row computes the row and sums its squares in rmsnorm_kernel's wave "
"order (byte-identical). An op name of its own so a caller that has not asked for it "
"keeps the per-row workgroups it always had."),
SCHEMA("rmsnorm_p", pLayernorm, oUnary,
"y = x * rsqrt(mean(x^2) + eps); an rmsnorm with NO gain tensor at all. Gemma's "
"attention normalises the value with a bare RMS (a weightless ggml_rms_norm) and the "
@@ -3016,6 +3055,11 @@ static const RadOpSchema kSchemas[] = {
"that follow are untouched. The multi-component modes (`mrope`, `imrope`, `axial`) "
"take [C, M] component-major positions and `sections`; with [M] positions every "
"component is that one, so mrope and imrope over a text batch are neox exactly."),
SCHEMA("rope_rows", pRope, oRope,
"the same rotation, and its launch is the same except with 64 or more rows and 4 or "
"more heads, where a thread owns one (token, pair) angle and turns that pair in every "
"head (byte-identical). An op name of its own so a caller that has not asked for it "
"keeps a thread a (head, pair), which spreads a decode's single token over the card."),
SCHEMA("layernorm", pLayernorm, oLayernorm,
"y = (x - mean) * rsqrt(var + eps) * w + b, biased variance, two passes. `b` optional."),
SCHEMA("grid_embed", pGridEmbed, oGridEmbed,
@@ -3144,6 +3188,11 @@ static const RadOpSchema kSchemas[] = {
"attn_paged, parameter for parameter and value for value, with q read at its own row "
"pitch: a column slice of a wider row -- the q part of a fused [q|k|v] projection -- read "
"where it lies rather than lifted into a dense block first."),
SCHEMA("attn_paged_qrow_tree", pAttnPaged, oAttnPagedTree,
"attn_paged_qrow over a tree verify (rad_drafter_tree): spec_parent is -2 for an "
"ordinary causal row, else the row's parent's index within its sequence's rows (-1 for "
"the block's first row). Inside the block such a row sees itself and its ancestors "
"only, and its window is measured from the block's first position plus its depth."),
SCHEMA("attn_paged_gate_quant", pAttnPagedGq, oAttnPagedGq,
"attn_paged followed by gate_quant_fp8 over its output, in the split-KV merge: each "
"merged (token, head) row is gated, rounded, written to `out` and quantised to E4M3 "
@@ -3250,6 +3299,12 @@ static const RadOpSchema kSchemas[] = {
"positions, and the greedy walk that turns a block of independent top-k sets into one "
"path. Only the K edges leaving the previous pick are scored, because the walk is "
"serial and the other K-1 rows of the score matrix are never read."),
SCHEMA("dflash_tree", pDflashTree, oDflashTree,
"dflash_select's lattice and edge scores grown best-first into a tree of `nodes` nodes: "
"a taken node's children are the valid candidates at the next position, each with log "
"probability parent + log_softmax(score / temp) over them; each round takes the largest "
"untaken child (ties to the first pushed). tokens and parents list the taken nodes in "
"order, a parent as its node index, 0 for the anchor."),
SCHEMA("all_reduce", pAllReduce, oAllReduce,
"sum over the tensor-parallel group. `exact` separates the exact sum from the "
"quantised wire and a caller that does not declare it gets no kernel. At 4 and 8 ranks "
@@ -3266,6 +3321,12 @@ static const RadOpSchema kSchemas[] = {
"C[M,N] = A[M,K] @ dequant(Bq)[N,K]^T. `dtype` names the operand COMBINATION, so one "
"op covers w4a16 through mxfp4a8 and an architecture plugin that changes quant changes "
"one string."),
SCHEMA("gemm_nt_q_short", pGemmNtQ, oGemmNtQ,
"the narrow fp8a8 row of `gemm_nt_q` with the short-prompt split rule: at N <= 512, K "
"<= 5120 and 41..64 rows it runs unsplit, where the split's per-slice floors dominate. "
"The split COUNT changes, so a row here is not bit-identical to the same row split; "
"both are exact. An op name of its own so every other caller keeps the split and "
"its bits."),
SCHEMA("gemm_nt_q_bias", pGemmNtQBias, oGemmNtQBias,
"gemm_nt_q with a per-column bias added to the f32 product before its one rounding."),
SCHEMA("dequant_w4", pDequantW4, oDequantW4,
@@ -3418,6 +3479,10 @@ static const RadOpSchema kSchemas[] = {
"columns) and optionally the bf16 product, and no [M, 2n] tensor is ever written. "
"Byte-identical to the two ops it replaces, which is what makes it substitutable "
"rather than a second numerical path."),
SCHEMA("gemm_nt_q_gated_wide", pGemmNtQGated, oGemmNtQGated,
"gemm_nt_q_gated at every M: the narrow tile to 64 rows and the gated prefill tile past "
"them, whose accumulators are the unfused prefill GEMM's. An op name of its own so the "
"narrow row keeps its M <= 64 band, its kernel and every other caller's path."),
SCHEMA("gemm_nt_q_gated_mx", pGemmNtQGated, oGemmNtQGatedMx,
"gemm_nt_q_gated over an OCP-MXFP4 [2n, K] gate_up weight: gemm_nt_q at dtype mxfp4a8 "
"(`b_ref` the per-row reference exponent) with gated_quant_fp8's pass folded into the "
@@ -3920,6 +3985,15 @@ static const RadConstraint cAttnDecodeH256Gqa2Fp8[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
/* attn_paged_qrow_tree on the same kernel: causal only (a tree has no two-sided reading). */
static const RadConstraint cAttnTreeDecodeH256Gqa2Fp8[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_EQ("causal", 1), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnTreeDecodeH256Gqa2Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_EQ("causal", 1), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
@@ -4455,6 +4529,12 @@ static const RadConstraint cDflashSelect[] = {
C_GE("steps", 1), C_GE("top_k", 1), C_LE("top_k", 32),
C_DIV("rank", 32), C_LE("rank", 512), C_IN("dtype", "bf16"),
};
/* dflash_tree's frontier (nodes x top_k children) and its node table live in LDS. */
static const RadConstraint cDflashTree[] = {
C_GE("steps", 1), C_LE("steps", 63), C_GE("top_k", 1), C_LE("top_k", 32),
C_DIV("rank", 32), C_LE("rank", 512), C_GE("nodes", 1), C_LE("nodes", 63),
C_IN("dtype", "bf16"),
};
/* The sandwich-norm joins hold 24 elements a thread over a 256-thread block (n <= 6144), and the
* route form quantises in whole 128-column groups. pair_argmax takes any row; expert_scale's top_k
* is the router's, at most 64. */
@@ -4913,6 +4993,14 @@ static const RadConstraint cGemmNtQGatedFp8[] = {
C_LE("M", 64), C_DIV("K", 256), C_DIV("N", 256), C_GE("N", 2048),
C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"),
};
/* `gemm_nt_q_gated_wide`: the same fold at any M. Past the narrow tile's 64 rows it runs the gated
* prefill tile, whose accumulators are the unfused prefill GEMM's, so its bytes are the pair's. An
* op name of its own, and one a model declares when it wants the whole prompt in the fold: the
* narrow row above keeps its ceiling, its kernel and every other caller's path. */
static const RadConstraint cGemmNtQGatedFp8Wide[] = {
C_DIV("K", 256), C_DIV("N", 256), C_GE("N", 2048),
C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"),
};
/* r4d_gemm_mxfp4a8_gated_gemv: the gemv row's WMMA form (K a multiple of 128, M <= 8) with a block
* per 16-column tile pair of the gated output. N/2 is a multiple of 128, so each 128-column
* group's eight blocks meet at its last arriver, which quantises the group. */
@@ -4933,6 +5021,7 @@ static const RadConstraint cGemmNtQGatedMxWide[] = {
static const RadConstraint cGateQuantFp8[] = {
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
};
/* `act` none is the plain product (`mul`), for a producer that is not a gate activation. */
/* libr4d's cSampleChain. The kernel has no geometry constraint (the radix passes run over a
* float's 256 byte buckets), but a row with no predicate would match a query that named nothing. */
static const RadConstraint cSampleChain[] = {
@@ -5819,6 +5908,18 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_rmsnorm, nullptr, nullptr, nullptr,
r4d_shape_rmsnorm },
/* The same norm, whose launch takes rows of 256 or fewer columns a wave a row once there are
* enough of them to fill the part; the chunk sums are rmsnorm_kernel's in wave order. */
{ "rmsnorm_rows_bf16", "rmsnorm_rows", "norm",
"root-mean-square norm with a gain, two passes over the row, a wave a short row at prefill row "
"counts",
"any n; the short-row form needs n <= 256 and 1024 or more rows; byte-identical to rmsnorm",
"bf16 y, x bf16 or (with a gain) f32, bf16 or f32 gain, fp32 reduction",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_rmsnorm_rows, nullptr, nullptr, nullptr,
r4d_shape_rmsnorm },
{ "rmsnorm_p_bf16", "rmsnorm_p", "norm",
"weightless root-mean-square norm (no gain), two passes over the row",
"any n; the sum of squares accumulates in f32 and only the store narrows",
@@ -6077,6 +6178,17 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_rope, nullptr, nullptr, nullptr,
r4d_shape_rope },
/* The same rotation with one angle a (token, pair) and every head turned with it, at prefill row
* counts: the angle does not depend on the head, so a thread owns one pair of one token. */
{ "rope_rows_bf16", "rope_rows", "attn",
"rotary embedding in place, one thread a (token, pair) angle, every head turned with it",
"the rope row's geometry; the per-angle form needs 64 or more rows and 4 or more heads",
"bf16 qkv, i32 positions, fp32 angles through the accurate sincosf; byte-identical to rope",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cRopeRow), NOTUNE,
nullptr, nullptr, r4d_rad_rope_rows, nullptr, nullptr, nullptr,
r4d_shape_rope },
{ "kv_store_bf16", "kv_store", "attn",
"scatter k and v into the paged cache, one workgroup a token",
"cache exactly [n_blocks, kv_heads, block_size, 2*head_dim]; a negative or out-of-range slot "
@@ -6653,6 +6765,28 @@ static const RadKernelInfo kKernels[] = {
r4d_rad_attn_qrow_decode_h256_gqa2_scratch,
nullptr, nullptr, nullptr },
/* The same under attn_paged_qrow_tree: a tree verify's mask (O_TREE instances), causal only. */
{ "attn_qrow_tree_decode_h256_gqa2_fp8kv", "attn_paged_qrow_tree", "attn",
"paged attention over a tree verify, q at its own row pitch, sliding window, split-KV",
"head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, causal",
"bf16 query (any row pitch, a multiple of 4), fp8-e4m3 kv cache with per-(seq,head) descales, "
"i32 parents, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnTreeDecodeH256Gqa2Fp8), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8,
r4d_rad_attn_qrow_decode_h256_gqa2_scratch,
nullptr, nullptr, nullptr },
{ "attn_qrow_tree_decode_h256_gqa2_bf16kv", "attn_paged_qrow_tree", "attn",
"paged attention over a tree verify, q at its own row pitch, sliding window, split-KV",
"head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, causal",
"bf16 query (any row pitch, a multiple of 4), bf16 kv cache, i32 parents, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnTreeDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16,
r4d_rad_attn_qrow_decode_h256_gqa2_scratch,
nullptr, nullptr, nullptr },
/* Head_dim 128 at gqa 8 under attn_paged_qrow (cAttnQrowH128G8Fp8 says why). */
{ "attn_qrow_h128_gqa8_fp8kv", "attn_paged_qrow", "attn",
"paged attention, any window, causal or not, split-KV (draft block); q at any row pitch",
@@ -6841,6 +6975,27 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
#undef R4D_WIN_PAIR
#undef R4D_WIN_ROW
/* ...and under attn_paged_qrow_tree, the scalar kernel with a tree verify's mask (the launch
* refuses a non-causal one and never takes the WMMA kernel). */
#define R4D_WIN_TREE_ROW(HD, G, KVN, KVS, C, KVDOC) \
{ "attn_qrow_tree_h" #HD "_gqa" #G "_" #KVN, "attn_paged_qrow_tree", "attn", \
"paged attention over a tree verify, q at its own row pitch, any window, causal", \
"head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \
"bf16 query (any row pitch), " KVDOC " kv cache, i32 parents, bf16 out, f32 partials", \
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, \
ROW(C), NOTUNE, \
nullptr, nullptr, r4d_rad_attn_window_tree_h##HD##_gqa##G##_##KVS, \
r4d_rad_attn_window_h##HD##_scratch, \
nullptr, nullptr, nullptr },
#define R4D_WIN_TREE_PAIR(HD, GQ) \
R4D_WIN_TREE_ROW(HD, GQ, bf16kv, bf16, cWinH##HD##G##GQ##Bf16, "bf16") \
R4D_WIN_TREE_ROW(HD, GQ, fp8kv, fp8, cWinH##HD##G##GQ##Fp8, "fp8-e4m3 (per-(seq,head) descales)")
R4D_WIN_TREE_PAIR(256, 1) R4D_WIN_TREE_PAIR(256, 2) R4D_WIN_TREE_PAIR(256, 4)
R4D_WIN_TREE_PAIR(256, 8) R4D_WIN_TREE_PAIR(512, 1) R4D_WIN_TREE_PAIR(512, 2)
R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
#undef R4D_WIN_TREE_PAIR
#undef R4D_WIN_TREE_ROW
{ "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
@@ -7800,6 +7955,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block,
r4d_shape_gemm_nt_q, r4d_rad_unrelayout_fp8_block },
/* The same narrow row with the short-prompt split rule (narrow_ksplit's `short_unsplit`), whose
* declaration the model owns: the scratch hook matches, so the split the launch takes is the one
* the arena was sized for. */
{ "gemm_fp8a8_nt_m16_short", "gemm_nt_q_short", "gemm",
"gemm_fp8a8_nt_m16 choosing its split from the short-prompt rule: at N <= 512, K <= 5120 and "
"41..64 rows the split's per-slice floors dominate and the row runs unsplit",
"the narrow row's: M <= 64; K a multiple of 128; N a multiple of 16",
"E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, bf16 C. "
"Unsplit sums its K blocks in one order and split its partial planes in another, so a row here "
"differs from the split result in its last bits; both are exact",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_M16,
ROW(cGemmNtFp8A8M16), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_fp8a8_m16_short, r4d_rad_gemm_fp8a8_m16_short_scratch,
r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block,
r4d_shape_gemm_nt_q, r4d_rad_unrelayout_fp8_block },
{ "gemm_fp8a8_gated_nt_m16", "gemm_nt_q_gated", "gemm",
"the narrow fp8 GEMM with the SwiGLU and the fp8 quantiser folded into its epilogue: the block's "
"waves split in half over the gate rows and the up rows, so a block emits one whole 128-column "
@@ -7819,6 +7990,23 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
/* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */
r4d_fuse_gemm_nt_q_gated },
/* The same fold at every M: the narrow tile to 64 rows, past them the gated prefill tile (128
* gate and 128 up rows against 64 activation rows a block), whose accumulators are the unfused
* prefill GEMM's. An op name of its own, which the model declares when it wants the whole prompt
* in the fold. */
{ "gemm_fp8a8_gated_nt_wide", "gemm_nt_q_gated_wide", "gemm",
"gemm_fp8a8_gated_nt_m16 at every M",
"any M; K a multiple of 256 and N of 256 for the narrow row's reasons; act silu only; the "
"prefill tile past 64 rows needs q_ld and y_ld multiples of 8 and a 16-byte-aligned y",
"E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, and the "
"QUANTISER's outputs; byte-identical to gemm_nt_q followed by gated_quant_fp8 at every M",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGemmNtQGatedFp8Wide), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_fp8a8_gated_wide, nullptr,
r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block,
r4d_shape_gemm_nt_q_gated, r4d_rad_unrelayout_fp8_block,
r4d_fuse_gemm_nt_q_gated },
{ "gemm_fp8a8_tiled", "gemm_nt_q", "gemm",
"the same GEMM for prefill row counts: 128x128 tile, eight waves of 2 weight x 4 activation "
"tiles, the weight read straight into registers and the activation staged through LDS, one K "
@@ -8570,16 +8758,16 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
{ "gate_quant_fp8", "gate_quant_fp8", "quant",
"an elementwise gated product and the fp8 activation quantiser in one pass, with the gate in "
"its own operand: a gated attention's gate is a column slice of the [q|gate] projection and "
"cannot be packed beside the attention output it scales",
"cannot be packed beside the attention output it scales; `act` none is `mul` + `quant_act_fp8`",
"n a multiple of 4; gate and x are both [M][n] and may have different pitches; no reduction "
"across the row, so no barrier; group 128; strides in elements",
"across the row, so no barrier; group 128; strides in elements; `act` silu, sigmoid or none",
"bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes "
"are taken over the BF16-ROUNDED product",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGateQuantFp8), NOTUNE,
nullptr, nullptr, r4d_rad_gate_quant_fp8, nullptr, nullptr, nullptr,
r4d_shape_gate_quant_fp8, nullptr,
/* `sigmoid` + `mul` + `quant_act_fp8`; the silu arm is declined (r4d_fuse.cpp). */
/* `sigmoid` + `mul` + `quant_act_fp8`, and `mul` + `quant_act_fp8` for act none (r4d_fuse.cpp). */
r4d_fuse_gate_quant_fp8 },
/* ---------------------------------------------------------------------------------- sampling
@@ -9038,6 +9226,16 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_dflash_select, nullptr, nullptr, nullptr,
r4d_shape_dflash_select },
{ "dflash_tree_bf16", "dflash_tree", "dflash",
"DFlash2's candidate lattice grown best-first into a tree (rad_drafter_tree): the selector's "
"edge scores for each taken node's children, one workgroup a sequence",
"top_k <= 32, rank a multiple of 32 and <= 512, steps and nodes <= 63: the frontier and the "
"node table are LDS extents",
"i32 candidate ids, f32 unary logits, bf16 hp and both codebooks, i32 tokens and parents out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cDflashTree), NOTUNE,
nullptr, nullptr, r4d_rad_dflash_tree, nullptr, nullptr, nullptr, nullptr },
/* pair_argmax, the sandwich-norm joins and expert_scale. The joins and expert_scale have no
* opd_shape: libref has no row for them, and tests/r4d_emu holds their source to the replaced chain
* bit for bit on the host. pair_argmax is described as libref describes it. */
@@ -10057,6 +10255,8 @@ extern "C" int rad_kernel_chain(int i) {
* plain, and the backend chains only the kernels named r4dchain* */
"attn_decode_h256_gqa2_fp8kv", "attn_decode_h256_gqa2_bf16kv",
"attn_qrow_decode_h256_gqa2_fp8kv", "attn_qrow_decode_h256_gqa2_bf16kv",
/* ...and their tree verify forms (O_TREE instances, the same launch) */
"attn_qrow_tree_decode_h256_gqa2_fp8kv", "attn_qrow_tree_decode_h256_gqa2_bf16kv",
/* the fused junction: its tail form (the two-shot with the junction after it) only */
"ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8_4rank",
/* the 31B's full layers: the windowed attention and its merge (r4d_attn_paged_window.hip,
@@ -10064,6 +10264,9 @@ extern "C" int rad_kernel_chain(int i) {
"attn_qrow_h512_gqa2_fp8kv", "attn_qrow_h512_gqa2_bf16kv",
"attn_qrow_h512_gqa4_fp8kv", "attn_qrow_h512_gqa4_bf16kv",
"attn_qrow_h512_gqa8_fp8kv", "attn_qrow_h512_gqa8_bf16kv",
"attn_qrow_tree_h512_gqa2_fp8kv", "attn_qrow_tree_h512_gqa2_bf16kv",
"attn_qrow_tree_h512_gqa4_fp8kv", "attn_qrow_tree_h512_gqa4_bf16kv",
"attn_qrow_tree_h512_gqa8_fp8kv", "attn_qrow_tree_h512_gqa8_bf16kv",
"quant_act_i8",
/* DFlash2's query and context passes: the narrow fp8 GEMMs (the gated gate_up among
* them), the activation quantiser, the norms, the conv projection, the opening
@@ -10081,7 +10284,7 @@ extern "C" int rad_kernel_chain(int i) {
* selector */
"sample_temp_f32", "sample_topk_f32", "sample_merge_topk_f32", "sample_pick_f32",
"ar_gather_4rank", "gemm_w8a8_nt_m64", "rowtopk_bf16", "rowtopk_merge",
"dflash_select_bf16",
"dflash_select_bf16", "dflash_tree_bf16",
/* the weight read beside a collective (its blocks add before reading, r4d_prefetch.hip) */
"prefetch",
};
+328 -12
View File
@@ -1051,6 +1051,63 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8
* band's upper bound (RadArgs.p), so `trim` here is 4096 while the issued count, and `tail`'s
* extent, is 1024. 90ede42 read the parameter, trimmed a 2048-key context to 0, and the attention
* over slice A's rows wrote nothing. */
/* The full-attention decode split law (r4d_decode_splits), read through the scratch hook's declare
* path, where the depth is the declared max_ctx. Qwen3.8-27B's TP2 rank: 12 query heads over 2 KV
* heads, head_dim 256. An 8-row verify (three waves at gqa 6) splits by depth: up to 16384 tokens
* 128 / units (x4: 16), then at least 64, and past 65536 512 / units capped at 256 (x1: 256, x2:
* 128, x4 and more: 64). A plain decode and the short block's 4-row verify keep the 256-workgroup
* target, and the two-tiles-a-segment cap still binds a short context (1024 tokens: 64 tiles of
* 16, at most 32 segments).
*
* The declared region is the worst over every sequence count up to max_seqs and every query length
* up to q_len (a shorter step can split more: attn_decode_scratch), so the region over the region
* at one forced segment is that worst, in the batch's own rows: `splits` is the law at the batch,
* `region` what the declare path must hold, at least `splits`. Where a 5-row step at shallow depth
* splits more per row than the 8-row verify (x1 at 65536, x2 and x4 at 16384, x4 at 1024), the
* region is the shorter step's. */
static void decode_split_law_case(const Plugin& pl) {
const char* name = "attn_decode_h256_gqa6_bf16kv";
if (!sel(name)) return;
const RadKernelInfo* r = find(pl, name);
if (!r || !r->scratch) { ok("decode split law", false, "row or its scratch hook absent"); return; }
auto bytes = [&](int64_t seqs, int64_t q_len, int64_t ctx, int64_t splits) {
std::vector<RadParam> ps = {
PI("n_head", 12), PI("gqa", 6), PI("head_dim", 256), PI("block_size", 16),
PI("max_seqs", seqs), PI("q_len", q_len), PI("max_ctx", ctx),
};
if (splits > 0) ps.push_back(PI("splits", splits));
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
return r->scratch(&a);
};
struct Want { int64_t seqs, q_len, ctx, splits, region; };
const Want want[] = {
{ 1, 8, 100000, 256, 256 }, { 2, 8, 100000, 128, 128 }, { 4, 8, 100000, 64, 64 },
{ 6, 8, 100000, 64, 64 }, { 8, 8, 100000, 64, 64 }, { 2, 8, 65536, 64, 64 },
{ 2, 8, 65552, 128, 128 }, { 1, 8, 65536, 64, 80 }, { 2, 8, 32768, 64, 64 },
{ 4, 8, 32768, 64, 64 }, { 7, 8, 32768, 64, 64 }, { 4, 8, 16400, 64, 64 },
{ 4, 8, 16384, 16, 20 }, { 2, 8, 16384, 32, 40 }, { 4, 8, 1024, 16, 20 },
{ 1, 8, 1024, 32, 32 }, { 4, 8, 640, 16, 16 }, { 8, 4, 100000, 16, 16 },
{ 16, 4, 100000, 8, 8 }, { 4, 1, 100000, 32, 32 }, { 1, 1, 100000, 128, 128 },
};
int bad = 0;
for (const Want& w : want) {
const int64_t law = bytes(w.seqs, w.q_len, w.ctx, 0), one = bytes(w.seqs, w.q_len, w.ctx, 1);
const int64_t got = one > 0 && law > 0 && law % one == 0 ? law / one : -1;
if (got != w.region || w.region < w.splits) {
std::printf(" FAIL decode split law: %lld x %lld rows over %lld: a region of %lld "
"segments, want %lld (the batch's own %lld)\n",
(long long)w.seqs, (long long)w.q_len, (long long)w.ctx, (long long)got,
(long long)w.region, (long long)w.splits);
++bad;
}
}
g_fail += bad;
if (!bad) std::printf(" ok decode split law: %zu batches\n", sizeof(want) / sizeof(want[0]));
}
static void kv_len_trim_case(const Plugin& pl) {
const char* name = "kv_len_trim";
if (!sel(name)) return;
@@ -1706,6 +1763,80 @@ static void attn_split_scratch_case(const Plugin& pl, const SplitGeo& g, const c
}
}
/* Every split-KV decode row's scratch at declare (the band's bound, parameters only, as the core
* sizes it) against what its launch checks at issue (the same hook over the issue's tensors): for
* each band bound up to 64 / gqa rows, every query length up to it and every sequence count up to
* max_seqs must fit. Host only; the tensors carry shapes and aligned placeholder addresses. The
* h256 split law targets 256 workgroups at q_len * gqa <= 32 and 128 above, so a step shorter than
* its band's bound can need more partials than the bound: 1.13.0 sized the bound only, and an MTP
* step of 4 rows at gqa 8 (band 5) refused with RAD_E_SCRATCH at issue (#293). */
static void attn_decode_scratch_band_case(const Plugin& pl) {
for (int k = 0; k < pl.kernel_count(); ++k) {
const RadKernelInfo* r = pl.kernel_at(k);
int hd = 0, gqa = 0;
if (std::strncmp(r->name, "attn_decode_h", 13) || !r->scratch ||
std::sscanf(r->name, "attn_decode_h%d_gqa%d", &hd, &gqa) != 2 || hd <= 0 || gqa <= 0)
continue;
if (!sel(r->name) && !sel("attn_decode_scratch")) continue;
const char* kvs = std::strrchr(r->name, '_') + 1;
const bool bf = !std::strcmp(kvs, "bf16kv");
const int64_t rowe = !std::strcmp(kvs, "fp8v4") ? 25 * hd / 16
: !std::strcmp(kvs, "k6v4") ? 22 * hd / 16 : 2 * hd;
const int64_t bs = std::strstr(r->name, "_bs4_") ? 4 : 16;
const int64_t max_seqs = 32, max_ctx = 200000, mb = (max_ctx + bs - 1) / bs;
const int top = std::max(1, 64 / gqa);
void* const fake = (void*)(uintptr_t)4096; /* aligned, never dereferenced */
std::string why;
int checked = 0;
for (const int64_t kv : { 1, 2 }) {
const int64_t n_head = kv * gqa;
for (int band = 1; band <= top; ++band) {
std::vector<RadParam> ps = {
PI("q_len", band), PI("head_dim", hd), PI("gqa", gqa), PI("n_head", n_head),
PI("max_seqs", max_seqs), PI("max_ctx", max_ctx), PI("block_size", bs),
PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"),
PS("kv_dtype", bf ? "bf16" : "fp8_e4m3") };
RadArgs d;
std::memset(&d, 0, sizeof(d));
d.p = ps.data(); d.n_p = (int)ps.size(); d.world_size = 1;
const int64_t declared = r->scratch(&d);
if (declared < 0) { why += fmt("; kv%lld band %d: declare refused %lld", (long long)kv,
band, (long long)declared); continue; }
/* the issue: no n_head / max_seqs, so the hook reads the tensors */
std::vector<RadParam> pi = {
PI("q_len", band), PI("head_dim", hd), PI("gqa", gqa), PI("max_ctx", max_ctx),
PI("block_size", bs), PI("causal", 1), PI("window", 0) };
for (int q = 1; q <= band; ++q)
for (int64_t n = 1; n <= max_seqs; ++n) {
std::vector<RadTensor> ts = {
T(fake, RAD_BF16, { n * q, n_head, hd }),
T(fake, bf ? RAD_BF16 : RAD_F8E4M3, { n * mb, kv, bs, rowe }),
T(fake, RAD_I32, { n, mb }), T(fake, RAD_I32, { n }),
T(fake, RAD_F32, { n, kv }), T(fake, RAD_F32, { n, kv }),
T(nullptr, RAD_I32, { n + 1 }),
T(fake, RAD_BF16, { n * q, n_head, hd }) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = pi.data(); a.n_p = (int)pi.size(); a.world_size = 1;
const int64_t need = r->scratch(&a);
++checked;
if (need < 0 || need > declared) {
why += fmt("; kv%lld band %d: q_len %d x %lld sequences needs %lld, "
"declared %lld", (long long)kv, band, q, (long long)n,
(long long)need, (long long)declared);
q = band;
break;
}
}
}
}
ok(fmt("%s: decode scratch at declare covers every shorter step", r->name).c_str(),
why.empty() && checked > 0,
why.empty() ? fmt("%d issue geometries", checked) : why.substr(2));
}
}
/* The h256/gqa6 prefill over an 8-bit cache with e4m3 products (`prefill_fp8` 1 Q.K^T, 2 P.V, 3
* both), against the inline oracle and against `exact`, the cache's exact row, on the same data.
@@ -13185,6 +13316,103 @@ static void fused_quant_fp8_numeric(const Plugin& pl) {
"rc=" + std::to_string(rc));
else same("gate_quant_fp8 is byte-identical to sigmoid + mul + quant_act_fp8");
/* --- mul + quant_act_fp8, against gate_quant_fp8 at act none -------------------------------
*
* LFM2's convolution gate: C * conv(B * x), then the codes its out projection reads. The
* kernel must round the product to bf16 (the `mul` step stores bf16) and take the codes over
* that value. Strided sources: gate and x are column slices of [M, 2K] planes, so a kernel
* ignoring a pitch reads the wrong half. Rows 1, 8 and 65 cover the narrow width's boundary
* and one past it; the scale plane stays K/128 wide at every M. */
{
const int64_t NROW = 65;
std::vector<uint16_t> hg((size_t)NROW * 2 * K), hx2((size_t)NROW * 2 * K);
for (int64_t r = 0; r < NROW; ++r)
for (int64_t c = 0; c < K; ++c) {
const float m = std::ldexp(1.0f, (int)(c / 128) - 2);
const float v = m * (0.041f * (float)((r * 31 + c * 17) % 73) - 1.4f);
hg[(size_t)r * 2 * K + c] = h_to_bf16(c == (r * 13) % K ? v * 23.0f : v);
hx2[(size_t)r * 2 * K + c] = h_to_bf16(m * (0.013f * (float)((r * 7 + c * 11) % 47) - 0.3f));
}
void* d_g = dalloc(hg.size() * 2);
void* d_x2 = dalloc(hx2.size() * 2);
void* d_py[2] = { dalloc((size_t)NROW * K * 2), dalloc((size_t)NROW * K * 2) };
void* d_pq[2] = { dalloc((size_t)NROW * K), dalloc((size_t)NROW * K) };
void* d_ps[2] = { dalloc((size_t)NROW * nkb * 4), dalloc((size_t)NROW * nkb * 4) };
if (!d_g || !d_x2 || !d_py[1] || !d_pq[1] || !d_ps[1]) {
ok("mul + quant_act_fp8 vs gate_quant_fp8 act none", false, "hipMalloc failed");
} else {
st_memcpy(d_g, hg.data(), hg.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_x2, hx2.data(), hx2.size() * 2, hipMemcpyHostToDevice);
for (const int64_t m : { (int64_t)1, (int64_t)8, (int64_t)65 }) {
RadTensor g = T(d_g, RAD_BF16, { m, K }); g.stride[0] = 2 * K;
RadTensor x = T(d_x2, RAD_BF16, { m, K }); x.stride[0] = 2 * K;
int r2 = launch_row(ml, { g, x, T(d_py[0], RAD_BF16, { m, K }) },
{ PI("M", m), PI("n", K), PS("dtype", "bf16") });
if (r2 == RAD_OK)
r2 = launch_row(qz, { T(d_py[0], RAD_BF16, { m, K }),
T(d_pq[0], RAD_F8E4M3, { m, K }),
T(d_ps[0], RAD_F32, { m, nkb }) },
{ PI("M", m), PI("n", K), PI("group", 128),
PS("dtype", "bf16") });
if (r2 == RAD_OK)
r2 = launch_row(tq, { g, x, T(d_pq[1], RAD_F8E4M3, { m, K }),
T(d_ps[1], RAD_F32, { m, nkb }),
T(d_py[1], RAD_BF16, { m, K }) },
{ PI("M", m), PI("n", K), PI("group", 128),
PS("dtype", "bf16"), PS("act", "none") });
if (r2 != RAD_OK) {
ok(("mul + quant_act_fp8 vs gate_quant_fp8 act none, M=" +
std::to_string(m)).c_str(), false, "rc=" + std::to_string(r2));
continue;
}
std::vector<uint16_t> y0((size_t)m * K), y1((size_t)m * K);
std::vector<uint8_t> qq0((size_t)m * K), qq1((size_t)m * K);
std::vector<float> ss0((size_t)m * nkb), ss1((size_t)m * nkb);
st_memcpy(y0.data(), d_py[0], y0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(y1.data(), d_py[1], y1.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(qq0.data(), d_pq[0], qq0.size(), hipMemcpyDeviceToHost);
st_memcpy(qq1.data(), d_pq[1], qq1.size(), hipMemcpyDeviceToHost);
st_memcpy(ss0.data(), d_ps[0], ss0.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(ss1.data(), d_ps[1], ss1.size() * 4, hipMemcpyDeviceToHost);
size_t ny = 0, nq = 0, ns = 0, nz = 0;
for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i];
for (size_t i = 0; i < qq0.size(); ++i) {
nq += qq0[i] != qq1[i];
nz += qq1[i] != 0;
}
for (size_t i = 0; i < ss0.size(); ++i)
ns += std::memcmp(&ss0[i], &ss1[i], 4) != 0;
ok(("gate_quant_fp8 act none is byte-identical to mul + quant_act_fp8, M=" +
std::to_string(m)).c_str(),
ny == 0 && nq == 0 && ns == 0 && nz > qq1.size() / 2,
"bf16 differs " + std::to_string(ny) + ", codes " + std::to_string(nq) +
", scales " + std::to_string(ns) + ", nonzero codes " +
std::to_string(nz));
/* Without out_bf16 the codes are taken over the same rounded product. */
r2 = launch_row(tq, { g, x, T(d_pq[1], RAD_F8E4M3, { m, K }),
T(d_ps[1], RAD_F32, { m, nkb }),
T(nullptr, RAD_BF16, {}) },
{ PI("M", m), PI("n", K), PI("group", 128),
PS("dtype", "bf16"), PS("act", "none") });
if (r2 != RAD_OK) {
ok(("gate_quant_fp8 act none without out_bf16, M=" +
std::to_string(m)).c_str(), false, "rc=" + std::to_string(r2));
continue;
}
st_memcpy(qq1.data(), d_pq[1], qq1.size(), hipMemcpyDeviceToHost);
st_memcpy(ss1.data(), d_ps[1], ss1.size() * 4, hipMemcpyDeviceToHost);
size_t dq2 = 0, ds2 = 0;
for (size_t i = 0; i < qq0.size(); ++i) dq2 += qq0[i] != qq1[i];
for (size_t i = 0; i < ss0.size(); ++i)
ds2 += std::memcmp(&ss0[i], &ss1[i], 4) != 0;
ok(("gate_quant_fp8 act none without out_bf16 keeps the codes, M=" +
std::to_string(m)).c_str(), dq2 == 0 && ds2 == 0,
"codes differ " + std::to_string(dq2) + ", scales " + std::to_string(ds2));
}
}
}
/* --- the same two at int8 codes, against the same products and quant_act_i8g ---
*
* With an I8 codes operand the producer writes int8 codes for an int8 trunk linear: the bf16
@@ -14416,6 +14644,90 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) {
std::to_string(live));
}
}
/* ---- past the narrow tile: `gemm_nt_q_gated_wide` runs the gated prefill tile,
* whose accumulators are the unfused prefill GEMM's, so its codes, scales and bf16
* product are the pair's over the whole prompt. 65 and 129 rows straddle one and
* two 64-row blocks. */
const RadKernelInfo* gt = find(pl, "gemm_fp8a8_tiled");
const RadKernelInfo* gw = find(pl, "gemm_fp8a8_gated_nt_wide");
for (const int64_t M : { (int64_t)65, (int64_t)129 }) {
if (!gt || !gw) {
ok("gemm_fp8a8_gated_nt_wide numeric", false, "row absent");
break;
}
void* dx = dalloc((size_t)M * K * 2);
void* dq = dalloc((size_t)M * K);
void* dqs = dalloc((size_t)M * sk * 4);
void* dy = dalloc((size_t)M * N * 2);
void* c0 = dalloc((size_t)M * nout);
void* c1 = dalloc((size_t)M * nout);
void* z0 = dalloc((size_t)M * gkb * 4);
void* z1 = dalloc((size_t)M * gkb * 4);
void* b0 = dalloc((size_t)M * nout * 2);
void* b1 = dalloc((size_t)M * nout * 2);
if (!dx || !dq || !dqs || !dy || !c1 || !z1 || !b1) {
ok("gemm_fp8a8_gated_nt_wide alloc", false, "hipMalloc failed");
continue;
}
std::vector<uint16_t> xm((size_t)M * K);
for (int64_t m = 0; m < M; ++m)
for (int64_t c = 0; c < K; ++c)
xm[(size_t)m * K + c] = xb[(size_t)((c + m * 37) % K)];
st_memcpy(dx, xm.data(), xm.size() * 2, hipMemcpyHostToDevice);
int rc = launch_row(qz, { T(dx, RAD_BF16, { M, K }), T(dq, RAD_F8E4M3, { M, K }),
T(dqs, RAD_F32, { M, sk }) },
{ PI("M", M), PI("n", K), PI("group", 128),
PS("dtype", "bf16") });
if (rc == RAD_OK)
rc = launch_row(gt, { T(dq, RAD_F8E4M3, { M, K }),
T(dqs, RAD_F32, { M, sk }),
T(d_wf, RAD_F8E4M3, { N, K }),
T(d_s, RAD_BF16, { sn, sk }),
T(dy, RAD_BF16, { M, N }) },
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 128),
PS("dtype", "fp8a8") });
if (rc == RAD_OK)
rc = launch_row(gq, { T(dy, RAD_BF16, { M, N }),
T(c0, RAD_F8E4M3, { M, nout }),
T(z0, RAD_F32, { M, gkb }),
T(b0, RAD_BF16, { M, nout }) },
{ PI("M", M), PI("n", nout), PI("group", 128),
PS("dtype", "bf16"), PS("act", "silu") });
if (rc == RAD_OK)
rc = launch_row(gw, { T(dq, RAD_F8E4M3, { M, K }),
T(dqs, RAD_F32, { M, sk }),
T(d_wf, RAD_F8E4M3, { N, K }),
T(d_s, RAD_BF16, { sn, sk }),
T(c1, RAD_F8E4M3, { M, nout }),
T(z1, RAD_F32, { M, gkb }),
T(b1, RAD_BF16, { M, nout }) },
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 128),
PS("dtype", "fp8a8"), PS("act", "silu") });
const std::string wn =
std::string("gemm_fp8a8_gated_nt_wide is byte-identical to the GEMM + "
"gated_quant_fp8, N ") + std::to_string((long long)N) +
" M " + std::to_string((long long)M);
if (rc != RAD_OK) { ok(wn.c_str(), false, "rc=" + std::to_string(rc)); continue; }
std::vector<uint8_t> q0((size_t)M * nout), q1((size_t)M * nout);
std::vector<float> s0((size_t)M * gkb), s1((size_t)M * gkb);
std::vector<uint16_t> y0((size_t)M * nout), y1((size_t)M * nout);
st_memcpy(q0.data(), c0, q0.size(), hipMemcpyDeviceToHost);
st_memcpy(q1.data(), c1, q1.size(), hipMemcpyDeviceToHost);
st_memcpy(s0.data(), z0, s0.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(s1.data(), z1, s1.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(y0.data(), b0, y0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(y1.data(), b1, y1.size() * 2, hipMemcpyDeviceToHost);
int nc = 0, nz = 0, ny = 0, live = 0;
for (size_t i = 0; i < q0.size(); ++i) nc += q0[i] != q1[i];
for (size_t i = 0; i < s0.size(); ++i)
nz += std::memcmp(&s0[i], &s1[i], 4) != 0;
for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i];
for (size_t i = 0; i < q1.size(); ++i) live += q1[i] != 0;
ok(wn.c_str(), nc == 0 && nz == 0 && ny == 0 && live > (int)q1.size() / 2,
"codes differ " + std::to_string(nc) + ", scales " + std::to_string(nz) +
", bf16 " + std::to_string(ny) + ", nonzero " + std::to_string(live));
}
}
}
}
@@ -18091,13 +18403,13 @@ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form)
}
/* 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
* 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. */
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,
"byte-identical to the two-grid form", (long long)M,
i8 ? "int8" : "E4M3");
const RadKernelInfo* r = find(pl, "hc_read_e4m3");
if (!r) { skip(nm.c_str(), "row absent"); return; }
@@ -18182,7 +18494,7 @@ static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) {
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));
ok(nm.c_str(), false, fmt("%s rc=%d", form ? "the two-grid form" : "the rule", rc));
pl.pin_hc_dec(0);
(void)hipStreamDestroy(hs);
return;
@@ -18396,12 +18708,12 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
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
/* The two-grid decode form (r4d_hc_read_pin_decode(1)) against the served one, 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");
time_now("the two-grid decode form");
pl.pin_hc_dec(0);
time_now("the launcher's rule");
}
@@ -25488,7 +25800,8 @@ struct ArThread {
* 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. */
* init returns RAD_E_DEVICE. A missing path is 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)
@@ -28563,9 +28876,10 @@ static void device_phase(const Plugin& pl) {
hipDeviceProp_t p;
if (hipGetDeviceProperties(&p, d) != hipSuccess) continue;
if (!g_case) std::printf(" device %d: %s\n", d, p.gcnArchName);
if (std::strncmp(p.gcnArchName, "gfx1201", 7) == 0) devs.push_back(d);
if (std::strncmp(p.gcnArchName, "gfx1201", 7) == 0 ||
std::strncmp(p.gcnArchName, "gfx1200", 7) == 0) devs.push_back(d);
}
if (devs.empty()) { skip("device phase", "no gfx1201 device"); return; }
if (devs.empty()) { skip("device phase", "no gfx1200/gfx1201 device"); return; }
st_set_device(devs[0]);
if (!g_case) std::printf("\ndevice smoke tests (device %d)\n", devs[0]);
@@ -28660,6 +28974,7 @@ static void device_phase(const Plugin& pl) {
attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1);
/* The 31B's prefill overlap at tp 4: sliding h256 gqa 2 (4 kv heads a rank, window 1024) and
* global h512 gqa 8 (1 kv head), a 2048-row chunk cut at 1024, first chunk and a later one. */
decode_split_law_case(pl);
kv_len_trim_case(pl);
for (const int64_t ctx : { (int64_t)2048, (int64_t)4096 }) {
attn_slice_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 4, 2048, 1024, ctx, 1024);
@@ -28771,6 +29086,7 @@ static void device_phase(const Plugin& pl) {
std::make_pair(8, 53), std::make_pair(1, 300),
std::make_pair(15, 640) })
attn_mixed_step_case(pl, *mr.g, mr.dec, mr.pre, mr.kv, c.first, c.second, 2048);
attn_decode_scratch_band_case(pl);
/* Flash-Next's QSA layers: twelve queries per KV head over 4-token pages, and six at
* four ranks, each layout's prefill (a long history and a ragged last tile), decode, and the
* widest verify (q_len 5 at gqa 12, 10 at gqa 6). */
@@ -31105,8 +31421,8 @@ 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. */
/* 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 })
for (bool i8 : { false, true }) hc_decode_forms(pl, m, i8);
}
@@ -31574,7 +31890,7 @@ static void usage(void) {
" --perfhc M [iters]: hc_read_e4m3 at Qwen3.8-Flash-Next's shape and M rows, every\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"
" then the two-grid decode form 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"