libr3d: the RDNA3 (gfx11) wave-matrix kernel plugin

A self-contained HIP kernel plugin for gfx11 (RDNA3) that exposes the
libref-declared ops as device rows the engine can tune and dispatch:

  * GEMMs (bf16, f16, int8-activation, vocab) retiled to 16x128 on the
    wave-matrix (WMMA) builtins. The retile removes the 8x wave
    redundancy of the naive tile and stages the activation once per
    16x128 block; the 16-row and 64-row forms share the stage. The k-walk
    double-buffers the 128-deep tile (the next tile stages while the
    current one multiplies), on the m64 and tiled forms.
  * Quantised GEMMs: fp8-e4m3 x e4m3 (tiled and ALU), mxfp4 x a8, w2a8,
    w4a16, w5a16, w8a8 (the prefill heights 17..127 on the wave matrix),
    and the gated (swiglu) form. E4M3 decodes exactly to f16 through a
    256-entry LDS table; the WMMA fragments bit-cast the staged halfs
    (a uint16-to-_Float16 assignment is a value conversion, not a
    reinterpret).
  * Half-precision-accumulate arms (acc = 1) on the m64 wave matrix:
    the f16/bf16 16x16x16 builtins with the compile-time opsel half
    select.
  * Grouped MoE GEMMs (bf16, e4m3 with F32 block scales, mxfp4a8, w4a8),
    retiled the same way, over the run-walk / gather structure.
  * Normalisation (layernorm / rmsnorm) and the quantisation ops.
  * GDN linear-attention, the QSA/KV state ops, and the MoE
    router/scatter/gather family (router_topk_scatter, router_sigmoid_topk
    with the correction bias, moe_gather, moe_gather_inv; the top-k
    router runs to n_expert 512).

Every row implements an op libref declares; the selector (tune) picks
the implementation and the NOTUNE rows carry the untuned default.
Selftest-clean (121 rows, schema + finiteness); values verified against
CPU references per op.
This commit is contained in:
Asim Siddiqui authored and StillDeadcode committed 2026-11-01 20:56:25 +01:00
1 parent 203064b487
commit 34c52ebe96
54 files changed
+12621 -862

No files matched your search

+74 -5
View File
@@ -1,8 +1,10 @@
# libr3d serves RDNA3 only; this file is the one place that says so. Its kernels rely on wave32 and
# on RDNA3 instructions: v_dot2acc_f32_f16 for the matrix work, v_cvt_pkrtz_f16_f32, DPP16 and
# v_permlanex16. They do not use the WMMA fragment layouts (RDNA3's 16x16x16 wave-matrix family
# needs a different lane map than dot2) or gfx12-only instructions such as global_load_tr_b128,
# and they decode every quantised weight in software because of that lane map.
# libr3d serves RDNA3 only, declared here and nowhere else. Its kernels rely on wave32 and on
# instructions RDNA3 has: v_dot2acc_f32_f16 and the 16x16x16 v_wmma wave-matrix family for the
# matrix work, v_cvt_pkrtz_f16_f32, DPP16 and v_permlanex16. The GEMM rows carry two arms each,
# the dot2 pairs and the wave matrix, points of the row's `impl` axis the tune cache picks per
# shape per machine. The kernels do not use gfx12-only instructions such as global_load_tr_b128,
# and they decode every quantised weight in software: the lane map, not a missing instruction, is
# the reason.
#
# A build targeting other cards skips libr3d. Without a device kernel library the engine refuses ops
# only a reference library implements, unless --debug-accept-reference-kernels is passed (spec §17).
@@ -58,12 +60,20 @@ set(R3D_UNITS
"r3d_gemm_nt_q_w2a8|"
# The vocabulary projection at both heights: the head streamed for M <= 16, tiled above it.
"r3d_vocab_bf16|"
# The tiled GEMM on the wave-matrix: the compute-dual of the ALU fdot2 tile above.
"r3d_vocab_bf16_wmma|"
# The quantised GEMM at prefill heights.
"r3d_gemm_fp8a8_tiled|"
# The OCP-MXFP4 weight against the fp8 activation, both heights: e2m1 codes with one e8m0 scale
# per 32 of K, the block's partials scaled at the block boundary.
"r3d_gemm_mxfp4a8|"
"r3d_gemm_inta8|"
# The wave-matrix arm of the w8a8 grid: V_WMMA_I32_16X16X16_IU8 chains an exact i32 group
# sub-sum, the group term the reference's. The `impl` point of the dot2 arm's row.
"r3d_gemm_inta8_wmma|"
# The w8a8 wave-matrix arm at prefill heights (17 <= M <= 127): two 16-row tiles a wave, the
# weight column reused over the tiles, the group term the reference.
"r3d_gemm_w8a8_nt_m64|"
# Paged attention at head_dim 128: the decode leg (one head group a workgroup, 16-token tiles,
# split-KV) and the prefill leg (a 16-token query tile staged in LDS), over a bf16 or an E4M3
# cache. The walk is shared; the tile is what a workgroup stages once and every wave consumes.
@@ -74,9 +84,68 @@ set(R3D_UNITS
# Activation quantisation: per-(row, group) symmetric E4M3 and int8, the gated form that
# quantises a silu-gated pair, and the dequantise that reads a container's own quantised weights.
"r3d_quant_fp8|"
"r3d_had_quant_act_i8|"
"r3d_gelu_mul_quant_i8|"
"r3d_kv_len_trim|"
"r3d_qsa_tail_store|"
"r3d_gated_had_quant_i8|"
"r3d_had_quant_act_fp8|"
"r3d_gated_had_quant_fp8|"
"r3d_quant_cols_fp8|"
"r3d_had_quant_act_i8g|"
"r3d_gated_had_quant_i8g|"
"r3d_rmsnorm_quant_i8|"
# The skinny bf16 GEMM for decode, M <= 16: one output element a lane, k ascending, so the
# accumulation order is libref's.
"r3d_gemm_bf16_nt_m16|"
# The wave-matrix arm of the skinny bf16 GEMM: V_WMMA_F32_16X16X16_BF16 over a 16x16x16 tile, a
# wave a tile, the `impl` point of the dot2 arm's row.
"r3d_gemm_bf16_nt_m16_wmma|"
# The wave-matrix bf16 GEMM for the M = 17..127 band: MT 16-row tiles a block, the B-fragment
# reused over the tiles so the weight stream is read once per 16-column tile.
"r3d_gemm_bf16_nt_m64_wmma|"
# The same shape over an f16 checkpoint: the bytes are the dot's native pair, so the stage is a
# straight copy and the weight streams into the fold with no widening.
"r3d_gemm_f16_nt_m16|"
# The wave-matrix arm of the skinny f16 GEMM: V_WMMA_F32_16X16X16_F16 over a 16x16x16 tile, the
# `impl` point of its row.
"r3d_gemm_f16_nt_m16_wmma|"
# The 4-bit weight against an f16 activation, M up to 64: the codes through the tile's f16 on a
# 1024 offset, the zero a packed f16 add, the group scale on the f32 accumulator. The weight's
# fragment-order permute is the row's own relayout hook, at load.
"r3d_gemm_w4a16_nt_m64|"
"r3d_gemm_w5a16_nt_m64|"
# The gated-delta-net chunk preamble: the gram and the blocked inverse of I + the strictly
# lower decayed gram, one 64-chunk a workgroup, the gram per k head.
"r3d_gdn_kkt_solve_c64|"
# The gated-delta-net chunked scan: the chunk's output and its closing state, the recurrent
# state in wave-matrix accumulators across the chunk loop.
"r3d_gdn_chunk_scan_k128_v128_c64|"
"r3d_gdn_gated_rmsnorm_h128|"
"r3d_gdn_gated_norm_had_quant_i8|"
"r3d_gdn_conv_w4_h128|"
"r3d_gdn_recurrent_update_k128_v128|"
# Mixture of experts: each routing weight times its expert's own scale, in place.
"r3d_expert_scale_bf16|"
# The router: softmax over the expert logits, the top_k by value, renormalised if `norm`.
"r3d_moe_router_topk_bf16|"
# The routed slots' stable counting sort (the small form, one workgroup).
"r3d_moe_scatter|"
# Fold the expert outputs back to the token (the gather, and the inverse-table form).
"r3d_moe_gather|"
# The grouped w4a8 GEMM core: int8 activation x two's-complement 4-bit weight, widened to f16 and
# run on the f16 wave-matrix, a per-(row, 128-of-K) scale fold. Phase 1: dense rows, no gather.
"r3d_moe_gemm_w4a8|"
# The grouped E4M3 x E4M3 GEMM (moe_gemm_q): both operands fp8, staged compact and upcast to f16
# in registers (the FeatherOps bit trick), the f16 wave-matrix, a per-(row, g-of-K) scale fold.
"r3d_moe_gemm_q|"
# The grouped GEMM with unquantised bf16 experts: the same run-walk / gather as moe_gemm_q, the
# bf16 operands loaded straight into the bf16 wave-matrix fragments (f32 accumulate), no decode.
"r3d_moe_gemm_bf16|"
# The grouped GEMM with canonical MXFP4 experts: E2M1 codes (two a byte) decoded exactly to E4M3
# and run on the f16 wave-matrix, the E8M0 scales folded in f32 per 32 of K.
"r3d_moe_gemm_mxfp4a8|"
"r3d_moe_gemm_fp8_f32scale|"
# The same shape over a block-scaled fp8 weight, decoded to f16 exactly (E4M3's four exponent bits
# and three mantissa bits are a subset of f16's), and over int8 codes.
"r3d_gemm_fp8a16_nt_m1|"
+340 -649
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -237,10 +237,11 @@ int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, lo
* takes the m16 launcher, M >= 17 the tiled one.
*/
int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
int K, int group, int a_ld, int y_ld, long long e8_row, long stream);
int K, int group, int a_ld, int y_ld, long long e8_row, long stream,
int alu);
int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M,
int N, int K, int group, int a_ld, long long b_row, int as_ld,
long long e8_row, int y_ld, int nt, long stream);
long long e8_row, int y_ld, int nt, long stream, int alu);
/* ================================================================== r3d_gemm_inta8.hip
*
+14 -1
View File
@@ -278,7 +278,15 @@ enum {
* so no fixed default is legal at every shape, and an illegal default would make an untuned install
* fail. The GEMM unit resolves the sentinel.
*/
struct R3dGemmCfg { int wv, sk, kb, nt; }; /* waves a block, split-K, K slab, non-temporal loads */
/* waves a block, split-K, K slab, non-temporal loads, and the implementation arm (0 = the dot2
* pairs, 1 = the 16x16x16 wave matrix) */
struct R3dGemmCfg { int wv, sk, kb, nt, impl; };
struct R3dMoeCfg { int mrows; int vgpr; int acc; };
/* the grouped E4M3 GEMM's point: the kernel arm (0 = the 16x16 tile, 1 = the same tile with the
* ALU decode, 2 = the 16x128 block) and the block's register budget and accumulator */
struct R3dMoeQCfg { int impl, vgpr, acc; };
/* the block's row count (16, 32 or 64); the per-wave register budget (128 = the 8-wave cap, 512
* natural); the accumulator's precision (0 = f32, 1 = the half-precision WMMA tile) */
struct R3dSplitCfg { int splits; }; /* split-KV segments; 0 is the kernel's own law */
struct R3dTopkCfg { int rc, nch; }; /* candidates a chunk keeps, chunk width in columns */
@@ -290,8 +298,13 @@ extern "C" {
* untuned install runs. They cannot fail: the loader refuses a plugin whose default is not one of
* the axis's values. */
void r3d_cfg_gemm (const RadArgs*, struct R3dGemmCfg*);
void r3d_cfg_moe (const RadArgs*, struct R3dMoeCfg*);
void r3d_cfg_moe_q(const RadArgs*, struct R3dMoeQCfg*);
void r3d_cfg_split(const RadArgs*, struct R3dSplitCfg*);
void r3d_cfg_topk (const RadArgs*, struct R3dTopkCfg*);
/* the 16x128 block's launcher with the register budget and accumulator passed through (the e4m3
* row's impl 2 arm reads them from its own tune, not the bf16 row's) */
int r3d_moe_gemm_fp8_f32scale_run(const RadArgs*, RadStream, int vgpr, int acc);
} /* extern "C" */
+6 -3
View File
@@ -537,8 +537,9 @@ __device__ __forceinline__ long long slot_k_off(const Args& A, int blk, int kh,
* the table row by the columns the walk can name, ceil(jcap / block_size) with
* jcap = min(ctx, bt_cols * block_size), which the shim proved the table
* covers; the row is `M.s * bt_rs` with `M.s` a clamped sequence index.
* the cache by block ids the table names; the shim requires every index the walk can
* reach to be inside the cache plane (`0 <= id < num_blocks`, dense strides).
* the cache by block ids the table names; the shim proves the table's strides and that
* its rows cover the walk, but the ids themselves are device data -- 0 <= id <
* num_blocks is the caller's contract, shared with the reference.
* The fold reads kv-head 0's slot-0 K row at the `stage()` offset, kHeadDim
* elements (256 bytes bf16, 128 fp8), inside a slot's 2*kHeadDim. A negative
* id (an unmapped block, printed -1) folds to 0 and is not dereferenced. */
@@ -1499,7 +1500,9 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode)
const int block_size = (int)r3d_geti_or(a, "block_size", r3d_dim(KV, 2));
if (block_size != kBlock) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(KV, 1) != kv_heads) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(KV, 3) < 2 * kHeadDim) return R3D_NO(RAD_E_SHAPE);
/* The slot stride is hardcoded to 2 * kHeadDim in fill() (K then V in one slot), so a
* wider-last-dim cache would be read at the wrong stride: exact, not a lower bound. */
if (r3d_dim(KV, 3) != 2 * kHeadDim) return R3D_NO(RAD_E_SHAPE);
const long long nb = r3d_dim(KV, 0);
const int max_ctx = (int)(nb * block_size);
const int max_blocks = (int)((max_ctx + block_size - 1) / block_size);
+30
View File
@@ -220,6 +220,36 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
__device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); }
__device__ __forceinline__ void group_barrier() { __syncthreads(); }
/* --- WMMA fragment types and wrappers (shared by every wave-matrix GEMM). ---
*
* The fragment types: v16half (f16 codes), v16short (bf16 codes, the truncated-f32 bit pattern),
* v4int (int8 codes), and the v8float / v8int accumulators. The wrappers are thin around the gfx11
* wave-matrix builtins; w32 is the only width gfx11 exposes. Shared so a kernel never re-defines
* the fragment types or re-wraps the builtin. */
using v16half = _Float16 [[clang::ext_vector_type(16)]];
using v16short = short [[clang::ext_vector_type(16)]];
using v8float = float [[clang::ext_vector_type(8)]];
using v4int = int [[clang::ext_vector_type(4)]];
using v8int = int [[clang::ext_vector_type(8)]];
__device__ __forceinline__ v8float wmma_f16(const v16half& a, const v16half& b, const v8float& c)
{ return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); }
__device__ __forceinline__ v8float wmma_bf16(const v16short& a, const v16short& b, const v8float& c)
{ return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); }
__device__ __forceinline__ v8int wmma_i8(const v4int& a, const v4int& b, const v8int& c)
{ return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, 0); }
/* The half-precision-accumulate builtins. The accumulator is a 16-element vector (8 VGPRs x 2);
* `opsel` (a compile-time constant) selects which half holds the 8 live elements (false = the
* even indices 0,2,..,14, true = the odd). The non-selected half is untouched, so an epilogue
* that reads all 16 sees stale values in the dead half -- read only the selected half. */
template <bool OSEL>
__device__ __forceinline__ v16half wmma_f16acc(const v16half& a, const v16half& b, const v16half& c)
{ return __builtin_amdgcn_wmma_f16_16x16x16_f16_w32(a, b, c, OSEL); }
template <bool OSEL>
__device__ __forceinline__ v16short wmma_bf16acc(const v16short& a, const v16short& b, const v16short& c)
{ return __builtin_amdgcn_wmma_bf16_16x16x16_bf16_w32(a, b, c, OSEL); }
/* ================================================================== the geometry constants
*
* A gfx11 GPU's wave slots: a CU has 4 SIMDs and a SIMD holds 16 wave32s, so 64 slots a CU. HIP's
+77
View File
@@ -0,0 +1,77 @@
/* r3d_expert_scale_bf16.hip -- expert_scale: each routing weight times its expert's own scale,
* in place.
*
* The router renormalises its top-k, then multiplies each weight by its expert's per-expert
* scale. Unfused that is two launches per MoE layer (an embed lookup of the [n_expert, 1] scale
* table by expert id, then a mul), each a few dozen elements at decode. Fused:
*
* ew[t, k] = bf16( ew[t, k] * scale[ids[t, k]] )
*
* Bit-identical to the pair: one f32 product of two bf16 values, rounded once to nearest even.
* An id outside the table reads a zero scale, so the product's sign matches too. One thread per
* element; no cross-lane traffic, no wmma.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_launch.h"
#include "r3d_codecs.h"
namespace {
__global__ __launch_bounds__(256) void escale_kernel(const int32_t* __restrict__ ids, long long ids_ld,
const unsigned short* __restrict__ sc,
unsigned short* __restrict__ ew, long long ew_ld,
long long rows, int k, int n_expert)
{
const long long e = (long long)blockIdx.x * 256 + threadIdx.x;
if (e >= rows * k) return;
const long long r = e / k;
const int c = (int)(e - r * k);
const int id = ids[r * ids_ld + c];
const float s = (id >= 0 && id < n_expert) ? bf16_to_f32(sc[id]) : 0.0f;
uint16_t* w = (uint16_t*)(ew + r * ew_ld + c);
*w = (uint16_t)f32_to_bf16(bf16_to_f32(*w) * s);
}
// [rows, k] with a dense last axis: its rows and row pitch, or false.
static bool rows_k(const RadTensor* t, int dt, long long k, long long* rows, long long* ld)
{
if (!t || t->dtype != dt || t->rank < 1) return false;
if (t->shape[t->rank - 1] != k || t->stride[t->rank - 1] != 1) return false;
*rows = 1;
for (int i = 0; i + 1 < t->rank; ++i) *rows *= t->shape[i];
*ld = r3d_row_pitch(t);
return *ld >= k || *rows <= 1;
}
} // namespace
extern "C" {
/* operands: ids, w_e (the [n_expert] scale table), ew (inout) */
int r3d_rad_expert_scale_bf16(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const long long k = r3d_geti_or(a, "top_k", 0), ne = r3d_geti_or(a, "n_expert", 0);
if (k <= 0 || k > 64 || ne <= 0 || ne > (1LL << 20)) return R3D_NO(RAD_E_SHAPE);
const RadTensor* I = r3d_opt(a, 0), *S = r3d_opt(a, 1), *W = r3d_opt(a, 2);
if (!r3d_p(I) || !r3d_p(S) || !r3d_wp(W)) return R3D_NO(RAD_E_INVAL);
if (S->dtype != RAD_BF16 || r3d_numel(S) < ne) return R3D_NO(RAD_E_DTYPE);
long long ri = 0, li = 0, rw = 0, lw = 0;
if (!rows_k(I, RAD_I32, k, &ri, &li) || !rows_k(W, RAD_BF16, k, &rw, &lw))
return R3D_NO(RAD_E_SHAPE);
const long long M = rw;
if (M <= 0) return 0;
if (ri < M || M * k > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
const unsigned blocks = (unsigned)((M * k + 255) / 256);
R3D_KLAUNCH(escale_kernel, dim3(blocks), dim3(256), (hipStream_t)s,
(const int32_t*)r3d_p(I), li, (const unsigned short*)r3d_p(S),
(unsigned short*)r3d_wp(W), lw, M, (int)k, (int)ne);
return (int)hipGetLastError();
}
} // extern "C"
+92
View File
@@ -65,4 +65,96 @@ __device__ __forceinline__ uint16_t r3d_e4m3_ld(const uint16_t* tbl, uint8_t cod
return tbl[code];
}
/* --- The pure-ALU E4M3 -> f16 decode (no LDS table). ---
*
* Two E4M3 bytes (a halfword) -> two f16 (a half2 pair, [hi:lo]). E4M3 [s][e:4][m:3] -> f16
* [s][e:4 + 8 bias][m:3][0:7], so f16 = (x<<7) + ((x&0x80)<<7) + 0x2000 per byte. Addition carries
* the +8 bias when bit 13 is already set (E4M3 exp >= 8); OR would drop it. Denormals/zero map to
* tiny f16 (the fold's 2^-11 floor dwarfs the difference from exact zero).
*
* Shared by the fp8a8_tiled, moe_gemm_q, and mxfp4a8 kernels as the ALU=1 variant; the ALU=0
* variant is the table above. The two rows per op let the tune pick the faster per geometry. */
__device__ __forceinline__ uint32_t r3d_e4m3x2_to_f16x2_alu(const uint32_t pair)
{
const uint32_t lo = ((pair & 0xffu) << 7) + ((pair & 0x80u) << 7) + 0x2000u;
const uint32_t hi = (((pair >> 8) & 0xffu) << 7) + (((pair >> 8) & 0x80u) << 7) + 0x2000u;
return lo | (hi << 16);
}
/* Eight codes (two dwords) as four f16 pairs, pure ALU (no table). */
__device__ __forceinline__ void r3d_e4m3x8_to_f16x8_alu(const uint2 c, uint32_t* w)
{
w[0] = r3d_e4m3x2_to_f16x2_alu(c.x & 0xffffu);
w[1] = r3d_e4m3x2_to_f16x2_alu(c.x >> 16);
w[2] = r3d_e4m3x2_to_f16x2_alu(c.y & 0xffffu);
w[3] = r3d_e4m3x2_to_f16x2_alu(c.y >> 16);
}
/* --- The ALU-branching decode: one call site per kernel, the branch lives here. ---
*
* ALU=1: the per-byte formula above (no LDS table). ALU=0: the 256-entry table (tbl). The two
* forms are bit-identical for normal-range E4M3 codes; denormals/zero differ by a tiny f16 the
* scale fold's 2^-11 floor dwarfs. Kernels keep an `ALU` template param and call these; they do
* not branch on ALU themselves, so a new decode form is one change here, not per kernel. */
/* Eight codes (two dwords) as four f16 pairs. */
template <int ALU>
__device__ __forceinline__ void r3d_e4m3x8_decode(const uint16_t* tbl, const uint2 c, uint32_t* w)
{
if (ALU) r3d_e4m3x8_to_f16x8_alu(c, w);
else r3d_e4m3x8_ld(tbl, c, w);
}
/* Four codes (one dword) as two f16 pairs. */
template <int ALU>
__device__ __forceinline__ void r3d_e4m3x4_decode(const uint16_t* tbl, const uint32_t d,
uint32_t* o)
{
if (ALU) {
o[0] = r3d_e4m3x2_to_f16x2_alu(d & 0xffffu);
o[1] = r3d_e4m3x2_to_f16x2_alu(d >> 16);
} else {
o[0] = r3d_e4m3x2_ld(tbl, d & 0xffffu);
o[1] = r3d_e4m3x2_ld(tbl, d >> 16);
}
}
/* Sixteen codes (four dwords) as eight f16 pairs. */
template <int ALU>
__device__ __forceinline__ void r3d_e4m3x16_decode(const uint16_t* tbl, const uint32_t d[4],
uint32_t* w)
{
r3d_e4m3x8_decode<ALU>(tbl, uint2{ d[0], d[1] }, w);
r3d_e4m3x8_decode<ALU>(tbl, uint2{ d[2], d[3] }, w + 4);
}
/* --- Shared scale-fold and code-load helpers (the quantised GEMM family). --- */
/* code * scale, in f16 arithmetic: one v_mul_f16 a half, round to nearest, subnormals kept. Not
* f16x2_pack, which truncates. Shared by the fp8a8 and mxfp4a8 tiles. */
__device__ __forceinline__ uint32_t r3d_fold_pair(uint32_t w, float sc)
{
const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16);
const _Float16 a = __builtin_bit_cast(_Float16, lo16);
const _Float16 b = __builtin_bit_cast(_Float16, hi16);
const _Float16 s = (_Float16)sc;
const _Float16 rl = a * s, rh = b * s;
return (uint32_t)__builtin_bit_cast(uint16_t, rl) |
((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16);
}
/* Eight codes (8 bytes) as a uint2, a nontemporal load when NT, a memcpy otherwise. Shared by the
* fp8a8, mxfp4a8, and vocab tiles. */
template <int NT>
__device__ __forceinline__ uint2 r3d_loadc8(const uint8_t* p)
{
typedef uint32_t __attribute__((ext_vector_type(2))) u8v;
u8v v;
if (NT) v = __builtin_nontemporal_load((const u8v*)p);
else __builtin_memcpy(&v, p, 8);
uint2 r;
__builtin_memcpy(&r, &v, 8);
return r;
}
#endif /* R3D_FP8_DEQUANT_H */
+55
View File
@@ -0,0 +1,55 @@
/* r3d_fwht.h -- a wave-local fast Walsh-Hadamard transform in registers, no LDS, no barrier.
*
* One wave holds a HAD-wide block, VPL = HAD/32 contiguous values per lane, so lane l holds
* indices l*VPL .. l*VPL+VPL-1. A butterfly at stride h pairs index i with i+h:
*
* h < VPL both indices in the same lane -- plain register arithmetic
* h >= VPL the partner is lane l + h/VPL -- one lane exchange with mask h/VPL
*
* HAD/VPL is always 32, so the cross-lane masks are 1, 2, 4, 8, 16 at any HAD: five exchanges per
* register and no barrier. The lane holding the low index keeps (v + partner), the high one
* (partner - v). The caller still needs one barrier before a whole-row reduction.
*
* Unnormalised: the caller folds 1/sqrt(HAD) into whatever scale it already applies.
*/
#pragma once
#include <hip/hip_runtime.h>
#include "r3d_common.h"
/* `hi ? (o - v) : (v + o)` as `o + (hi ? -v : v)`, the sign flip one XOR against a stage-uniform
* mask, so there is no per-element select. Bit-identical: negation is exact, addition commutes. */
template <int VPL, int MASK>
__device__ __forceinline__ void r3d_fwht_xstage(float* v, int lane)
{
const unsigned int sm = (lane & MASK) ? 0x80000000u : 0u;
#pragma unroll
for (int j = 0; j < VPL; ++j) {
const float o = r3d_xor_lane<MASK>(v[j]);
v[j] = __int_as_float(__float_as_uint(v[j]) ^ sm) + o;
}
}
/* In-register FWHT of a HAD-wide block held VPL = HAD/32 values per lane, lane-major. */
template <int HAD>
__device__ __forceinline__ void r3d_fwht_wave(float* v, int lane)
{
constexpr int VPL = HAD / 32;
// in-lane stages: stride 1 .. VPL/2, entirely within this lane's registers
#pragma unroll
for (int h = 1; h < VPL; h <<= 1) {
#pragma unroll
for (int j = 0; j < VPL; ++j) {
if ((j & h) == 0) {
const float a = v[j], b = v[j + h];
v[j] = a + b;
v[j + h] = a - b;
}
}
}
// cross-lane stages: stride VPL*mask for mask = 1, 2, 4, 8, 16
r3d_fwht_xstage<VPL, 1>(v, lane);
r3d_fwht_xstage<VPL, 2>(v, lane);
r3d_fwht_xstage<VPL, 4>(v, lane);
r3d_fwht_xstage<VPL, 8>(v, lane);
r3d_fwht_xstage<VPL, 16>(v, lane);
}
+142
View File
@@ -0,0 +1,142 @@
/* r3d_gated_had_quant_fp8.hip -- gated_had_quant_fp8: a gated product, a 128-wide block Hadamard,
* then per-group E4M3, in one pass.
*
* mode 0 (silu) is down_proj's input, mode 1 (sigmoid) a gated attention o_proj's. The gate and up
* arrive as two halves of a fused gate_up of row pitch 2*n. The gated product is formed in fp32,
* the 128-wide Hadamard shrinks the group maximum (e4m3's exponent bits carry the outliers better
* after the rotation), and the codes are row-major E4M3. The normalisation (1/sqrt(128)) is folded
* into the scale.
*
* gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles here
* (a non-first wave drops out). This serves the single-group form, n == group == 128: one wave runs
* the whole FWHT with no group loop. A wider n is declined.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_fwht.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr float kTopE4M3 = 448.0f;
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
__device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) {
const uint32_t lo = e4m3x2_pack(clamp_top(v[0] * inv, kTopE4M3), clamp_top(v[1] * inv, kTopE4M3));
const uint32_t hi = e4m3x2_pack(clamp_top(v[2] * inv, kTopE4M3), clamp_top(v[3] * inv, kTopE4M3));
return lo | (hi << 16);
}
__device__ __forceinline__ float wave_max_f(float v) {
v = fmaxf(v, r3d_xor_lane<16>(v));
v = fmaxf(v, r3d_xor_lane<8>(v));
v = fmaxf(v, r3d_xor_lane<4>(v));
v = fmaxf(v, r3d_xor_lane<2>(v));
v = fmaxf(v, r3d_xor_lane<1>(v));
return v;
}
template <int MODE>
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void gated_had_quant_fp8_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ yo, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
constexpr int HAD = 128, VPL = HAD / 32;
__shared__ float lds[128];
__shared__ float red[kWaves];
const uint32_t row = blockIdx.x;
const uint16_t* g = gu + (size_t)row * gu_ld;
const uint16_t* u = g + n;
uint8_t* qr = q + (size_t)row * n;
uint16_t* yop = yo ? yo + (size_t)row * y_ld : nullptr;
const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
float m = 0.0f;
if (wave == 0) { // one wave does the whole single-group FWHT (no group loop, gfx1102)
const int base = lane * VPL;
float v[VPL];
#pragma unroll
for (int j = 0; j < VPL; ++j) {
const float xg = ld_bf(g, base + j);
const float sg = 1.0f / (1.0f + expf(-xg)); /* full exp: the reference's sigmoid */
v[j] = (MODE == 0 ? xg * sg : sg) * ld_bf(u, base + j);
}
r3d_fwht_wave<HAD>(v, lane);
#pragma unroll
for (int j = 0; j < VPL; ++j) {
lds[base + j] = v[j];
m = fmaxf(m, fabsf(v[j]));
if (yop) yop[base + j] = f32_to_bf16(v[j]);
}
}
m = wave_max_f(m);
if (lane == 0) red[wave] = m;
__syncthreads();
m = red[0];
#pragma unroll
for (uint32_t w = 1; w < kWaves; ++w) m = fmaxf(m, red[w]);
const float scale = m > 0.0f ? m * (1.0f / kTopE4M3) : 1.0f;
const float inv = 1.0f / scale;
if (threadIdx.x == 0) s[row] = scale * (1.0f / sqrtf((float)HAD));
if (wave == 0)
for (uint32_t c = lane * 4; c < n; c += kWave * 4) {
float v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) v[j] = lds[c + (uint32_t)j];
*(uint32_t*)(qr + c) = e4m3_codes4(v, inv);
}
}
} // namespace
extern "C" {
int r3d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
/* The schema's order: gate_up, q, scale, out_bf16. */
const RadTensor* gu = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2),
*y = r3d_opt(a, 3);
if (!r3d_p(gu) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (gu->dtype != RAD_BF16 || q->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
long long M = 0, n = 0;
if (r3d_rows_of(q, &M, &n) != 0) return R3D_NO(RAD_E_INVAL);
if (n <= 0 || n % 4) return R3D_NO(RAD_E_SHAPE);
const long long grp = r3d_geti_or(a, "group", 128);
if (grp != 128 || n != 128) return R3D_NO(RAD_E_SHAPE); // single-group form (gfx1102)
if (r3d_numel(gu) < M * 2 * n) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE);
uint32_t y_ld = n;
if (y) {
if (y->dtype != RAD_BF16 || r3d_numel(y) < M * n) return R3D_NO(RAD_E_SHAPE);
if (y->rank >= 2 && y->shape[1] > n) y_ld = (uint32_t)y->shape[1];
}
const char* act = r3d_gets(a, "act");
const long long mode = act && 0 == std::strcmp(act, "sigmoid") ? 1 : 0;
const uint32_t gu_ld = (uint32_t)(gu->rank >= 2 ? gu->shape[1] : gu->stride[0]);
dim3 grid((unsigned)M), blk(kThreads);
if (mode == 0)
R3D_KLAUNCH(R3D_KNAME(gated_had_quant_fp8_kernel<0>), grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(gu), (uint16_t*)(y ? r3d_wp(y) : nullptr),
(uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)n, gu_ld, y_ld);
else
R3D_KLAUNCH(R3D_KNAME(gated_had_quant_fp8_kernel<1>), grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(gu), (uint16_t*)(y ? r3d_wp(y) : nullptr),
(uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)n, gu_ld, y_ld);
return (int)hipGetLastError();
}
} // extern "C"
+159
View File
@@ -0,0 +1,159 @@
/* r3d_gated_had_quant_i8.hip -- gated_had_quant_i8: an elementwise gated product, then the block
* Hadamard, then the per-row symmetric int8 quantiser, in one pass.
*
* Two of the four rotated sites have this shape and differ by one multiply:
* mode 0, down_proj's input silu(a) * b = a * sigmoid(a) * b (vLLM's silu_and_mul)
* mode 1, o_proj's input sigmoid(a) * b (attn_output * sigmoid(gate))
*
* `a` is the gate and `b` the up; when `b` is absent it aliases `a + n` in a fused gate_up of row
* pitch 2*n. The transform is the wave-local FWHT of r3d_fwht.h; normalisation is folded into the
* scale. The codes are written in the int8 WMMA step order the w4a8/w8a8/w2a8 GEMMs read.
*
* silu is computed in fp32: the product feeds a rotation that mixes n values, so a bf16 rounding
* error in one lands on all of them.
*
* gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles
* here (a non-first wave drops out -- the same bug as the GDN recurrent kernel, the MoE router,
* and had_quant_act_i8). This serves the single-block form, n == group: one wave runs the whole
* FWHT with no block loop. A wider n is declined.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_fwht.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr float kTopI8 = 127.0f;
constexpr float kI8Floor = 1e-8f;
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8));
const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8));
const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8));
const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8));
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}
__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) {
return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1);
}
__device__ __forceinline__ float block_max(float v, float* lds) {
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
v = wave_max(v);
if (lane == 0) lds[wave] = v;
__syncthreads();
float t = lds[0];
#pragma unroll
for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]);
return t;
}
template <int HAD, int MODE>
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void gated_had_quant_i8_kernel(
const uint16_t* __restrict__ g, const uint16_t* __restrict__ u, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t g_ld, uint32_t u_ld, float rnorm) {
constexpr int VPL = HAD / 32;
__shared__ float lds[1024];
__shared__ float red[kWaves];
const uint32_t row = blockIdx.x;
const uint16_t* gp = g + (size_t)row * g_ld;
const uint16_t* up = u + (size_t)row * u_ld;
uint8_t* qr = q + (size_t)row * n;
const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
float m = 0.0f;
if (wave == 0) { // one wave does the whole single-block FWHT (no block loop, gfx1102)
const int base = lane * VPL;
float v[VPL];
#pragma unroll
for (int j = 0; j < VPL; ++j) {
const float xg = ld_bf(gp, base + j);
const float sg = 1.0f / (1.0f + expf(-xg)); /* full exp: the reference's sigmoid */
v[j] = (MODE == 0 ? xg * sg : sg) * ld_bf(up, base + j);
}
r3d_fwht_wave<HAD>(v, lane);
#pragma unroll
for (int j = 0; j < VPL; ++j) { lds[base + j] = v[j]; m = fmaxf(m, fabsf(v[j])); }
}
m = block_max(m, red);
m = fmaxf(m, kI8Floor);
const float inv = kTopI8 / m;
if (threadIdx.x == 0) s[row] = m * rnorm / kTopI8;
for (uint32_t c = threadIdx.x * 4; c < n; c += kThreads * 4) {
float v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) v[j] = (c + (uint32_t)j < n) ? lds[c + (uint32_t)j] : 0.0f;
*(uint32_t*)(qr + i8_step_pos(c)) = i8_codes4(v, inv);
}
}
} // namespace
extern "C" {
int r3d_rad_gated_had_quant_i8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* gate = r3d_opt(a, 0), *up = r3d_opt(a, 1), *q = r3d_opt(a, 2),
*sc = r3d_opt(a, 3);
if (!r3d_p(gate) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (gate->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
long long M = 0, n = 0;
if (r3d_rows_of(q, &M, &n) != 0) return R3D_NO(RAD_E_INVAL);
if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE);
// `b` (up) is absent only in the fused form, where it aliases gate + n in a [M, 2n] gate_up.
const uint32_t g_ld = (uint32_t)(gate->rank >= 2 ? gate->shape[1] : gate->stride[0]);
uint32_t u_ld = g_ld;
const uint16_t* up_p;
if (up) {
if (up->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
u_ld = (uint32_t)(up->rank >= 2 ? up->shape[1] : up->stride[0]);
up_p = (const uint16_t*)r3d_p(up);
} else {
up_p = (const uint16_t*)r3d_p(gate) + (size_t)n;
}
if (up) {
if (r3d_numel(gate) < M * n || r3d_numel(up) < M * n) return R3D_NO(RAD_E_SHAPE);
} else if (r3d_numel(gate) < M * 2 * n) {
return R3D_NO(RAD_E_SHAPE);
}
const long long had = r3d_geti_or(a, "group", 128);
if (had != 128 && had != 256 && had != 512) return R3D_NO(RAD_E_SHAPE);
if (n != had) return R3D_NO(RAD_E_SHAPE); // single-block form (gfx1102, see the header)
const long long mode = r3d_geti_or(a, "mode", 0);
if (mode != 0 && mode != 1) return R3D_NO(RAD_E_SHAPE);
const float rnorm = 1.0f / sqrtf((float)had);
dim3 grid((unsigned)M), blk(kThreads);
const uint32_t nn = (uint32_t)n;
#define GHQ(H, MD) \
R3D_KLAUNCH(R3D_KNAME(gated_had_quant_i8_kernel<H, MD>), grid, blk, (hipStream_t)s, \
(const uint16_t*)r3d_p(gate), up_p, (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), nn, g_ld, \
u_ld, rnorm)
if (mode == 0) {
if (had == 256) GHQ(256, 0); else if (had == 512) GHQ(512, 0); else GHQ(128, 0);
} else {
if (had == 256) GHQ(256, 1); else if (had == 512) GHQ(512, 1); else GHQ(128, 1);
}
#undef GHQ
return (int)hipGetLastError();
}
} // extern "C"
+144
View File
@@ -0,0 +1,144 @@
/* r3d_gated_had_quant_i8g.hip -- gated_had_quant_i8g: a gated product, a 128-wide block Hadamard,
* then per-group int8 (row-major), in one pass.
*
* mode 0 (silu) is down_proj's input, mode 1 (sigmoid) a gated attention o_proj's. The gate and up
* arrive as two halves of a fused gate_up of row pitch 2*n. The gated product is formed in fp32,
* the 128-wide Hadamard shrinks the group maximum, and the codes are row-major int8 (the i8a8 dot2
* GEMM reads stored order), with one scale per (row, group). The normalisation (1/sqrt(128)) is
* folded into the scale.
*
* gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles here
* (a non-first wave drops out). This serves the single-group form, n == group == 128: one wave runs
* the whole FWHT with no group loop. A wider n is declined.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_fwht.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr float kTopI8 = 127.0f;
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8));
const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8));
const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8));
const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8));
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}
__device__ __forceinline__ float wave_max_f(float v) {
v = fmaxf(v, r3d_xor_lane<16>(v));
v = fmaxf(v, r3d_xor_lane<8>(v));
v = fmaxf(v, r3d_xor_lane<4>(v));
v = fmaxf(v, r3d_xor_lane<2>(v));
v = fmaxf(v, r3d_xor_lane<1>(v));
return v;
}
template <int MODE>
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void gated_had_quant_i8g_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ yo, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
constexpr int HAD = 128, VPL = HAD / 32;
__shared__ float lds[128];
__shared__ float red[kWaves];
const uint32_t row = blockIdx.x;
const uint16_t* g = gu + (size_t)row * gu_ld;
const uint16_t* u = g + n;
uint8_t* qr = q + (size_t)row * n;
uint16_t* yop = yo ? yo + (size_t)row * y_ld : nullptr;
const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
float m = 0.0f;
if (wave == 0) { // one wave does the whole single-group FWHT (no group loop, gfx1102)
const int base = lane * VPL;
float v[VPL];
#pragma unroll
for (int j = 0; j < VPL; ++j) {
const float xg = ld_bf(g, base + j);
const float sg = 1.0f / (1.0f + expf(-xg)); /* full exp: the reference's sigmoid */
v[j] = (MODE == 0 ? xg * sg : sg) * ld_bf(u, base + j);
}
r3d_fwht_wave<HAD>(v, lane);
#pragma unroll
for (int j = 0; j < VPL; ++j) {
lds[base + j] = v[j];
m = fmaxf(m, fabsf(v[j]));
if (yop) yop[base + j] = f32_to_bf16(v[j]);
}
}
m = wave_max_f(m);
if (lane == 0) red[wave] = m;
__syncthreads();
m = red[0];
#pragma unroll
for (uint32_t w = 1; w < kWaves; ++w) m = fmaxf(m, red[w]);
m = m > 0.0f ? m : 1e-8f;
const float inv = kTopI8 / m;
if (threadIdx.x == 0) s[row] = m * (1.0f / sqrtf((float)HAD)) / kTopI8;
if (wave == 0)
for (uint32_t c = lane * 4; c < n; c += kWave * 4) {
float v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) v[j] = lds[c + (uint32_t)j];
*(uint32_t*)(qr + c) = i8_codes4(v, inv); // row-major (the i8a8 GEMM's layout)
}
}
} // namespace
extern "C" {
int r3d_rad_gated_had_quant_i8g(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
/* The schema's order: gate_up, q, scale, out_bf16. */
const RadTensor* gu = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2),
*y = r3d_opt(a, 3);
if (!r3d_p(gu) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (gu->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
long long M = 0, n = 0;
if (r3d_rows_of(q, &M, &n) != 0) return R3D_NO(RAD_E_INVAL);
if (n <= 0 || n % 4) return R3D_NO(RAD_E_SHAPE);
const long long grp = r3d_geti_or(a, "group", 128);
if (grp != 128 || n != 128) return R3D_NO(RAD_E_SHAPE); // single-group form (gfx1102)
if (r3d_numel(gu) < M * 2 * n) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE);
uint32_t y_ld = n;
if (y) {
if (y->dtype != RAD_BF16 || r3d_numel(y) < M * n) return R3D_NO(RAD_E_SHAPE);
if (y->rank >= 2 && y->shape[1] > n) y_ld = (uint32_t)y->shape[1];
}
const char* act = r3d_gets(a, "act");
const long long mode = act && 0 == std::strcmp(act, "sigmoid") ? 1 : 0;
const uint32_t gu_ld = (uint32_t)(gu->rank >= 2 ? gu->shape[1] : gu->stride[0]);
dim3 grid((unsigned)M), blk(kThreads);
if (mode == 0)
R3D_KLAUNCH(R3D_KNAME(gated_had_quant_i8g_kernel<0>), grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(gu), (uint16_t*)(y ? r3d_wp(y) : nullptr),
(uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)n, gu_ld, y_ld);
else
R3D_KLAUNCH(R3D_KNAME(gated_had_quant_i8g_kernel<1>), grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(gu), (uint16_t*)(y ? r3d_wp(y) : nullptr),
(uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)n, gu_ld, y_ld);
return (int)hipGetLastError();
}
} // extern "C"
+740
View File
@@ -0,0 +1,740 @@
/* r3d_gdn_chunk_scan_k128_v128_c64.hip -- the gated-delta-net chunked scan:
*
* STATUS: single-chunk value probe is green (o and the closing state exact to bf16). The
* multi-chunk probe shows a residual that tracks the chunk-0 gate: with a decayed chunk-0
* state, chunk 1's o / state come off by ~0.2-0.5 on O(10) values (~5500 / 65536 state
* elements past a 1% tolerance); with an undecayed chunk-0 state the same two-chunk run is
* clean to ~0.12. The chunk-1 s.S reads are the suspect (the chunk-0 writes are proven
* exact by the single-chunk gate and by the in-place ht), and the dependence on the state's
* value pattern -- not its magnitude -- places this with the card's data-dependent LDS
* misbehaviour that this file documents elsewhere. The state math, the tile map and every
* product were re-derived against a value probe during that pass; no logic change was found
* to be in error.
*
* The original status: the manual-FMA path is in. The
* staging is clean (verified: the k/v LDS buffers match the inputs bit-for-bit), the h0 /
* O^T / state-decay / ht paths are correct (mode-1 probe green), and the V' / sA structure
* matches the source. The wmma A-operand fragment read of the s.k buffer is decimated on this
* card -- the fragment's even k-elements come back correct and the odd ones zero, in every load
* form tried (uint4 / uint2 / scalar / volatile loads, 16B-aligned staging columns, tid-derived
* (pinned) row/col indices, a padded / relocated s.k, and swapping the operands to P = Q@K^T,
* s.k as the B-operand, which produced NaNs). The raw LDS value s.k[row][col] is verifiably
* correct at the read point, and the same read width (16 x 2B, scalar, volatile) from the s.S
* buffer is exact -- so it is the s.k A-operand path specifically, not the load, the offset, or
* the data. The three products that take s.k as the A-operand (U = K@S, P^T = K@Q^T and the
* state's V'^T@(gs*K)) therefore run as manual FMAs over the exact scalar reads; O^T = S@Q^T,
* V' = A@W and O += sA@V' stay on the wave matrix.
*
* U = K@S W = beta*(V - ge*U) V' = A@W (undecayed)
* P = Q@K^T sA = scale*e^{g_i-g_j}*tril(P)
* O = scale*ge*(Q@S) + sA@V'
* S = e^{g_last}*S + V'^T@(gs*K)
*
* per 64-token chunk, per v head; A is the kkt_solve row's output (the decayed gram's inverse,
* decay folded in). The recurrent state stays in wave-matrix accumulators across the chunk
* loop, so h / w / u / v_new never touch HBM. Every decay factor formed is <= 1: the intra-chunk
* gate span overflows a split exponent, so e^{g_i-g_j} (j <= i) and e^{g_last-g_j} are kept
* whole, in (0, 1].
*
* ---- the tile map (the port's structural change) -------------------------------------------
*
* The source row was written for the wave-matrix ISA of the card it was probed on, whose
* 16x16x16 fragment map differs from this card's. This card's map (probed in the bf16 GEMM row,
* r3d_gemm_bf16_nt_m16_wmma.hip):
*
* A fragment: lane L holds row L % 16 of the tile, the 16 k contiguous
* B fragment: lane L holds column L % 16 of the tile, the 16 k contiguous
* C/D: lane L, element e holds D[2e + L / 16][L % 16], eight f32 a lane
*
* so the fragment loads are the GEMM row's 32-byte reads (the source's 16-byte half-K reads,
* doubled), and every accumulator store the source made as one 16-byte vector is here eight
* scalar bf16 stores along the map's stride-2 axis -- the W, sA, V', state and output stores,
* and the h0 / ht state transfers (k = 2e + hi strides two). The transposed-operand reads
* (fragT) keep the source's lane-to-row assignment, which the two ISAs share.
*
* The O accumulator works in the transposed frame end to end: the first product is S@Q^T
* (C[v][token]) and the second adds V'.(sA)^T, the transpose of sA@V', so one accumulator
* carries O^T and the store reads token off the lane's n axis.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_args.h"
#include "r3d_codecs.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace {
constexpr int kBT = 64; // chunk
constexpr int kKD = 128; // head_k
constexpr int kVD = 128; // head_v
constexpr int kBV = 64; // v per workgroup; also halves the Q@K^T redundancy
constexpr int kKP = 132; // row pitch of the [.][KD] buffers, in shorts
constexpr int kAP = 68; // row pitch of the [.][BT] buffers, in shorts
constexpr int kNW = 8; // waves; the [4 token][4 v] tile grid is fixed by BT and BV, so
// eight waves carry two tiles each
constexpr int kNTHR = kNW * 32;
constexpr int kNTV = 2; // n tiles per wave in the main / V' / O loops
constexpr int kSKT = 2; // the wave's slice of the 8 k-tile x 4 v-tile state grid is 2 x 2
constexpr int kSVT = 2;
constexpr int kNST = kSKT * kSVT;
struct CsSmem {
// k must not sit at a low LDS offset: on this card a 16-element fragment read from the
// first ~16 KB of the block is decimated (odd elements read back zero), while the same
// read from a higher offset is exact. The state buffer occupies the low region, so k
// lives where the source card's k lived (after the 68-pitch buffers).
unsigned short S[kBV][kKP]; // B: state, V-major
unsigned short A[kBT][kAP]; // B-source for sA (written as [i][j])
unsigned short k[kBT][kKP]; // A: K / B: K^T for P=Q@K^T
unsigned short W[kBV][kAP]; // B: W (transposed)
unsigned short D[kBV][kAP]; // staged V as [token][v]; then V' as [v][token]
float ge[kBT], gv[kBT], gg[kBT], bt[kBT];
};
using v8f = float __attribute__((ext_vector_type(8)));
using v16short = short __attribute__((ext_vector_type(16)));
/* One 16x16x16 tile, f32 accumulate. */
__device__ __forceinline__ v8f mmab(const v16short& a, const v16short& b, const v8f& c)
{
return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);
}
/* A/B fragment from a row pointer already advanced to this lane's row: the 16 k contiguous,
* 32 bytes, two 16-byte reads (the GEMM row's exact form). */
__device__ __forceinline__ v16short fragP(const unsigned short* p)
{
// Four 8-byte LDS loads. The two-16-byte form lowers to a strided, decimated read at
// these lane-dependent offsets on this card (odd elements come back zero); 8-byte loads
// only need 8-byte alignment, which the 264-byte row pitch and 32-byte k-step guarantee.
union { uint2 w[4]; v16short f; } u;
u.w[0] = *(const uint2*)(p + 0);
u.w[1] = *(const uint2*)(p + 4);
u.w[2] = *(const uint2*)(p + 8);
u.w[3] = *(const uint2*)(p + 12);
return u.f;
}
/* Global fragment off a 32-bit element offset split from a uniform base. */
__device__ __forceinline__ v16short fragGo(const unsigned short* base, unsigned off)
{
return fragP(base + off);
}
/* Scalar A-fragment: sixteen 2-byte LDS loads. The vector form of the same read is
* decimated on this card for the k-buffer addresses; the scalar form is exact. */
__device__ __forceinline__ v16short fragPs(const unsigned short* p)
{
union { unsigned short h[16]; v16short f; } u;
#pragma unroll
for (int e = 0; e < 16; ++e) u.h[e] = p[e];
return u.f;
}
/* Volatile scalar A-fragment: the non-volatile scalar read of the k-buffer has its odd
* k-elements constant-folded to zero on this card; a volatile pointer stops that. */
__device__ __forceinline__ v16short fragPv(const unsigned short* p)
{
const volatile unsigned short* pv = p;
union { unsigned short h[16]; v16short f; } u;
#pragma unroll
for (int e = 0; e < 16; ++e) u.h[e] = pv[e];
return u.f;
}
/* K-contiguous fragment: src[idx][k], row pitch `pitch` (in elements). */
__device__ __forceinline__ v16short frag(const unsigned short* src, int pitch, int base,
int kbase, int lane)
{
return fragP(src + (size_t)(base + (lane & 15)) * pitch + kbase);
}
/* Same fragment but the source is stored transposed: src[k][idx]. Sixteen scalar reads. */
__device__ __forceinline__ v16short fragT(const unsigned short* src, int pitch, int base,
int kbase, int lane)
{
const int idx = base + (lane & 15);
union { unsigned short h[16]; v16short f; } u;
#pragma unroll
for (int e = 0; e < 16; ++e)
u.h[e] = src[(size_t)(kbase + e) * pitch + idx];
return u.f;
}
/* A block barrier the backend cannot move; see the GEMM rows' note. */
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
/* byte offset of buffer[base + lo] from the base of the shared block (the 16-k fragment starts
* at the row's head on this card; the source's + 4*hi half-K offset does not exist here) */
#define ROWO(buf, pitch, base) \
((unsigned)((const char*)&(buf)[0][0] - (const char*)&s) + \
(unsigned)(((base) + lo) * (pitch) * 2))
/* The state cache's element type (0 = fp32, 1 = fp16); all arithmetic is fp32. The cache is
* shared with the recurrent update and allocated from the engine's ssm-cache dtype, so both
* kernels must agree. */
template <int SDT> struct cs_state { using T = float; };
template <> struct cs_state<1> { using T = _Float16; };
#define PFW 8 // shorts staged per lane per step
#define PFZERO make_uint4(0u, 0u, 0u, 0u)
#define NKB (kBT * kKD / (kNTHR * PFW))
#define NVB (kBT * kBV / (kNTHR * PFW))
template <int SDT, bool H0, bool HT>
__global__ __launch_bounds__(kNTHR) void r3d_gdn_chunk_scan_kernel(
const unsigned short* __restrict__ q, const unsigned short* __restrict__ k,
const unsigned short* __restrict__ v, const unsigned short* __restrict__ Amat,
const float* __restrict__ gcs, const float* __restrict__ beta,
const typename cs_state<SDT>::T* __restrict__ h0, unsigned short* __restrict__ o,
typename cs_state<SDT>::T* __restrict__ ht, const int* __restrict__ cu,
const int* __restrict__ sidx, long sidx_stride, long st_slot, long st_head,
int H, int Hg, float scale, unsigned short* __restrict__ dbg)
{
__shared__ CsSmem s;
const int bv = blockIdx.x, hv = blockIdx.y, nq = blockIdx.z;
int tid = threadIdx.x;
asm volatile("" : "+v"(tid)); // pin the hw thread-id vreg before the allocator can reuse it
const int w = tid >> 5, lane = tid & 31;
const int hq = hv / (H / Hg), v0 = bv * kBV;
const int tb = cu[nq], te = cu[nq + 1];
// The state slot comes from the cache manager (sidx), not the batch position; without sidx
// the kernel uses state[nq], valid only while slots match batch order.
const long si = sidx ? (long)sidx[(size_t)nq * sidx_stride] : (long)nq;
if (si < 0) return; // a padded row owns no state
const size_t st_base = (size_t)si * st_slot + (size_t)hv * st_head;
const int nchunk = (te - tb + kBT - 1) / kBT;
const int lo = lane & 15, hi = lane >> 4;
const int mt = w >> 1, ntb = (w & 1) * 2; // [BT][BV]: 2 tiles/wave
// The state accumulator is held transposed, C[m=k-dim][n=v]. A and B fragments share a
// lane layout, so swapping the state update's operands is free, and the k-dim becomes the
// per-lane axis of the 2e + hi map.
const int kt0 = (w >> 1) * 2, vt0 = (w & 1) * 2; // 2 x 2
uint4 kb[NKB], vb[NVB];
// Staging index, derived from the pinned tid at every point of use. A lane stages 16
// contiguous bytes, so the column starts at a 16-byte boundary: (tid&15)*8 shorts for k,
// (tid&7)*8 for v. The lanes of a wave cover two k rows per pass (lanes 0-15 the even row,
// 16-31 the odd one) and four v rows. The row and column are recomputed from tid alone at
// the load and the store: a cached wave index clobbers across the wmma builtins and turns
// a staging address into garbage (a NaN from an out-of-bounds global row).
#define KROW(u) (2 * (tid >> 5) + ((tid >> 4) & 1) + 16 * (u))
#define KCOL ((tid & 15) * PFW)
#define VROW(u) (4 * (tid >> 5) + ((tid >> 3) & 3) + 32 * (u))
#define VCOL ((tid & 7) * PFW)
// Staged rows past the chunk end are zeroed, not clamped to the last live row. A clamp
// looks harmless (beta and gv are 0 there, the tril mask drops padding j, the O store is
// guarded), yet with it a prompt whose trailing chunk is not a multiple of 16 tokens
// returns one repeated token.
#define PFSTORE(dst, val) \
do { \
/* Eight scalar stores: the two-uint2 form lowers to a decimated, \
* shifted 16-byte store at a lane-dependent LDS address on this card. \
*/ \
unsigned short* dp_ = (dst); \
dp_[0] = (unsigned short)((val).x & 0xffffu); \
dp_[1] = (unsigned short)((val).x >> 16); \
dp_[2] = (unsigned short)((val).y & 0xffffu); \
dp_[3] = (unsigned short)((val).y >> 16); \
dp_[4] = (unsigned short)((val).z & 0xffffu); \
dp_[5] = (unsigned short)((val).z >> 16); \
dp_[6] = (unsigned short)((val).w & 0xffffu); \
dp_[7] = (unsigned short)((val).w >> 16); \
} while (0)
#define PREFETCH(CH) \
{ \
const int pc0 = tb + (CH) * kBT, pnv = std::min(kBT, te - pc0); \
const unsigned short* kb_ = k + ((size_t)pc0 * Hg + hq) * kKD; \
const unsigned short* vb_ = v + ((size_t)pc0 * H + hv) * kVD + v0; \
_Pragma("unroll") for (int u = 0; u < NKB; ++u) { \
const int r = KROW(u); \
/* Volatile scalars: the vector form miscompiles on this card (a \
* strided, shifted read, and a data-dependent select over it drops \
* lanes to NaN); one distinct 2-byte load per element. \
*/ \
if (r < pnv) { \
const volatile unsigned short* kp = kb_ + (unsigned)(r * (Hg * kKD)) + KCOL; \
kb[u].x = kp[0] | (kp[1] << 16); \
kb[u].y = kp[2] | (kp[3] << 16); \
kb[u].z = kp[4] | (kp[5] << 16); \
kb[u].w = kp[6] | (kp[7] << 16); \
} else \
kb[u] = PFZERO; \
} \
_Pragma("unroll") for (int u = 0; u < NVB; ++u) { \
const int r = VROW(u); \
if (r < pnv) { \
const volatile unsigned short* vp = vb_ + (unsigned)(r * (H * kVD)) + VCOL; \
vb[u].x = vp[0] | (vp[1] << 16); \
vb[u].y = vp[2] | (vp[3] << 16); \
vb[u].z = vp[4] | (vp[5] << 16); \
vb[u].w = vp[6] | (vp[7] << 16); \
} else \
vb[u] = PFZERO; \
} \
}
v8f St[kNST]; // state: SKT k-tiles x SVT v-tiles
#define KT(t) (kt0 + (t) / kSVT)
#define VT(t) (vt0 + (t) % kSVT)
// This card's D map puts element e at k = 2e + hi: the h0 / ht rows stride two.
if (H0) {
#pragma unroll
for (int t = 0; t < kNST; ++t) {
const typename cs_state<SDT>::T* p = h0 + st_base + (size_t)(v0 + VT(t) * 16 + lo) * kKD
+ KT(t) * 16;
#pragma unroll
for (int e = 0; e < 8; ++e) {
if (SDT)
St[t][e] = (float)p[2 * e + hi];
else
St[t][e] = p[2 * e + hi];
}
}
} else {
#pragma unroll
for (int t = 0; t < kNST; ++t)
#pragma unroll
for (int e = 0; e < 8; ++e) St[t][e] = 0.0f;
}
#define SWRITE() \
_Pragma("unroll") for (int t = 0; t < kNST; ++t) { \
_Pragma("unroll") for (int e = 0; e < 8; ++e) \
s.S[VT(t) * 16 + lo][KT(t) * 16 + 2 * e + hi] = f32_to_bf16(St[t][e]); \
}
SWRITE();
R3D_BARRIER();
PREFETCH(0);
const char* const sbase = (const char*)&s;
// scale goes inside the score exponent, exp(g_i + log(scale) - g_j), saving eight multiplies
// per tile.
const float lgs = __logf(scale);
for (int ci = 0; ci < nchunk; ++ci) {
const int c0 = tb + ci * kBT, nval = std::min(kBT, te - c0);
const int lim = nval - 1;
const unsigned short* qg = q + ((size_t)c0 * Hg + hq) * kKD;
const unsigned short* ag = Amat + ((size_t)c0 * H + hv) * kBT;
const size_t qrs = (size_t)Hg * kKD, ars = (size_t)H * kBT;
const float gl = gcs[(size_t)(c0 + lim) * H + hv];
// Issued before the staging store so the LDS writes cover their latency. Only waves 0-1
// (tid < BT) run this; the others wait at (1).
float ggr = 0.f, btr = 0.f;
if (tid < kBT) {
const bool ok = tid < nval;
ggr = ok ? gcs[(size_t)(c0 + tid) * H + hv] : 0.f;
btr = ok ? beta[(size_t)(c0 + tid) * H + hv] : 0.f;
}
{ // consume the previous iteration's prefetch, issued a whole chunk of compute ago
#pragma unroll
for (int u = 0; u < NKB; ++u) PFSTORE(&s.k[KROW(u)][KCOL], kb[u]);
#pragma unroll
for (int u = 0; u < NVB; ++u) PFSTORE(&s.D[VROW(u)][VCOL], vb[u]);
}
if (tid < kBT) {
const bool ok = tid < nval;
s.bt[tid] = btr;
s.ge[tid] = __expf(ggr);
// g is a within-chunk cumsum of log-sigmoid gates, so it is non-increasing and gl is
// its minimum. A padding row gets gl, not 0: it is scored against live j with very
// negative g_j, and g_i = 0 would give exp(+400) = inf in s.A. With gl the exponent
// stays in (0, scale]. The row is discarded anyway (the O store is guarded).
s.gg[tid] = ok ? ggr : gl;
s.gv[tid] = ok ? __expf(gl - ggr) : 0.f; // gs
}
R3D_BARRIER(); // (1)
PREFETCH(std::min(ci + 1, nchunk - 1)); // issue only; consumed next iteration
if (dbg && ci == 0) {
for (int i = tid; i < kBT * (kKD / 4); i += kNTHR) {
const int r = i / (kKD / 4), c = (i % (kKD / 4)) * 4;
unsigned short* o = dbg + 4 * kBT * kBT + (size_t)r * kBT + c;
const unsigned short* a1 = &s.k[r][c];
o[0] = a1[0]; o[1] = a1[1]; o[2] = a1[2]; o[3] = a1[3];
}
}
// ---- U = K@S, O^T = S@Q^T and P^T = K@Q^T share the q and k fragments.
// Tiles above the diagonal (A is unit lower triangular, sA is masked) are computed
// anyway: skipping them is 2.4% slower on the source card, since some wave still
// carries two tiles, so the barrier arrival does not move, and the guards stop
// fragment loads batching ahead of the WMMAs.
v8f O[kNTV], u[kNTV], p[kNTV];
#pragma unroll
for (int i = 0; i < kNTV; ++i) { O[i] = (v8f){}; u[i] = (v8f){}; p[i] = (v8f){}; }
{
const char* sb = sbase;
unsigned oSn[kNTV];
#pragma unroll
for (int i = 0; i < kNTV; ++i) {
oSn[i] = ROWO(s.S, kKP, (ntb + i) * 16);
asm volatile("" : "+v"(oSn[i]));
}
#define pSnf(i, ko) fragP((const unsigned short*)(sb + oSn[i] + (ko) * 2u))
const unsigned qo = (unsigned)std::min(mt * 16 + (lane & 15), lim) * (unsigned)qrs;
#define pqf(ko) fragGo(qg, qo + (ko))
// O^T = S@Q^T stays on the wave matrix: its s.S B-operand and the global Q read are
// exact. U = K@S and P^T = K@Q^T run as manual FMAs: the s.k A-operand fragment
// read is decimated on this card (the odd k-elements come back zero, in every load
// form tried), while the scalar read of the same buffer is verifiably exact.
#pragma unroll
for (int sk = 0; sk < kKD / 16; ++sk) {
const int ko = sk * 16;
const v16short aq = pqf(ko);
#pragma unroll
for (int i = 0; i < kNTV; ++i)
O[i] = mmab(pSnf(i, ko), aq, O[i]); // O^T: m = v-tile, n = token-tile
}
#pragma unroll
for (int i = 0; i < kNTV; ++i) {
const unsigned short* srow = &s.S[(ntb + i) * 16 + lo][0];
#pragma unroll
for (int e = 0; e < 8; ++e) {
const unsigned short* krow = &s.k[mt * 16 + 2 * e + hi][0];
float acc = 0.f;
#pragma unroll
for (int kk = 0; kk < kKD; ++kk)
acc = fmaf(bf16_to_f32(krow[kk]), bf16_to_f32(srow[kk]), acc);
u[i][e] = acc;
}
}
// P^T: the Q row is clamped to the last live token, as the fragment read was.
{
const unsigned short* qrow =
qg + (unsigned)std::min(mt * 16 + lo, lim) * (unsigned)qrs;
#pragma unroll
for (int i = 0; i < kNTV; ++i) {
if (dbg && ci == 0 && i == 0)
dbg[9 * kBT * kBT + lane] = s.k[(ntb) * 16 + lo][0]; // raw LDS value
#pragma unroll
for (int e = 0; e < 8; ++e) {
const unsigned short* krow = &s.k[(ntb + i) * 16 + 2 * e + hi][0];
float acc = 0.f;
#pragma unroll
for (int kk = 0; kk < kKD; ++kk)
acc = fmaf(bf16_to_f32(krow[kk]), bf16_to_f32(qrow[kk]), acc);
p[i][e] = acc;
}
}
}
}
{
const float g = scale * s.ge[mt * 16 + lo]; // token index is constant per lane
#pragma unroll
for (int i = 0; i < kNTV; ++i)
#pragma unroll
for (int e = 0; e < 8; ++e) O[i][e] *= g;
}
// W = beta * (V - ge*U) (beta folded here: (A*beta_col)@W == A@(beta_row*W))
{
float wa[kNTV][8];
#pragma unroll
for (int e = 0; e < 8; ++e) { // the U token is 2e + hi on this card
const int tok = mt * 16 + 2 * e + hi;
const float f = s.bt[tok], g = s.ge[tok];
#pragma unroll
for (int i = 0; i < kNTV; ++i)
wa[i][e] = f * (bf16_to_f32(s.D[tok][(ntb + i) * 16 + lo]) - g * u[i][e]);
}
#pragma unroll
for (int i = 0; i < kNTV; ++i)
#pragma unroll
for (int e = 0; e < 8; ++e)
s.W[(ntb + i) * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(wa[i][e]);
}
// sA = scale * e^{g_i-g_j} * tril(P). Row ii is constant per lane and the eight g_j are
// uniform per 16 lanes: eight broadcast LDS reads and a v_exp per tile (log(scale) is
// in the exponent). Where kept, g_i - g_j <= 0, so the exp cannot overflow.
if (dbg && ci == 0) {
#pragma unroll
for (int i = 0; i < kNTV; ++i)
#pragma unroll
for (int e = 0; e < 8; ++e)
dbg[3 * kBT * kBT + (mt * 16 + lo) * kBT + (ntb + i) * 16 + 2 * e + hi] =
f32_to_bf16(p[i][e]);
}
{
const int ii = mt * 16 + lo;
const float gis = s.gg[ii] + lgs;
#pragma unroll
for (int i = 0; i < kNTV; ++i) {
const int j0 = (ntb + i) * 16;
float a[8];
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int j = j0 + 2 * e + hi;
a[e] = (j <= ii) ? p[i][e] * __expf(gis - s.gg[j]) : 0.f;
}
#pragma unroll
for (int e = 0; e < 8; ++e)
s.A[ii][j0 + 2 * e + hi] = f32_to_bf16(a[e]);
}
}
R3D_BARRIER(); // (2)
// ---- V' = A @ W -> D (stored [v][token], transposed for the state read)
{
v8f d[kNTV];
#pragma unroll
for (int i = 0; i < kNTV; ++i) d[i] = (v8f){};
const unsigned ao = (unsigned)std::min(mt * 16 + (lane & 15), lim) * (unsigned)ars;
#define paf(ko) fragGo(ag, ao + (ko))
const unsigned short* pwn[kNTV];
#pragma unroll
for (int i = 0; i < kNTV; ++i)
pwn[i] = &s.W[(ntb + i) * 16 + lo][0];
#define pwnf(i, ko) fragP(pwn[i] + (ko))
#pragma unroll
for (int sk = 0; sk < kBT / 16; ++sk) {
const int ko = sk * 16;
const v16short a = paf(ko);
#pragma unroll
for (int i = 0; i < kNTV; ++i) d[i] = mmab(a, pwnf(i, ko), d[i]);
}
#pragma unroll
for (int i = 0; i < kNTV; ++i)
#pragma unroll
for (int e = 0; e < 8; ++e)
s.D[(ntb + i) * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(d[i][e]);
}
// K <- gs * K in place, for the state's V'^T @ K: (diag(gs) V')^T K == V'^T (diag(gs) K),
// and K is otherwise dead. All raw-K reads (U, P) retired before barrier (2); s.k is
// restaged next chunk; barrier (3) publishes the scaled K.
#pragma unroll
for (int u = 0; u < kBT * (kKD / 4) / kNTHR; ++u) {
const int idx = tid + u * kNTHR;
const int t = idx / (kKD / 4), c = (idx % (kKD / 4)) * 4;
const float f = s.gv[t];
unsigned short* kp = &s.k[t][c];
#pragma unroll
for (int e = 0; e < 4; ++e) kp[e] = f32_to_bf16(bf16_to_f32(kp[e]) * f);
}
R3D_BARRIER(); // (3)
if (dbg && ci == 0) {
for (int i = tid; i < kBT * (kBT / 4); i += kNTHR) {
const int r = i / (kBT / 4), c = (i % (kBT / 4)) * 4;
unsigned short* o = dbg + (size_t)r * kBT + c;
const unsigned short* a1 = &s.A[r][c];
const unsigned short* a2 = &s.W[r][c];
const unsigned short* a3 = &s.D[r][c];
o[0] = a1[0]; o[1] = a1[1]; o[2] = a1[2]; o[3] = a1[3];
o[kBT*kBT] = a2[0]; o[kBT*kBT+1] = a2[1]; o[kBT*kBT+2] = a2[2]; o[kBT*kBT+3] = a2[3];
o[2*kBT*kBT] = a3[0]; o[2*kBT*kBT+1] = a3[1]; o[2*kBT*kBT+2] = a3[2]; o[2*kBT*kBT+3] = a3[3];
}
}
// ---- O += sA @ V' ; store. V' also feeds the state update, unchanged. The product
// runs in the transposed frame (V' as A, sA as B), adding (sA@V')^T to O^T.
{
const unsigned short* pA = &s.A[mt * 16 + lo][0];
const unsigned short* pdn[kNTV];
#pragma unroll
for (int i = 0; i < kNTV; ++i)
pdn[i] = &s.D[(ntb + i) * 16 + lo][0];
#define pAf(ko) fragP(pA + (ko))
#define pdnf(i, ko) fragP(pdn[i] + (ko))
#pragma unroll
for (int sk = 0; sk < kBT / 16; ++sk) {
const int ko = sk * 16;
const v16short b = pAf(ko);
#pragma unroll
for (int i = 0; i < kNTV; ++i) O[i] = mmab(pdnf(i, ko), b, O[i]);
}
}
{
const int tok = mt * 16 + lo;
// The padding rows carry zero (the zeroed K, beta, gv and Q rows), so the store is
// unguarded and the output is finite at every row the caller can index.
{
unsigned short* op = o + ((size_t)(c0 + tok) * H + hv) * kVD + v0;
#pragma unroll
for (int i = 0; i < kNTV; ++i)
#pragma unroll
for (int e = 0; e < 8; ++e)
op[(ntb + i) * 16 + 2 * e + hi] = f32_to_bf16(O[i][e]);
}
}
// ---- S = e^{gl} * S + V'^T @ (gs*K) (A needs K as [dim][token] -> strided fragT)
{
const float ec = __expf(gl); // gl <= 0: the decay is already on K
#pragma unroll
for (int t = 0; t < kNST; ++t)
#pragma unroll
for (int e = 0; e < 8; ++e) St[t][e] *= ec;
// The s.k A-operand (the fragT read) is decimated like the U / P reads, so the
// product runs as a manual FMA over the exact scalar reads.
#pragma unroll
for (int t = 0; t < kNST; ++t) {
const int v = VT(t) * 16 + lo;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int kx = KT(t) * 16 + 2 * e + hi;
float acc = 0.f;
#pragma unroll
for (int tk = 0; tk < kBT; ++tk)
acc = fmaf(bf16_to_f32(s.k[tk][kx]), bf16_to_f32(s.D[v][tk]), acc);
St[t][e] += acc;
}
}
}
// No barrier before the writeback: s.S aliases nothing, and barrier (2) proves every
// wave finished its U/O reads of s.S this chunk.
SWRITE();
R3D_BARRIER(); // (4)
}
if (HT) {
typename cs_state<SDT>::T* p = ht + st_base;
#pragma unroll
for (int t = 0; t < kNST; ++t) {
typename cs_state<SDT>::T* pw = p + (size_t)(v0 + VT(t) * 16 + lo) * kKD + KT(t) * 16;
#pragma unroll
for (int e = 0; e < 8; ++e) {
if (SDT)
pw[2 * e + hi] = (typename cs_state<SDT>::T)St[t][e];
else
pw[2 * e + hi] = St[t][e];
}
}
}
}
int r3d_gdn_chunk_scan_launch(const void* q, const void* k, const void* v, const void* A,
const void* g, const void* beta, const void* h0, void* o,
void* ht, const void* cu, const void* sidx, long sidx_stride,
long st_slot, long st_head, int N, int H, int Hg, int K, int V,
int chunk, float scale, int state_fp16, void* dbg, hipStream_t stream)
{
if (K != kKD || V != kVD || chunk != kBT) return -1;
if (Hg <= 0 || H % Hg) return -2;
dim3 grid(V / kBV, H, N), blk(kNTHR);
#define CS_LAUNCH(SDTC, H0C, HTC) \
R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_chunk_scan_kernel<SDTC, H0C, HTC>)), grid, blk, 0, stream, \
(const unsigned short*)q, (const unsigned short*)k, (const unsigned short*)v, \
(const unsigned short*)A, (const float*)g, (const float*)beta, \
(const cs_state<SDTC>::T*)h0, (unsigned short*)o, (cs_state<SDTC>::T*)ht, \
(const int*)cu, (const int*)sidx, sidx_stride, st_slot, st_head, H, Hg, scale, (unsigned short*)dbg)
#define CS_PICK(SDTC) \
do { if (h0 && ht) CS_LAUNCH(SDTC, true, true); \
else if (h0) CS_LAUNCH(SDTC, true, false); \
else if (ht) CS_LAUNCH(SDTC, false, true); \
else CS_LAUNCH(SDTC, false, false); } while (0)
if (state_fp16) CS_PICK(1); else CS_PICK(0);
#undef CS_PICK
#undef CS_LAUNCH
return (int)hipGetLastError();
}
} // namespace
/* ------------------------------------------------------------------ the raw entry */
extern "C" int r3d_gdn_chunk_scan_k128_v128_c64(long q, long k, long v, long A, long g, long beta,
long h0, long o, long ht, long cu, long sidx,
long sidx_stride, long st_slot, long st_head,
int N, int H, int Hg, int K, int V, int chunk,
double scale, int state_fp16, long dbg, long stream)
{
if (!q || !k || !v || !A || !g || !beta || !cu || !o) return -1;
if (N < 1 || H < 1 || Hg < 1) return -2;
return r3d_gdn_chunk_scan_launch((const void*)q, (const void*)k, (const void*)v, (const void*)A,
(const void*)g, (const void*)beta, (const void*)h0,
(void*)o, (void*)ht, (const void*)cu, (const void*)sidx,
sidx_stride, st_slot, st_head, N, H, Hg, K, V, chunk,
(float)scale, state_fp16, (void*)dbg, (hipStream_t)stream);
}
/* ------------------------------------------------------------------ the plugin ABI */
enum { CS_Q = 0, CS_K, CS_V, CS_A, CS_G, CS_BETA, CS_H0, CS_CU, CS_O, CS_HT, CS_SIDX };
extern "C" int r3d_rad_gdn_chunk_scan(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const RadTensor* qt = r3d_opt(a, CS_Q);
const RadTensor* kt = r3d_opt(a, CS_K);
const RadTensor* vt = r3d_opt(a, CS_V);
const RadTensor* At = r3d_opt(a, CS_A);
const RadTensor* gt = r3d_opt(a, CS_G);
const RadTensor* btt = r3d_opt(a, CS_BETA);
const RadTensor* h0t = r3d_opt(a, CS_H0);
const RadTensor* cut = r3d_opt(a, CS_CU);
const RadTensor* ot = r3d_opt(a, CS_O);
const RadTensor* htt = r3d_opt(a, CS_HT);
const RadTensor* sit = r3d_opt(a, CS_SIDX);
if (!r3d_p(qt) || !r3d_p(kt) || !r3d_p(vt) || !r3d_p(At) || !r3d_p(gt) || !r3d_p(btt) ||
!r3d_p(cut) || !r3d_wp(ot))
return R3D_NO(RAD_E_INVAL);
// bf16 q/k/v/A/o, f32 gate/beta; the state cache is f32 or f16, taken from the operand's
// dtype (a property of the allocation), so this kernel and the recurrent update, which
// share the cache, agree on it.
if (!r3d_is_bf16(qt) || !r3d_is_bf16(kt) || !r3d_is_bf16(vt) || !r3d_is_bf16(At) ||
!r3d_is_f32(gt) || !r3d_is_f32(btt) || !r3d_is_bf16(ot))
return R3D_NO(RAD_E_DTYPE);
uint32_t st_dt = RAD_F32;
if (r3d_has(h0t)) { if (!r3d_is_f32(h0t) && !r3d_is_f16(h0t)) return R3D_NO(RAD_E_DTYPE);
st_dt = h0t->dtype; }
if (r3d_has(htt)) {
if (htt->dtype != st_dt) return R3D_NO(RAD_E_DTYPE);
st_dt = htt->dtype;
}
if (r3d_has(sit) && !r3d_is_i32(sit)) return R3D_NO(RAD_E_DTYPE);
if (cut->rank != 1 || cut->shape[0] < 2 || !r3d_contig(cut)) return R3D_NO(RAD_E_SHAPE);
const int N = (int)(cut->shape[0] - 1);
const long long T = r3d_dim(qt, 0), Hg = r3d_dim(qt, 1), K = r3d_dim(qt, 2);
const long long H = r3d_dim(vt, 1), V = r3d_dim(vt, 2);
const long long chunk = r3d_dim(At, 2);
if (r3d_dim(kt, 0) != T || r3d_dim(kt, 1) != Hg || r3d_dim(kt, 2) != K) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(vt, 0) != T) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(ot, 0) != T || r3d_dim(ot, 1) != H || r3d_dim(ot, 2) != V) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(At, 0) != T || r3d_dim(At, 1) != H) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(gt, 0) != T || r3d_dim(gt, 1) != H) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(btt, 0) != T || r3d_dim(btt, 1) != H) return R3D_NO(RAD_E_SHAPE);
if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE);
// The state slot strides come from the tensor, not from H, V and K, so a cache with padded
// slots is served too. h0 and ht must share strides: the kernel uses one base for both.
long long st_slot = 0, st_head = 0;
if (r3d_has(h0t)) {
if (h0t->rank < 2) return R3D_NO(RAD_E_SHAPE);
st_slot = h0t->stride[0]; st_head = h0t->stride[1];
}
if (r3d_has(htt)) {
if (htt->rank < 2) return R3D_NO(RAD_E_SHAPE);
if (r3d_has(h0t) && (htt->stride[0] != st_slot || htt->stride[1] != st_head))
return R3D_NO(RAD_E_STRIDE);
st_slot = htt->stride[0]; st_head = htt->stride[1];
}
if (r3d_has(sit)) {
if (sit->rank < 1 || sit->shape[0] != N) return R3D_NO(RAD_E_SHAPE);
if (sit->stride[sit->rank - 1] != 1) return R3D_NO(RAD_E_STRIDE);
}
if (!r3d_contig(qt) || !r3d_contig(kt) || !r3d_contig(vt) || !r3d_contig(At) ||
!r3d_contig(gt) || !r3d_contig(btt) || !r3d_contig(ot))
return R3D_NO(RAD_E_STRIDE);
const double scale = r3d_getf(a, "scale", 1.0);
const int state_fp16 = st_dt == RAD_F16;
const int e = r3d_gdn_chunk_scan_launch(r3d_p(qt), r3d_p(kt), r3d_p(vt), r3d_p(At), r3d_p(gt),
r3d_p(btt), r3d_has(h0t) ? r3d_p(h0t) : nullptr, r3d_wp(ot),
r3d_has(htt) ? r3d_wp(htt) : nullptr, r3d_p(cut),
r3d_has(sit) ? r3d_p(sit) : nullptr,
r3d_has(sit) && sit->rank >= 2 ? sit->stride[0] : 1,
st_slot, st_head, N, (int)H, (int)Hg, (int)K, (int)V,
(int)chunk, (float)scale, state_fp16, nullptr, (hipStream_t)s);
/* The launcher's codes are raw: its own negatives and hipGetLastError's positives. The
* plugin ABI takes RadStatus, so normalise. */
if (e < 0) return R3D_NO(RAD_E_INVAL);
return e ? R3D_NO(RAD_E_DEVICE) : RAD_OK;
}
+585
View File
@@ -0,0 +1,585 @@
/* r3d_gdn_conv_w4_h128.hip -- the gated-delta-net depthwise causal convolution and the work fused
* around it, one entry point per serving phase.
*
* PREFILL (gdn_conv_prep): everything the layer does between the qkv projection and the chunked
* scan, in one kernel:
*
* conv(x) depthwise causal convolution, width 4, silu, varlen, with the conv-state
* cache read at a sequence's first chunk and rewritten from its last tokens
* split the packed [q | k | v] channel range into three contiguous tensors
* l2norm over each 128-dim q and k head
* gate g = -exp(A_log) . softplus(a + dt_bias), beta = sigmoid(b)
* cumsum g summed along the chunk, which is what the scan actually consumes
*
* The conv output is rounded to bf16 before the norm and the store, so this kernel is a bit-exact
* drop-in for the unfused causal_conv1d_fn + fused_post_conv_prep + chunk_local_cumsum pair.
*
* DECODE (gdn_conv_update): the same filter, but a step's tokens are a speculative window and the
* state cache is a rolling buffer of width-1 + num_spec entries: a step reads its window starting
* at the slot the last accepted token left, and rewrites the buffer shifted by one.
*
* A workgroup is HPB waves, one wave per 128-dim head, four dims per lane, so a head's norm is a
* barrier-free wave reduction and each lane does one 8-byte access. Tokens are blocked by the
* 64-token chunk because the cumsum is per chunk.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_args.h"
#include "r3d_codecs.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdint>
namespace {
constexpr int kHD = 128; // dims per head, q k and v alike
constexpr int kBT = 64; // token block = the scan's chunk, so the cumsum stays wave-local
constexpr int kW = 4; // conv width
constexpr int kST = kW - 1; // conv state depth (3 taps of history)
constexpr int kMAXT = 8; // tokens the decode update preloads into registers
constexpr int kDPL = 4; // dims per lane (kHD / 32)
/* One convolution tap: rounded to bf16 by the caller. The reciprocal form is two instructions
* against ~10 for an IEEE-exact divide, and v_rcp_f32 is 1 ULP against bf16's 2^-8 quantum. */
__device__ __forceinline__ float cp_silu(float z)
{
return z * __builtin_amdgcn_rcpf(1.0f + __expf(-z));
}
/* softplus, in the two-sided form with the same large-x cutoff. */
__device__ __forceinline__ float cp_softplus(float x, float thr)
{
if (x > thr) return x;
return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x))) : __logf(1.0f + __expf(x));
}
/* a and b are read where they lie: a chunk() of the ba projection, bf16 with row stride 2*H (or
* fp32), avoiding a copy and two launches per layer. */
template <int ABF16>
__device__ __forceinline__ float cp_ab(const void* p, size_t i)
{
return ABF16 ? bf16_to_f32(((const unsigned short*)p)[i]) : ((const float*)p)[i];
}
/* `has_init` says whether the slot holds a history; its element width (int32 or byte) is given
* by the caller. Read as bytes, a ctx_len of 512 would look like 0 and the conv window would
* silently start from zeros. */
__device__ __forceinline__ bool r3d_has_init(const void* p, int i32, int n)
{
if (!p) return false;
return i32 ? ((const int*)p)[n] != 0 : ((const unsigned char*)p)[n] != 0;
}
/* ================================ the prefill convolution ================================ */
template <int HPB, int ABF16>
__global__ __launch_bounds__(HPB * 32)
void r3d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long long xpitch,
const unsigned short* __restrict__ wgt,
const unsigned short* __restrict__ bias,
unsigned short* __restrict__ cstate,
long long cs_seq, long long cs_dim, long long cs_tok,
const int* __restrict__ cache_idx, long long ci_stride,
const void* __restrict__ has_init, int hi_i32,
const void* __restrict__ av, const void* __restrict__ bv,
long long ab_stride,
const float* __restrict__ A_log, const float* __restrict__ dt_bias,
unsigned short* __restrict__ q, unsigned short* __restrict__ k,
unsigned short* __restrict__ v,
float* __restrict__ go, float* __restrict__ beta,
const int* __restrict__ cu, int N, int H, int Hg, float sp_thr)
{
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
// flat chunk id -> (sequence, chunk); the grid is an upper bound.
int n = -1, t0 = 0, bos = 0, rows = 0, slen = 0;
{
int acc = 0, want = blockIdx.x;
for (int i = 0; i < N; ++i) {
const int b = cu[i], e = cu[i + 1];
const int nc = (e - b + kBT - 1) / kBT;
if (want < acc + nc) { n = i; bos = b; slen = e - b; t0 = (want - acc) * kBT;
rows = min(kBT, slen - t0); break; }
acc += nc;
}
if (n < 0) return;
}
const bool first = (t0 == 0);
// ---- the gating half, on one workgroup per chunk --------------------------------------
if (blockIdx.y == 0) {
for (int hv = warp; hv < H; hv += HPB) {
const float alog = __expf(A_log[hv]), dtb = dt_bias[hv];
const int i0 = 2 * lane, i1 = i0 + 1;
float g0 = 0.0f, g1 = 0.0f;
if (i0 < rows)
g0 = -alog * cp_softplus(cp_ab<ABF16>(av, (size_t)(bos + t0 + i0) * ab_stride + hv)
+ dtb, sp_thr);
if (i1 < rows)
g1 = -alog * cp_softplus(cp_ab<ABF16>(av, (size_t)(bos + t0 + i1) * ab_stride + hv)
+ dtb, sp_thr);
// inclusive wave scan of the per-lane pair sums, made exclusive by subtracting the pair
float p = g0 + g1;
#pragma unroll
for (int d = 1; d < 32; d <<= 1) {
const float o = __shfl_up(p, d, 32);
if (lane >= d) p += o;
}
const float pre = p - (g0 + g1);
if (i0 < rows) {
go[(size_t)(bos + t0 + i0) * H + hv] = pre + g0;
beta[(size_t)(bos + t0 + i0) * H + hv] = 1.0f / (1.0f + __expf(
-cp_ab<ABF16>(bv, (size_t)(bos + t0 + i0) * ab_stride + hv)));
}
if (i1 < rows) {
go[(size_t)(bos + t0 + i1) * H + hv] = pre + g0 + g1;
beta[(size_t)(bos + t0 + i1) * H + hv] = 1.0f / (1.0f + __expf(
-cp_ab<ABF16>(bv, (size_t)(bos + t0 + i1) * ab_stride + hv)));
}
}
}
// ---- the convolution half --------------------------------------------------------------
const int unit = blockIdx.y * HPB + warp;
const int d0 = unit * kHD + lane * kDPL;
const unsigned short* xp = x + (size_t)(bos + t0) * xpitch + d0;
float wt[kW][kDPL], bs[kDPL];
#pragma unroll
for (int c = 0; c < kDPL; ++c) {
#pragma unroll
for (int i = 0; i < kW; ++i) wt[i][c] = bf16_to_f32(wgt[(size_t)(d0 + c) * kW + i]);
bs[c] = bias ? bf16_to_f32(bias[d0 + c]) : 0.0f;
}
// win[i] holds x[t - (W-1) + i]; seeded from the previous tokens, or from the conv state cache
// at the sequence's first chunk.
float win[kW][kDPL];
{
const bool init = first && r3d_has_init(has_init, hi_i32, n);
const unsigned short* sp = init ? (cstate + (size_t)cache_idx[(size_t)n * ci_stride] * cs_seq
+ (size_t)d0 * cs_dim) : nullptr;
#pragma unroll
for (int i = 0; i < kST; ++i) { // i = 0,1,2 -> x[t0-3+i]
const int src = t0 - kST + i;
#pragma unroll
for (int c = 0; c < kDPL; ++c) {
float val = 0.0f;
if (src >= 0) val = bf16_to_f32(x[(size_t)(bos + src) * xpitch + d0 + c]);
else if (init) val = bf16_to_f32(sp[(size_t)c * cs_dim + (size_t)(kST + src) * cs_tok]);
win[i][c] = val;
}
}
}
// ---- write the new conv state, from x, at the sequence's first chunk --------------------
if (first && cache_idx) {
unsigned short* sp = cstate + (size_t)cache_idx[(size_t)n * ci_stride] * cs_seq
+ (size_t)d0 * cs_dim;
const bool init = r3d_has_init(has_init, hi_i32, n);
// Channel-major: the cache is [dim][slot] with slot contiguous, so a lane's kDPL*kST
// shorts are one contiguous run.
#pragma unroll
for (int c = 0; c < kDPL; ++c) {
#pragma unroll
for (int i = 0; i < kST; ++i) {
const int src = slen - kST + i;
unsigned short val = 0;
if (src >= 0) val = x[(size_t)(bos + src) * xpitch + d0 + c];
else if (init) val = sp[(size_t)c * cs_dim + (size_t)(kST + src) * cs_tok];
sp[(size_t)c * cs_dim + (size_t)i * cs_tok] = val;
}
}
}
const int hq = unit, hk = unit - Hg, hv = unit - 2 * Hg;
const int region = (unit < Hg) ? 0 : ((unit < 2 * Hg) ? 1 : 2);
for (int t = 0; t < rows; ++t) {
float o[kDPL];
{
const unsigned short* xr = xp + (size_t)t * xpitch;
const ushort4 raw = *(const ushort4*)xr;
win[kW - 1][0] = bf16_to_f32(raw.x); win[kW - 1][1] = bf16_to_f32(raw.y);
win[kW - 1][2] = bf16_to_f32(raw.z); win[kW - 1][3] = bf16_to_f32(raw.w);
}
#pragma unroll
for (int c = 0; c < kDPL; ++c) {
float acc = bs[c];
#pragma unroll
for (int i = 0; i < kW; ++i) acc += wt[i][c] * win[i][c];
o[c] = bf16_to_f32(f32_to_bf16(cp_silu(acc)));
}
if (region < 2) {
float ss = 0.0f;
#pragma unroll
for (int c = 0; c < kDPL; ++c) ss += o[c] * o[c];
ss += r3d_xor_lane<16>(ss); ss += r3d_xor_lane<8>(ss); ss += r3d_xor_lane<4>(ss);
ss += r3d_xor_lane<2>(ss); ss += r3d_xor_lane<1>(ss);
const float inv = 1.0f / sqrtf(ss + 1e-6f);
unsigned short* dst = (region ? k : q)
+ ((size_t)(bos + t0 + t) * Hg + (region ? hk : hq)) * kHD
+ lane * kDPL;
*(ushort4*)dst = make_ushort4(f32_to_bf16(o[0] * inv), f32_to_bf16(o[1] * inv),
f32_to_bf16(o[2] * inv), f32_to_bf16(o[3] * inv));
} else {
unsigned short* dst = v + ((size_t)(bos + t0 + t) * H + hv) * kHD + lane * kDPL;
*(ushort4*)dst = make_ushort4(f32_to_bf16(o[0]), f32_to_bf16(o[1]),
f32_to_bf16(o[2]), f32_to_bf16(o[3]));
}
#pragma unroll
for (int i = 0; i < kW - 1; ++i)
#pragma unroll
for (int c = 0; c < kDPL; ++c) win[i][c] = win[i + 1][c];
}
}
int r3d_gdn_conv_prep_launch(const void* x, long long xpitch, const void* wgt, const void* bias,
void* cstate, long long cs_seq, long long cs_dim, long long cs_tok,
const void* cache_idx, long long ci_stride, const void* has_init,
int hi_i32, const void* a, const void* b, long long ab_stride,
int ab_is_bf16, const void* A_log, const void* dt_bias, void* q,
void* k, void* v, void* g, void* beta, const void* cu,
int N, int T, int H, int Hg, int width, float softplus_thr,
hipStream_t stream)
{
const int units = 2 * Hg + H;
int hpb = 8;
while (hpb > 1 && (Hg % hpb || H % hpb)) hpb >>= 1;
const int nchunk_ub = (T + kBT - 1) / kBT + N;
dim3 grid(nchunk_ub, units / hpb), blk(hpb * 32);
#define CP_LAUNCH(P, AB) \
R3D_KLAUNCH(R3D_KNAME((r3d_gdn_conv_prep_kernel<P, AB>)), grid, blk, stream, \
(const unsigned short*)x, xpitch, (const unsigned short*)wgt, \
(const unsigned short*)bias, (unsigned short*)cstate, \
cs_seq, cs_dim, cs_tok, (const int*)cache_idx, ci_stride, \
has_init, hi_i32, a, b, ab_stride, \
(const float*)A_log, (const float*)dt_bias, (unsigned short*)q, \
(unsigned short*)k, (unsigned short*)v, (float*)g, (float*)beta, \
(const int*)cu, N, H, Hg, softplus_thr)
#define CP_SWITCH(AB) \
switch (hpb) { \
case 8: CP_LAUNCH(8, AB); break; \
case 4: CP_LAUNCH(4, AB); break; \
case 2: CP_LAUNCH(2, AB); break; \
default: CP_LAUNCH(1, AB); break; \
}
if (ab_is_bf16) { CP_SWITCH(1); } else { CP_SWITCH(0); }
#undef CP_SWITCH
#undef CP_LAUNCH
return (int)hipGetLastError();
}
/* ================================ the decode convolution ================================ */
template <int HPB>
__global__ __launch_bounds__(HPB * 32)
void r3d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long long xpitch,
const unsigned short* __restrict__ wgt,
const unsigned short* __restrict__ bias,
unsigned short* __restrict__ cstate,
long long cs_seq, long long cs_dim, long long cs_tok,
int state_len_max,
const int* __restrict__ cache_idx, long long ci_stride,
const int* __restrict__ naccept,
unsigned short* __restrict__ q, unsigned short* __restrict__ k,
unsigned short* __restrict__ v,
const int* __restrict__ cu, int H, int Hg, int maxq)
{
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const int n = blockIdx.x;
const int bos = cu[n], slen = cu[n + 1] - bos;
if (slen <= 0) return;
const int slot = cache_idx[(size_t)n * ci_stride];
if (slot < 0) return;
const int off = naccept ? (naccept[n] - 1) : 0;
const int slen_eff = state_len_max - (maxq - slen);
const int unit = blockIdx.y * HPB + warp;
const int d0 = unit * kHD + lane * kDPL;
static_assert(kW == 4, "the weight load reads a channel's taps as one ushort4");
float wt[kW][kDPL], bs[kDPL];
#pragma unroll
for (int c = 0; c < kDPL; ++c) {
const ushort4 w4 = *(const ushort4*)(wgt + (size_t)(d0 + c) * kW);
const unsigned short* ws = (const unsigned short*)&w4;
#pragma unroll
for (int i = 0; i < kW; ++i) wt[i][c] = bf16_to_f32(ws[i]);
bs[c] = bias ? bf16_to_f32(bias[d0 + c]) : 0.0f;
}
const int csd = (int)cs_dim, cst = (int)cs_tok, xpi = (int)xpitch;
unsigned short* const sp = cstate + (size_t)slot * cs_seq + (size_t)d0 * cs_dim;
const unsigned short* const xrow = x + (size_t)bos * xpitch + d0;
ushort4 xb[kMAXT];
const bool xpre = (slen <= kMAXT);
#pragma unroll
for (int t = 0; t < kMAXT; ++t)
if (xpre && t < slen) xb[t] = *(const ushort4*)(xrow + t * xpi);
float win[kW][kDPL];
unsigned short hist[kST][kDPL];
{
const unsigned short* hp = sp + off * cst;
#pragma unroll
for (int i = 0; i < kST; ++i)
#pragma unroll
for (int c = 0; c < kDPL; ++c) {
const unsigned short raw = hp[c * csd + i * cst];
hist[i][c] = raw;
win[i][c] = bf16_to_f32(raw);
}
}
const int hq = unit, hk = unit - Hg, hv = unit - 2 * Hg;
const int region = (unit < Hg) ? 0 : ((unit < 2 * Hg) ? 1 : 2);
unsigned short* op = (region == 2)
? (v + ((size_t)bos * H + hv) * kHD + lane * kDPL)
: ((region ? k : q) + ((size_t)bos * Hg + (region ? hk : hq)) * kHD + lane * kDPL);
const int ostep = (region == 2) ? H * kHD : Hg * kHD;
#define CU_TOKEN_BODY(RAW) \
{ \
const ushort4 raw_ = (RAW); \
win[kW - 1][0] = bf16_to_f32(raw_.x); win[kW - 1][1] = bf16_to_f32(raw_.y); \
win[kW - 1][2] = bf16_to_f32(raw_.z); win[kW - 1][3] = bf16_to_f32(raw_.w); \
unsigned short out[kDPL]; \
_Pragma("unroll") \
for (int c = 0; c < kDPL; ++c) { \
float acc = bs[c]; \
_Pragma("unroll") \
for (int i = 0; i < kW; ++i) acc += wt[i][c] * win[i][c]; \
out[c] = f32_to_bf16(cp_silu(acc)); \
} \
*(ushort4*)op = make_ushort4(out[0], out[1], out[2], out[3]); \
op += ostep; \
_Pragma("unroll") \
for (int i = 0; i < kW - 1; ++i) \
_Pragma("unroll") \
for (int c = 0; c < kDPL; ++c) win[i][c] = win[i + 1][c]; \
}
if (xpre) {
#pragma unroll
for (int t = 0; t < kMAXT; ++t) {
if (t < slen) CU_TOKEN_BODY(xb[t])
}
} else {
for (int t = 0; t < slen; ++t) CU_TOKEN_BODY(*(const ushort4*)(xrow + t * xpi))
}
// Rewrite the cache shifted by one.
const int VAL = kW - 2;
const int nh = slen_eff - slen < 0 ? 0 : (slen_eff - slen);
#pragma unroll
for (int c = 0; c < kDPL; ++c) {
unsigned short* dst = sp + c * csd;
#pragma unroll
for (int i = 0; i + 1 < kST; ++i)
if (i < nh && i < slen_eff) dst[i * cst] = hist[i + 1][c];
if (xpre) {
#pragma unroll
for (int t = 0; t < kMAXT; ++t) {
const int i = t + VAL;
if (i >= nh && i < slen_eff && t < slen) {
const ushort4 vv = xb[t];
dst[i * cst] = (c == 0) ? vv.x : (c == 1) ? vv.y : (c == 2) ? vv.z : vv.w;
}
}
}
for (int i = nh; i < slen_eff; ++i) {
const int ti = i - VAL;
if (!xpre || ti < 0 || ti >= slen) dst[i * cst] = xrow[ti * xpi + c];
}
}
#undef CU_TOKEN_BODY
}
int r3d_gdn_conv_update_launch(const void* x, long long xpitch, const void* wgt, const void* bias,
void* cstate, long long cs_seq, long long cs_dim, long long cs_tok,
int state_len_max, const void* cache_idx, long long ci_stride,
const void* num_accepted, void* q, void* k, void* v,
const void* cu, int N, int H, int Hg, int width, int max_query_len,
hipStream_t stream)
{
const int units = 2 * Hg + H;
int hpb = 8;
while (hpb > 1 && (Hg % hpb || H % hpb)) hpb >>= 1;
while (hpb > 1 && (long)N * (units / hpb) < 256) hpb >>= 1;
dim3 grid(N, units / hpb), blk(hpb * 32);
#define CU_LAUNCH(P) \
R3D_KLAUNCH(R3D_KNAME((r3d_gdn_conv_update_kernel<P>)), grid, blk, stream, \
(const unsigned short*)x, xpitch, (const unsigned short*)wgt, \
(const unsigned short*)bias, (unsigned short*)cstate, cs_seq, cs_dim, \
cs_tok, state_len_max, (const int*)cache_idx, ci_stride, \
(const int*)num_accepted, (unsigned short*)q, (unsigned short*)k, \
(unsigned short*)v, (const int*)cu, H, Hg, max_query_len)
switch (hpb) {
case 8: CU_LAUNCH(8); break;
case 4: CU_LAUNCH(4); break;
case 2: CU_LAUNCH(2); break;
default: CU_LAUNCH(1); break;
}
#undef CU_LAUNCH
return (int)hipGetLastError();
}
/* A contiguous cu (rank 1, >= 2) gives the sequence count; -1 on refusal. */
static int seqs_of(const RadTensor* cu, int* out)
{
if (!cu || cu->rank != 1 || cu->shape[0] < 2) return -1;
if (!r3d_contig(cu)) return -2;
*out = (int)(cu->shape[0] - 1);
return 0;
}
} // namespace
/* ------------------------------------------------------------------ the plugin ABI: conv prep */
enum { CP_X = 0, CP_W, CP_B, CP_ALOG, CP_DTB, CP_CSTATE, CP_CU, CP_A, CP_BGATE, CP_CACHE_IDX,
CP_HAS_INIT, CP_Q, CP_K, CP_V, CP_G, CP_BETA };
extern "C" int r3d_rad_gdn_conv_prep(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, CP_X);
const RadTensor* w = r3d_opt(a, CP_W);
const RadTensor* b = r3d_opt(a, CP_B);
const RadTensor* alog = r3d_opt(a, CP_ALOG);
const RadTensor* dtb = r3d_opt(a, CP_DTB);
const RadTensor* cst = r3d_opt(a, CP_CSTATE);
const RadTensor* cu = r3d_opt(a, CP_CU);
const RadTensor* q = r3d_opt(a, CP_Q);
const RadTensor* k = r3d_opt(a, CP_K);
const RadTensor* v = r3d_opt(a, CP_V);
const RadTensor* g = r3d_opt(a, CP_G);
const RadTensor* beta = r3d_opt(a, CP_BETA);
const RadTensor* ta = r3d_opt(a, CP_A);
const RadTensor* tb = r3d_opt(a, CP_BGATE);
const RadTensor* cidx = r3d_opt(a, CP_CACHE_IDX);
const RadTensor* hin = r3d_opt(a, CP_HAS_INIT);
if (!r3d_p(x) || !r3d_p(w) || !r3d_p(alog) || !r3d_p(dtb) || !r3d_p(cst) || !r3d_p(cu) ||
!r3d_wp(q) || !r3d_wp(k) || !r3d_wp(v) || !r3d_wp(g) || !r3d_wp(beta))
return R3D_NO(RAD_E_INVAL);
// Optional in the schema but required here: the kernel dereferences all three.
if (!r3d_p(ta) || !r3d_p(tb) || !r3d_p(cidx)) return R3D_NO(RAD_E_INVAL);
if (x->rank < 2 || q->rank != 3 || k->rank != 3 || v->rank != 3) return R3D_NO(RAD_E_SHAPE);
if (g->rank != 2 || beta->rank != 2 || cst->rank != 3 || ta->rank != 2) return R3D_NO(RAD_E_SHAPE);
int N = 0;
if (seqs_of(cu, &N) != 0) return R3D_NO(RAD_E_SHAPE);
const long long xpitch = r3d_row_pitch(x);
if (xpitch < 0) return R3D_NO(RAD_E_STRIDE);
const long long ab_stride = r3d_row_pitch(ta);
if (ab_stride < 0) return R3D_NO(RAD_E_STRIDE);
if (r3d_row_pitch(tb) != ab_stride) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(q) || !r3d_contig(k) || !r3d_contig(v) || !r3d_contig(g) ||
!r3d_contig(beta) || !r3d_contig(w) || !r3d_contig(alog) || !r3d_contig(dtb))
return R3D_NO(RAD_E_STRIDE);
if (cidx->rank < 1) return R3D_NO(RAD_E_SHAPE);
const long long T = q->shape[0];
const long long Hg = q->shape[1];
const long long K = q->shape[2];
const long long H = v->shape[1];
const long long V = v->shape[2];
if (k->shape[0] != T || k->shape[1] != Hg || k->shape[2] != K) return R3D_NO(RAD_E_SHAPE);
if (v->shape[0] != T) return R3D_NO(RAD_E_SHAPE);
if (g->shape[0] != T || g->shape[1] != H) return R3D_NO(RAD_E_SHAPE);
if (beta->shape[0] != T || beta->shape[1] != H) return R3D_NO(RAD_E_SHAPE);
if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE);
if (K != kHD || V != kHD) return R3D_NO(RAD_E_SHAPE);
const int width = (int)r3d_geti_or(a, "conv_width", kW);
if (width != kW) return R3D_NO(RAD_E_SHAPE);
const float thr = (float)r3d_getf(a, "softplus_thr", 20.0);
if ((float)r3d_getf(a, "l2_eps", 1e-6) != 1e-6f) return R3D_NO(RAD_E_UNSUPPORTED);
const int ab_is_bf16 = (ta->dtype == RAD_BF16) ? 1 : 0;
if (tb->dtype != ta->dtype) return R3D_NO(RAD_E_DTYPE);
if (!ab_is_bf16 && ta->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_bf16(x) || !r3d_is_bf16(w) || !r3d_is_bf16(cst) ||
!r3d_is_bf16(q) || !r3d_is_bf16(k) || !r3d_is_bf16(v) ||
!r3d_is_f32(alog) || !r3d_is_f32(dtb) || !r3d_is_f32(g) || !r3d_is_f32(beta))
return R3D_NO(RAD_E_DTYPE);
return r3d_gdn_conv_prep_launch(r3d_p(x), xpitch, r3d_p(w), b ? r3d_p(b) : nullptr, r3d_wp(cst),
cst->stride[0], cst->stride[1], cst->stride[2],
r3d_p(cidx), cidx->stride[0], hin ? r3d_p(hin) : nullptr,
hin && (hin->dtype == RAD_I32 || hin->dtype == RAD_U32),
r3d_p(ta), r3d_p(tb), ab_stride, ab_is_bf16,
r3d_p(alog), r3d_p(dtb), r3d_wp(q), r3d_wp(k), r3d_wp(v),
r3d_wp(g), r3d_wp(beta), r3d_p(cu),
N, (int)T, (int)H, (int)Hg, width, thr, (hipStream_t)s);
}
/* ------------------------------------------------------------------ the plugin ABI: conv update */
enum { CU_X = 0, CU_W, CU_B, CU_CSTATE, CU_SIDX, CU_NACC, CU_CU, CU_Q, CU_K, CU_V };
extern "C" int r3d_rad_gdn_conv_update(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, CU_X);
const RadTensor* w = r3d_opt(a, CU_W);
const RadTensor* b = r3d_opt(a, CU_B);
const RadTensor* cst = r3d_opt(a, CU_CSTATE);
const RadTensor* sidx = r3d_opt(a, CU_SIDX);
const RadTensor* nacc = r3d_opt(a, CU_NACC);
const RadTensor* cu = r3d_opt(a, CU_CU);
const RadTensor* q = r3d_opt(a, CU_Q);
const RadTensor* k = r3d_opt(a, CU_K);
const RadTensor* v = r3d_opt(a, CU_V);
if (!r3d_p(x) || !r3d_p(w) || !r3d_p(cst) || !r3d_p(sidx) || !r3d_p(cu) ||
!r3d_wp(q) || !r3d_wp(k) || !r3d_wp(v))
return R3D_NO(RAD_E_INVAL);
if (cst->rank != 3 || q->rank != 3 || k->rank != 3 || v->rank != 3) return R3D_NO(RAD_E_SHAPE);
if (sidx->rank < 1) return R3D_NO(RAD_E_SHAPE);
int N = 0;
if (seqs_of(cu, &N) != 0) return R3D_NO(RAD_E_SHAPE);
const long long xpitch = r3d_row_pitch(x);
if (xpitch < 0) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(q) || !r3d_contig(k) || !r3d_contig(v) || !r3d_contig(w))
return R3D_NO(RAD_E_STRIDE);
const long long T = q->shape[0];
const long long Hg = q->shape[1];
const long long K = q->shape[2];
const long long H = v->shape[1];
const long long V = v->shape[2];
if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE);
if (v->shape[0] != T || k->shape[0] != T) return R3D_NO(RAD_E_SHAPE);
if (K != kHD || V != kHD) return R3D_NO(RAD_E_SHAPE);
if (!r3d_is_bf16(x) || !r3d_is_bf16(w) || !r3d_is_bf16(cst) ||
!r3d_is_bf16(q) || !r3d_is_bf16(k) || !r3d_is_bf16(v))
return R3D_NO(RAD_E_DTYPE);
const int width = (int)r3d_geti_or(a, "conv_width", kW);
const long long state_len_max = cst->shape[2];
const long long mql = state_len_max - (width - 2);
if (width != kW || mql < 1) return R3D_NO(RAD_E_SHAPE);
return r3d_gdn_conv_update_launch(r3d_p(x), xpitch, r3d_p(w), b ? r3d_p(b) : nullptr,
r3d_wp(cst), cst->stride[0], cst->stride[1], cst->stride[2],
(int)state_len_max, r3d_p(sidx), sidx->stride[0],
nacc ? r3d_p(nacc) : nullptr, r3d_wp(q), r3d_wp(k), r3d_wp(v),
r3d_p(cu), N, (int)H, (int)Hg, width, (int)mql,
(hipStream_t)s);
}
+183
View File
@@ -0,0 +1,183 @@
/* r3d_gdn_gated_norm_had_quant_i8.hip -- the GDN block's gated RMS norm, block Hadamard and
* per-row int8 quantiser in one pass: out_proj's input on the 48 linear-attention layers (the
* fourth rotated site in a W4A8 layer).
*
* out = x * rsqrt(mean_head(x^2) + eps) * w * silu(z)
*
* Two extents: the RMS is per head (head_dim = 128), while the rotation and the int8 scale are
* per token over the flattened H*128. The reduction is segmented: a head is 128/VPL consecutive
* lanes, and the xor masks below that stay inside one head.
*
* HAD=128 VPL=4 32 lanes/head one head per rotation block
* HAD=256 VPL=8 16 lanes/head two heads per block
* HAD=512 VPL=16 8 lanes/head four heads per block
*
* At width 128 the rotation mixes only within a head; wider widths mix across heads.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_args.h"
#include "r3d_codecs.h"
#include "r3d_fwht.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdint>
namespace {
constexpr int kHEAD = 128; // head_dim
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
__host__ __device__ __forceinline__ int r3d_act_threads(int M, int K)
{
if (M <= 32) return 1024;
const int lim = K >= 8192 ? (1 << 24) : (K >= 4096 ? 120 : 72);
return M <= lim ? 512 : 256;
}
template <int HAD, int THR>
__global__ __launch_bounds__(THR) void r3d_gdn_gated_norm_had_quant_i8_kernel(
const unsigned short* __restrict__ X, const unsigned short* __restrict__ Z,
const float* __restrict__ Wg, signed char* __restrict__ Q, float* __restrict__ S,
int K, long long xrow, long long zrow, int zgrp, int zblk, float eps, float rnorm)
{
constexpr int VPL = HAD / 32, NW = THR / 32;
constexpr int LPH = kHEAD / VPL; // lanes spanned by one head
extern __shared__ float lds[];
float* red = lds + K;
const int row = blockIdx.x;
const unsigned short* x = X + (size_t)row * xrow;
const unsigned short* z = Z + (size_t)row * zrow;
// zgrp != 0: Z is read in place from the interleaved qkvz projection (avoiding a `z_out[:] = z`
// copy per layer): element i is at (i / zblk) * zgrp + (i % zblk). zblk is a multiple of HAD,
// so a rotation block never straddles a group.
const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
float m = 0.f;
for (int blk = wave; blk < K / HAD; blk += NW) {
const int base = blk * HAD + lane * VPL;
const int zbase = zgrp ? (base / zblk) * zgrp + (base % zblk) : base;
float v[VPL];
float ss = 0.f;
#pragma unroll
for (int j = 0; j < VPL; ++j) {
v[j] = bf16_to_f32(x[base + j]);
ss += v[j] * v[j];
}
// segmented: masks below LPH never cross a head
ss = r3d_xor_sum<LPH>(ss);
const float rms = __frsqrt_rn(ss * (1.f / (float)kHEAD) + eps);
#pragma unroll
for (int j = 0; j < VPL; ++j) {
const float g = bf16_to_f32(z[zbase + j]);
v[j] = v[j] * rms * Wg[(base + j) & (kHEAD - 1)] * (g / (1.f + __expf(-g)));
}
r3d_fwht_wave<HAD>(v, lane);
#pragma unroll
for (int j = 0; j < VPL; ++j) {
lds[base + j] = v[j];
m = fmaxf(m, fabsf(v[j]));
}
}
m = wave_max(m);
if (lane == 0) red[wave] = m;
R3D_BARRIER();
m = red[0];
#pragma unroll
for (int i = 1; i < NW; ++i) m = fmaxf(m, red[i]);
m = fmaxf(m, 1e-8f);
const float inv = 127.f / m;
if (threadIdx.x == 0) S[row] = m * rnorm / 127.f;
signed char* q = Q + (size_t)row * K;
for (int i = threadIdx.x; i < K; i += THR) {
const int st = i >> 4, j = i & 15;
const int sr = (st << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
const int t = __float2int_rn(lds[sr] * inv);
q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
}
int r3d_gdn_gated_norm_hq_i8_launch(const void* x, const void* z, const void* w, void* q,
void* sc, int M, int K, long long xrow, long long zrow,
int zgrp, int zblk, int had, float eps, hipStream_t stream)
{
const float rn = 1.f / sqrtf((float)had);
const long long xr = xrow ? xrow : K, zr = zrow ? zrow : K;
const int thr = r3d_act_threads(M, K);
const size_t shmem = (size_t)K * sizeof(float) + (size_t)(thr / 32) * sizeof(float);
if (shmem > 65536) return -3;
#define R3D_GNHQ_LAUNCH(H, T) \
R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_gated_norm_had_quant_i8_kernel<H, T>)), dim3((unsigned)M), \
dim3(T), shmem, stream, (const unsigned short*)x, (const unsigned short*)z, \
(const float*)w, (signed char*)q, (float*)sc, K, xr, zr, zgrp, zblk, eps, rn)
#define R3D_GNHQ_T(H) switch (thr) { \
case 256: R3D_GNHQ_LAUNCH(H, 256); break; \
case 512: R3D_GNHQ_LAUNCH(H, 512); break; \
case 1024: R3D_GNHQ_LAUNCH(H, 1024); break; \
default: return -2; }
switch (had) {
case 128: R3D_GNHQ_T(128); break;
case 256: R3D_GNHQ_T(256); break;
default: R3D_GNHQ_T(512); break;
}
#undef R3D_GNHQ_T
#undef R3D_GNHQ_LAUNCH
return (int)hipGetLastError();
}
} // namespace
/* ------------------------------------------------------------------ the plugin ABI */
enum { GNH_X = 0, GNH_Z, GNH_W, GNH_Q, GNH_S };
extern "C" int r3d_rad_gdn_gated_norm_hq_i8(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, GNH_X);
const RadTensor* z = r3d_opt(a, GNH_Z);
const RadTensor* w = r3d_opt(a, GNH_W);
const RadTensor* q = r3d_opt(a, GNH_Q);
const RadTensor* sc = r3d_opt(a, GNH_S);
if (!r3d_p(x) || !r3d_p(z) || !r3d_p(w) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (!r3d_is_bf16(x) || !r3d_is_bf16(z) || !r3d_is_f32(w)) return R3D_NO(RAD_E_DTYPE);
if (q->dtype != RAD_I8 && q->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(sc)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(q) || !r3d_contig(sc) || !r3d_contig(w)) return R3D_NO(RAD_E_STRIDE);
long long M = 0, K = 0;
if (r3d_rows_of(x, &M, &K) != 0) return R3D_NO(RAD_E_SHAPE);
const long long head = r3d_geti_or(a, "head_dim", kHEAD);
if (head != kHEAD) return R3D_NO(RAD_E_SHAPE);
if (K % kHEAD) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(w) != head) return R3D_NO(RAD_E_SHAPE); // wgain is 128 floats, not K
const long long had = r3d_geti_or(a, "group", 0);
if (had != 128 && had != 256 && had != 512) return R3D_NO(RAD_E_SHAPE);
// A rotation block cannot straddle a tensor-parallel shard boundary.
if (K % had) return R3D_NO(RAD_E_SHAPE);
const long long xrow = r3d_row_pitch(x);
const long long zrow = r3d_row_pitch(z);
if (xrow < 0 || zrow < 0) return R3D_NO(RAD_E_STRIDE);
// Interleaved-gate layout (see the kernel); zgrp 0 means contiguous.
const long long zgrp = r3d_geti_or(a, "zgrp", 0);
const long long zblk = r3d_geti_or(a, "zblk", 0);
if (zgrp && (zblk % had || zblk < had || zgrp < zblk)) return R3D_NO(RAD_E_INVAL);
const float eps = (float)r3d_getf(a, "eps", 1e-6);
return r3d_gdn_gated_norm_hq_i8_launch(r3d_p(x), r3d_p(z), r3d_p(w), r3d_wp(q), r3d_wp(sc),
(int)M, (int)K, xrow, zrow, (int)zgrp, (int)zblk,
(int)had, eps, (hipStream_t)s);
}
+175
View File
@@ -0,0 +1,175 @@
/* r3d_gdn_gated_rmsnorm_h128.hip -- the gated RMS norm a gated-delta-net layer applies to its
* own output before the output projection:
*
* out[r][d] = x[r][d] * rsqrt(mean_d(x[r][:]^2) + eps) * w[d] * act(z[r][d])
*
* one row per (token, head), 128 wide; act is silu (the default) or sigmoid. Replaces FLA's
* rmsnorm_fn (mamba/ops/layernorm_gated). A separate row because the chunked scan's workgroup
* owns only 64 of a row's 128 v channels; the decode recurrent update owns whole rows and fuses
* this into its epilogue.
*
* One wave per row, four channels per lane: a barrier-free five-shuffle wave sum, and one 8-byte
* access per lane for each load and the store.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_args.h"
#include "r3d_codecs.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace {
constexpr int kD = 128; // channels per row
constexpr int kDPL = 4; // channels per lane
constexpr int kNW = 8; // rows in flight per workgroup
constexpr int kNTHR = kNW * 32;
__device__ __forceinline__ float gn_act(float z, int kind)
{
const float s = 1.0f / (1.0f + __expf(-z));
return kind ? s : z * s; // 1 = sigmoid, 0 = silu / swish
}
template <int ACT>
__global__ __launch_bounds__(kNTHR)
void r3d_gdn_gated_rmsnorm_kernel(const unsigned short* __restrict__ x,
const unsigned short* __restrict__ z,
const float* __restrict__ w,
unsigned short* __restrict__ o,
long long rows, long long xrow, long long zrow,
long long orow, long long zheads, long long ztok, float eps)
{
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
const long long r = (long long)blockIdx.x * kNW + warp;
if (r >= rows) return;
const int d0 = lane * kDPL;
// The gate may be a column view of a fused [q|k|v|z] projection: within a token the `zheads`
// gate rows are `zrow` apart and the next token is `ztok` away. zheads <= 0 is the flat case.
const long long zoff = zheads > 0 ? (r / zheads) * ztok + (r % zheads) * zrow : r * zrow;
const ushort4 xv = *(const ushort4*)(x + r * xrow + d0);
float v[kDPL] = {bf16_to_f32(xv.x), bf16_to_f32(xv.y), bf16_to_f32(xv.z), bf16_to_f32(xv.w)};
float ss = 0.0f;
#pragma unroll
for (int c = 0; c < kDPL; ++c) ss += v[c] * v[c];
ss = wave_sum(ss);
const float scale = __frsqrt_rn(ss * (1.0f / kD) + eps);
const ushort4 zv = *(const ushort4*)(z + zoff + d0);
const float zz[kDPL] = {bf16_to_f32(zv.x), bf16_to_f32(zv.y),
bf16_to_f32(zv.z), bf16_to_f32(zv.w)};
const float4 ww = *(const float4*)(w + d0);
const float wv[kDPL] = {ww.x, ww.y, ww.z, ww.w};
unsigned short out[kDPL];
#pragma unroll
for (int c = 0; c < kDPL; ++c)
out[c] = f32_to_bf16(v[c] * scale * wv[c] * gn_act(zz[c], ACT));
*(ushort4*)(o + r * orow + d0) = make_ushort4(out[0], out[1], out[2], out[3]);
}
int r3d_gdn_gated_rmsnorm_launch(const void* x, const void* z, const void* w, void* o,
long long rows, long long xrow, long long zrow, long long orow,
long long zheads, long long ztok, int act, float eps,
hipStream_t stream)
{
dim3 grid((unsigned)((rows + kNW - 1) / kNW)), blk(kNTHR);
if (act)
R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_gated_rmsnorm_kernel<1>)), grid, blk, 0, stream,
(const unsigned short*)x, (const unsigned short*)z, (const float*)w,
(unsigned short*)o, rows, xrow, zrow, orow, zheads, ztok, eps);
else
R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_gated_rmsnorm_kernel<0>)), grid, blk, 0, stream,
(const unsigned short*)x, (const unsigned short*)z, (const float*)w,
(unsigned short*)o, rows, xrow, zrow, orow, zheads, ztok, eps);
return (int)hipGetLastError();
}
} // namespace
/* ------------------------------------------------------------------ the raw entry */
extern "C" int r3d_gdn_gated_rmsnorm_h128(long x, long z, long w, long o, long long rows,
long long xrow, long long zrow, long long orow,
long long zheads, long long ztok, int width,
float eps, int act, long stream)
{
if (!x || !z || !w || !o) return -1;
if (width != kD || rows < 1) return -2;
return r3d_gdn_gated_rmsnorm_launch((const void*)x, (const void*)z, (const void*)w, (void*)o,
rows, xrow, zrow, orow, zheads, ztok, act, eps,
(hipStream_t)stream);
}
/* ------------------------------------------------------------------ the plugin ABI */
enum { GN_X = 0, GN_Z, GN_W, GN_O };
/* The (token, head) row pitch of an operand whose last axis is `width`: the stride of the axis
* above it (the head axis), -1 when the layout does not put consecutive rows that far apart. */
static long long gn_row_pitch(const RadTensor* t, long long width)
{
if (!t || t->rank < 1) return -1;
if (t->shape[t->rank - 1] == width) {
if (t->stride[t->rank - 1] != 1) return -1;
return t->rank >= 2 ? t->stride[t->rank - 2] : width;
}
return r3d_contig(t) ? width : -1;
}
extern "C" int r3d_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, GN_X);
const RadTensor* z = r3d_opt(a, GN_Z);
const RadTensor* w = r3d_opt(a, GN_W);
const RadTensor* o = r3d_opt(a, GN_O);
if (!r3d_p(x) || !r3d_p(z) || !r3d_p(w) || !r3d_wp(o)) return R3D_NO(RAD_E_INVAL);
if (!r3d_is_bf16(x) || !r3d_is_bf16(z) || !r3d_is_bf16(o) || !r3d_is_f32(w))
return R3D_NO(RAD_E_DTYPE);
if (x->rank < 2 || z->rank < 2 || o->rank < 2) return R3D_NO(RAD_E_SHAPE);
if (!r3d_contig(w)) return R3D_NO(RAD_E_STRIDE);
// One row is one (token, head). x and out are [tokens, heads, channels] (rank 3, as the chunk
// scan requires) while the gate may be the flat [tokens, heads*channels] projection. So the
// width comes from `channels` (or x's last axis), the row count from x, and each operand's
// pitch between consecutive (token, head) rows is read per its shape.
const long long width = r3d_geti_or(a, "channels", x->shape[x->rank - 1]);
if (width <= 0 || r3d_numel(x) % width) return R3D_NO(RAD_E_SHAPE);
const long long rows = r3d_numel(x) / width;
if (r3d_numel(z) < rows * width || r3d_numel(o) < rows * width) return R3D_NO(RAD_E_SHAPE);
const long long xrow = gn_row_pitch(x, width);
const long long orow = gn_row_pitch(o, width);
if (xrow < 0 || orow < 0) return R3D_NO(RAD_E_STRIDE);
// The gate may also be a column slice of a wider [q|k|v|z] row (fp8 delta net): heads are
// `width` apart within a token and tokens are the slice's stride apart, so the kernel also
// takes the head count. zheads stays 0 for the flat layouts.
long long zrow = gn_row_pitch(z, width), zheads = 0, ztok = 0;
if (zrow < 0 && z->rank == 2 && z->stride[1] == 1 && z->shape[1] % width == 0) {
zheads = z->shape[1] / width;
ztok = z->stride[0];
zrow = width;
if (zheads <= 0 || rows % zheads) return R3D_NO(RAD_E_SHAPE);
if (x->rank >= 3 && x->shape[x->rank - 2] != zheads) return R3D_NO(RAD_E_SHAPE);
}
if (zrow < 0) return R3D_NO(RAD_E_STRIDE);
const float eps = (float)r3d_getf(a, "eps", 1e-6);
const int act = r3d_act_code(a, "act", nullptr, -1);
if (act != 0 && act != 1) return R3D_NO(RAD_E_INVAL);
return r3d_gdn_gated_rmsnorm_launch(r3d_p(x), r3d_p(z), r3d_p(w), r3d_wp(o),
rows, xrow, zrow, orow, zheads, ztok,
act, eps, (hipStream_t)s);
}
+475
View File
@@ -0,0 +1,475 @@
/* r3d_gdn_kkt_solve_c64.hip -- the gated-delta-net chunk preamble in one kernel:
*
* A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1} per chunk of 64
*
* The FLA chunk_scaled_dot_kkt_fwd + solve_tril pair, fused: the gram stays in LDS and only the
* bf16 inverse is stored. The gram is computed once per k head, not per v head: K K^T does not
* depend on beta or g, so one workgroup owns a (chunk, k head) and applies each v head's scales
* to it. The decay is applied per element as e^{g_i-g_j}, not split about a per-chunk reference:
* each half of e^{g_i-c} * e^{c-g_j} can overflow fp32 on its own, and the exponent is always
* <= 0 here (g decreases along the chunk and only i > j is kept).
*
* The inverse is blocked 16 -> 32 -> 64. The four diagonal blocks use fp32 forward substitution
* (one wave each, one lane per column), cheaper than a WMMA Neumann series at this size and exact
* in fp32, as in FLA. The 32-merges and the 64-merge are wave-matrix, using
*
* [[P, 0], [R, Q]]^-1 = [[P^-1, 0], [-Q^-1 R P^-1, Q^-1]]
*
* mma(X, Y) computes X . Y^T from two k-contiguous operands, so a left operand is row-major and a
* right operand is stored transposed. The intermediates are staged transposed in the 32x32
* scratch; the final inverse is assembled row-major for the HBM store.
*
* ---- the tile map (the port's one structural change) ---------------------------------------
*
* The source row was written for the wave-matrix ISA of the card it was probed on, whose
* 16x16x16 fragment map differs from this card's. This card's map (probed in the bf16 GEMM row,
* r3d_gemm_bf16_nt_m16_wmma.hip):
*
* A fragment: lane L holds row L % 16 of the tile, the 16 k contiguous
* B fragment: lane L holds column L % 16 of the tile, the 16 k contiguous
* C/D: lane L, element e holds D[2e + L / 16][L % 16], eight f32 a lane
*
* so the fragment loads are the bf16 GEMM row's 32-byte reads, and every accumulator store that
* the source row made as one 16-byte vector is here eight scalar bf16 stores along the map's
* stride-2 axis. The transposed-operand reads (fragT) keep the source's lane-to-row assignment,
* which the two ISAs share.
*
* The blocked inverse reads the blocks it overwrites before writing them, with barriers between
* stages, so one 64x64 buffer plus a 32x32 scratch carries the whole solve: 11 KiB of LDS.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_args.h"
#include "r3d_codecs.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace {
constexpr int kBT = 64; // chunk
constexpr int kKD = 128; // head_k
constexpr int kNBK = 4; // 16x16 blocks per chunk edge
constexpr int kAP = 68; // row pitch of the [BT][BT] buffers, in shorts: 8-byte aligned
// for the store, and 16 rows still cover every bank
constexpr int kNW = 4;
constexpr int kNTHR = kNW * 32;
constexpr int kNTILE = 10; // upper-triangular tiles of a 4x4 tiling
constexpr int kMAXT = (kNTILE + kNW - 1) / kNW;
using v8f = float __attribute__((ext_vector_type(8)));
using v16short = short __attribute__((ext_vector_type(16)));
/* One 16x16x16 tile, f32 accumulate. */
__device__ __forceinline__ v8f mmab(const v16short& a, const v16short& b, const v8f& c)
{
return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);
}
/* A/B fragment from a row pointer already advanced to this lane's row and half-K: the 16 k
* contiguous, 32 bytes, two 16-byte reads. The row pitches are multiples of 4 shorts and the
* kbase is a multiple of 16, so the 16-byte alignment the reads need holds. */
__device__ __forceinline__ v16short fragP(const unsigned short* p)
{
// The GEMM row's exact form: load a uint4, bit-cast it. Loading the ext-vector type
// directly lowers differently on this backend and corrupts the fragment.
union { r3d_u32x4 w[2]; v16short f; } u;
u.w[0] = __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
u.w[1] = __builtin_bit_cast(r3d_u32x4, *(const uint4*)(p + 8));
return u.f;
}
/* Global fragment off a 32-bit element offset split from a uniform base: the immediate-offset
* form the bf16 GEMM row's note describes. The row is clamped at the call site so a partial last
* chunk cannot read past the tensor (those rows are discarded downstream). */
__device__ __forceinline__ v16short fragGo(const unsigned short* base, unsigned off)
{
return fragP(base + off);
}
/* K-contiguous fragment: src[idx][k], row pitch `pitch` (in elements). */
__device__ __forceinline__ v16short frag(const unsigned short* src, int pitch, int base,
int kbase, int lane)
{
return fragP(src + (size_t)(base + (lane & 15)) * pitch + kbase);
}
/* Same fragment but the source is stored transposed: src[k][idx]. Sixteen scalar reads. */
__device__ __forceinline__ v16short fragT(const unsigned short* src, int pitch, int base,
int kbase, int lane)
{
const int idx = base + (lane & 15);
union { unsigned short h[16]; v16short f; } u;
#pragma unroll
for (int e = 0; e < 16; ++e)
u.h[e] = src[(size_t)(kbase + e) * pitch + idx];
return u.f;
}
/* C[mt*16 .. ][nt*16 .. ] += A[M][K] @ B[N][K]^T over KSTEP 16-wide steps. */
template <int KSTEP>
__device__ __forceinline__ v8f gemm16(const unsigned short* A, int Ap, int mt,
const unsigned short* B, int Bp, int nt,
int lane, v8f acc)
{
#pragma unroll
for (int s = 0; s < KSTEP; ++s)
acc = mmab(frag(A, Ap, mt * 16, s * 16, lane), frag(B, Bp, nt * 16, s * 16, lane), acc);
return acc;
}
/* A block barrier the backend cannot move; see the GEMM rows' note. */
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
/* The chunk's buffers. One 64x64 buffer plus a 32x32 scratch. ST is a staging line: every
* scattered store out of a wmma accumulator goes through it first. A scattered store issued
* directly from the accumulator registers is miscompiled on this backend (the wmma result is
* corrupted by the store's address arithmetic); a contiguous lane-major store into LDS, a
* barrier, and the scatter out of LDS is the proven safe form. */
struct KkSmem {
unsigned short A[kBT][kAP]; // A on the way in, its inverse on the way out
unsigned short TMP[32][36]; // one 32x32 intermediate, transposed
float ST[kNTHR * 8]; // one gram round (128 threads x 8), contiguous per thread
float gb[kBT], bt[kBT]; // the chunk's gate cumsum and beta, per token
};
/* (mt, nt) of upper-triangular tile ti, computed with wave-uniform arithmetic instead of a
* table load. */
__device__ __forceinline__ void kkt_tile(int ti, int* mt, int* nt)
{
int m = 0, n = ti;
while (n >= kNBK - m) { n -= (kNBK - m); ++m; }
*mt = m; *nt = n + m;
}
template <int HG_RATIO>
__global__ __launch_bounds__(kNTHR)
void r3d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k,
const float* __restrict__ beta,
const float* __restrict__ g,
unsigned short* __restrict__ Ao,
const int* __restrict__ cu,
int N, int H, int Hg)
{
__shared__ KkSmem s;
int tid = threadIdx.x;
asm volatile("" : "+v"(tid)); // pin the hw thread-id vreg before the allocator can reuse it
const int lane = tid & 31, warp = tid >> 5;
const int lo = lane & 15, hi = lane >> 4;
const int hg = blockIdx.y;
// Resolve the flat chunk id to (sequence, chunk). The grid is an upper bound on the chunk
// count, so surplus workgroups exit here; this saves the host a device-to-host sync to size
// the grid exactly.
int n = -1, t0 = 0, bos = 0, rows = 0;
{
int acc = 0, want = blockIdx.x;
for (int i = 0; i < N; ++i) {
const int b = cu[i], e = cu[i + 1];
const int nc = (e - b + kBT - 1) / kBT;
if (want < acc + nc) { n = i; bos = b; t0 = (want - acc) * kBT;
rows = std::min(kBT, e - b - t0); break; }
acc += nc;
}
if (n < 0) return;
}
// ---- zero A once: the parts no store reaches (the upper tiles) are the same for every head.
// 16-byte stores (the buffer is 8704 bytes, 16-byte aligned).
for (int i = tid; i < kBT * kAP / 8; i += kNTHR) ((uint4*)&s.A[0][0])[i] = make_uint4(0, 0, 0, 0);
// ---- the gram, once for all HG_RATIO v heads of this k head -----------------------------
const unsigned short* kp = k + ((size_t)(bos + t0) * Hg + hg) * kKD;
const unsigned krow = (unsigned)(Hg * kKD);
// The gram, once for all v heads: tile (mt, nt) of P is staged lane-contiguous into ST and
// then parked in A's upper triangle, where A is zero. An off-diagonal tile goes into the
// (mt, nt) slot; a diagonal tile goes straight into its (nt, mt) target slot, so the
// per-head pass below is an in-place scale for it (no cross-lane read/write on one tile).
#pragma unroll
for (int t = 0; t < kMAXT; ++t) {
const int ti = warp + t * kNW;
v8f P = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
if (ti < kNTILE) {
int mt, nt; kkt_tile(ti, &mt, &nt);
// One 32-bit offset per operand row, hoisted out of the k loop.
const unsigned om = (unsigned)(std::min(mt * 16 + (lane & 15), rows - 1)) * krow;
const unsigned on = (unsigned)(std::min(nt * 16 + (lane & 15), rows - 1)) * krow;
#pragma unroll
for (int sk = 0; sk < kKD / 16; ++sk) {
const v16short fa = fragGo(kp, om + sk * 16);
const v16short fb = fragGo(kp, on + sk * 16);
P = mmab(fa, fb, P);
}
}
#pragma unroll
for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = P[e];
R3D_BARRIER();
if (ti < kNTILE) {
int mt, nt; kkt_tile(ti, &mt, &nt);
#pragma unroll
for (int e = 0; e < 8; ++e) {
if (mt == nt)
s.A[nt * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]);
else
s.A[mt * 16 + 2 * e + hi][nt * 16 + lo] = f32_to_bf16(s.ST[tid * 8 + e]);
}
}
}
R3D_BARRIER();
for (int hh = 0; hh < HG_RATIO; ++hh) {
const int hv = hg * HG_RATIO + hh;
// ---- per-head gate and beta for this chunk
if (tid < kBT) {
const int t = std::min(tid, rows - 1);
s.gb[tid] = g[(size_t)(bos + t0 + t) * H + hv];
s.bt[tid] = beta[(size_t)(bos + t0 + t) * H + hv];
}
R3D_BARRIER();
// ---- scale, mask and place the gram as the strictly lower half of A -----------------
// Element e of tile (mt, nt) lands at A[i = nt*16 + lo][j = mt*16 + 2e + hi], the lower
// triangle when i > j. Off-diagonal tiles were parked transposed at A[j][i], so the
// scale reads that slot; diagonal tiles are scaled in place.
#pragma unroll
for (int t = 0; t < kMAXT; ++t) {
const int ti = warp + t * kNW;
if (ti < kNTILE) {
int mt, nt; kkt_tile(ti, &mt, &nt);
const int i = nt * 16 + lo; // row of A
const bool live = (i < rows);
const float bi = live ? s.bt[i] : 0.0f;
const float gi = live ? s.gb[i] : 0.0f;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int j = mt * 16 + 2 * e + hi;
const float pv = (mt == nt) ? bf16_to_f32(s.A[i][j])
: bf16_to_f32(s.A[j][i]);
// For a live row, i > j gives g_i <= g_j, so the exponent is never positive.
// Padding rows and columns must be masked to -inf: with gi = 0 the exponent
// -gb[j] is large and positive, 0 * inf = NaN, and the WMMA merges in the
// blocked inverse would spread it into live rows.
const float d = (live && i > j && j < rows) ? (gi - s.gb[j]) : -INFINITY;
s.A[i][j] = f32_to_bf16(bi * __expf(d) * pv);
}
}
}
R3D_BARRIER();
// ---- 1. the four diagonal blocks, by fp32 forward substitution ----------------------
// D = (I + N)^-1 solves D = I - N D row by row. Lane l owns column l of D, so the dot
// product over j < i is in 16 registers and N[i][j] is a broadcast LDS read.
for (int p = warp; p < kNBK; p += kNW) {
const int b0 = p * 16;
float d[16];
#pragma unroll
for (int i = 0; i < 16; ++i) {
float acc = 0.0f;
#pragma unroll
for (int j = 0; j < 16; ++j)
if (j < i) acc += bf16_to_f32(s.A[b0 + i][b0 + j]) * d[j];
d[i] = ((lo == i) ? 1.0f : 0.0f) - acc;
}
if (lane < 16) {
#pragma unroll
for (int i = 0; i < 16; ++i) s.A[b0 + i][b0 + lo] = f32_to_bf16(d[i]);
}
}
R3D_BARRIER();
// ---- 2. the two 32-merges: M10 = -D1 A10 D0 -----------------------------------------
for (int blk = warp; blk < 2; blk += kNW) {
const int r0 = blk * 32; // 32-block origin
// X = A10 . D0 (left A10 row-major, right D0 transposed)
v8f X = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
const v16short af = frag(&s.A[0][0], kAP, r0 + 16, r0, lane);
X = mmab(af, fragT(&s.A[0][0], kAP, r0, r0, lane), X);
// Stage X lane-contiguous, then scatter it out of ST (see the KkSmem note). The
// stage is transposed for the next product: TMP[n][m] = X[m][n], and element e is
// X[m = 2e + hi][n = lo]. Each of the two merges owns 16 rows of TMP.
#pragma unroll
for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = X[e];
R3D_BARRIER();
#pragma unroll
for (int e = 0; e < 8; ++e)
s.TMP[blk * 16 + lo][2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]);
R3D_BARRIER();
// M10 = -D1 . X (left D1 row-major, in place in A; right X transposed, in TMP)
v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
Y = mmab(frag(&s.A[0][0], kAP, r0 + 16, r0 + 16, lane),
frag(&s.TMP[0][0], 36, blk * 16, 0, lane), Y);
#pragma unroll
for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Y[e];
R3D_BARRIER();
// Element e is A[r0 + 16 + 2e + hi][r0 + lo].
#pragma unroll
for (int e = 0; e < 8; ++e)
s.A[r0 + 16 + 2 * e + hi][r0 + lo] = f32_to_bf16(-s.ST[tid * 8 + e]);
}
R3D_BARRIER();
R3D_BARRIER();
// Flip the sign of the R block with a binary subtraction. In this kernel context the
// compiler drops unary minus on the 64-merge accumulator store, so the overall minus
// of M[32:,:32] = -Q^-1 (R P^-1) is carried by the negated R: the merge computes
// Q^-1 . (-R) . P^-1 and stores it as-is. (Flipping Q^-1 in place instead breaks its
// final value, because the restoring flip is dropped in the same way.)
for (int idx = tid; idx < 32 * 32; idx += kNTHR) {
const int r = 32 + idx / 32, c = idx % 32;
s.A[r][c] = f32_to_bf16(0.0f - bf16_to_f32(s.A[r][c]));
}
R3D_BARRIER();
// ---- 3. the 64-merge: M[32:,:32] = -Q^-1 (R P^-1) -----------------------------------
// Y = R . P^-1, R = A[32:,:32] row-major, P^-1 read transposed out of A[:32,:32]
for (int t = warp; t < 4; t += kNW) {
const int mt = t >> 1, nt = t & 1;
v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
#pragma unroll
for (int sk = 0; sk < 2; ++sk)
Y = mmab(frag(&s.A[0][0], kAP, 32 + mt * 16, sk * 16, lane),
fragT(&s.A[0][0], kAP, nt * 16, sk * 16, lane), Y);
// Stage Y lane-contiguous for the transposed scatter below.
#pragma unroll
for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Y[e];
}
R3D_BARRIER();
// TMP[n][m] = Y[m][n]; element e is Y[m = 2e + hi (within the mt tile)][n = lo
// (within the nt tile)].
for (int t = warp; t < 4; t += kNW) {
const int mt = t >> 1, nt = t & 1;
#pragma unroll
for (int e = 0; e < 8; ++e)
s.TMP[nt * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]);
}
R3D_BARRIER(); // every wave has read R into TMP; now it may be overwritten
// Z = -Q^-1 . Y, Q^-1 = A[32:,32:] row-major, Y transposed = TMP
for (int t = warp; t < 4; t += kNW) {
const int mt = t >> 1, nt = t & 1;
v8f Z = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
#pragma unroll
for (int sk = 0; sk < 2; ++sk)
Z = mmab(frag(&s.A[0][0], kAP, 32 + mt * 16, 32 + sk * 16, lane),
frag(&s.TMP[0][0], 36, nt * 16, sk * 16, lane), Z);
#pragma unroll
for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Z[e];
}
R3D_BARRIER();
for (int t = warp; t < 4; t += kNW) {
const int mt = t >> 1, nt = t & 1;
// Element e is A[32 + mt*16 + 2e + hi][nt*16 + lo]. This wmma instance
// negates its product on this toolchain, so the minus belongs to it:
// store the accumulator as-is.
#pragma unroll
for (int e = 0; e < 8; ++e)
s.A[32 + mt * 16 + 2 * e + hi][nt * 16 + lo] = f32_to_bf16(s.ST[tid * 8 + e]);
}
R3D_BARRIER();
// Clear the upper-triangular parking slots (they still hold gram values) so the
// stored matrix is a clean lower-triangular inverse.
for (int idx = tid; idx < 64 * 64; idx += kNTHR) {
const int r = idx / 64, c = idx % 64;
if (c > r) s.A[r][c] = 0;
}
R3D_BARRIER();
// ---- store: one row of the inverse is 64 bf16, contiguous in HBM ---------------------
{
unsigned short* op = Ao + ((size_t)(bos + t0) * H + hv) * kBT;
const size_t orow = (size_t)H * kBT;
for (int r = tid / 8; r < rows; r += kNTHR / 8) {
const int c8 = (tid & 7) * 8;
*(uint4*)(op + (size_t)r * orow + c8) = *(const uint4*)(&s.A[r][c8]);
}
}
if (hh + 1 < HG_RATIO) R3D_BARRIER();
}
}
int r3d_gdn_kkt_solve_launch(const void* k, const void* beta, const void* g, void* A,
const void* cu, int N, int T, int H, int Hg, int K, int chunk,
hipStream_t stream)
{
if (K != kKD || chunk != kBT) return -1;
if (H % Hg) return -2;
const int nchunk_ub = (T + kBT - 1) / kBT + N; // sum of per-sequence chunk counts, bounded
dim3 grid(nchunk_ub, Hg), blk(kNTHR);
#define R3D_KKLAUNCH(R) \
R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_kkt_solve_kernel<R>)), grid, blk, 0, stream, \
(const unsigned short*)k, (const float*)beta, (const float*)g, \
(unsigned short*)A, (const int*)cu, N, H, Hg)
switch (H / Hg) {
case 1: R3D_KKLAUNCH(1); break;
case 2: R3D_KKLAUNCH(2); break;
case 3: R3D_KKLAUNCH(3); break;
case 4: R3D_KKLAUNCH(4); break;
case 6: R3D_KKLAUNCH(6); break;
case 8: R3D_KKLAUNCH(8); break;
default: return -3;
}
#undef R3D_KKLAUNCH
return (int)hipGetLastError();
}
} // namespace
/* ------------------------------------------------------------------ the raw entry */
extern "C" int r3d_gdn_kkt_solve_c64(long k, long beta, long g, long A, long cu,
int N, int T, int H, int Hg, int K, int chunk,
long stream)
{
if (!k || !beta || !g || !A || !cu) return -1;
if (N < 1 || T < 1) return -2;
if (H < 1 || Hg < 1) return -2;
return r3d_gdn_kkt_solve_launch((const void*)k, (const void*)beta, (const void*)g, (void*)A,
(const void*)cu, N, T, H, Hg, K, chunk, (hipStream_t)stream);
}
/* ------------------------------------------------------------------ the plugin ABI */
enum { QK_K = 0, QK_BETA, QK_G, QK_CU, QK_A };
extern "C" int r3d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const RadTensor* kt = r3d_opt(a, QK_K);
const RadTensor* bt = r3d_opt(a, QK_BETA);
const RadTensor* gt = r3d_opt(a, QK_G);
const RadTensor* cu = r3d_opt(a, QK_CU);
const RadTensor* Ao = r3d_opt(a, QK_A);
if (!r3d_p(kt) || !r3d_p(bt) || !r3d_p(gt) || !r3d_p(cu) || !r3d_wp(Ao))
return R3D_NO(RAD_E_INVAL);
if (!r3d_is_bf16(kt) || !r3d_is_f32(bt) || !r3d_is_f32(gt) || !r3d_is_i32(cu) ||
!r3d_is_bf16(Ao))
return R3D_NO(RAD_E_DTYPE);
if (cu->rank != 1 || cu->shape[0] < 2 || !r3d_contig(cu)) return R3D_NO(RAD_E_SHAPE);
const int N = (int)(cu->shape[0] - 1);
const long long T = r3d_dim(kt, 0), Hg = r3d_dim(kt, 1), K = r3d_dim(kt, 2);
const long long H = r3d_dim(bt, 1), chunk = r3d_dim(Ao, 2);
if (r3d_dim(gt, 0) != T || r3d_dim(gt, 1) != H || r3d_dim(bt, 0) != T)
return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(Ao, 0) != T || r3d_dim(Ao, 1) != H) return R3D_NO(RAD_E_SHAPE);
if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE);
if (!r3d_contig(kt) || !r3d_contig(bt) || !r3d_contig(gt) || !r3d_contig(Ao))
return R3D_NO(RAD_E_STRIDE);
return r3d_gdn_kkt_solve_launch(r3d_p(kt), r3d_p(bt), r3d_p(gt), r3d_wp(Ao), r3d_p(cu),
N, (int)T, (int)H, (int)Hg, (int)K, (int)chunk,
(hipStream_t)s);
}
@@ -0,0 +1,350 @@
/* r3d_gdn_recurrent_update_k128_v128.hip -- the gated-delta-net recurrent state update, run by
*
* STATUS: the loop-restructure workaround is in; the value probe is the remaining gate. Three
* compiler bugs were found, two worked around outright and the third around by loop shape:
*
* 1. A DPP shuffle (__shfl_xor) inside the token loop miscompiles: 48 of the 256 threads drop
* out and the row's stores never land. Worked around: every cross-lane exchange (the l2
* norms, the S k / S q closes, the gated-norm wave sum) goes through an __shared__ scratch
* instead of a shuffle.
*
* 2. As a template <int NORM, int ABF16> the kernel's device code is present and the launch
* succeeds, but the kernel never runs (not even a prologue sentinel lands), while a plain
* kernel in the same file runs fine. Worked around: the kernel is plain; norm and ab_bf16
* are runtime parameters.
*
* 3. With both fixes in, the loop was compiler-sensitive: the fused in-loop pair (the state
* update h[j] += u*kk[j] with the on accumulation) plus the third cross-lane exchange and
* the o write produced a kernel whose token loop did not land its o stores, while
* near-identical variants did. The trigger is a specific interaction of the 64-element
* register state, the LDS exchanges and the o write; it has not been reduced to a minimal
* repro. Worked around: the update and the o dot run as separate loops, and the o store is
* volatile. The value probe is the gate.
*
* decode (prefill runs the chunked scan). One kernel for the whole step:
*
* g = -exp(A_log) . softplus(a + dt_bias) beta = sigmoid(b) q, k l2-normalised
* S *= e^g
* u = beta . (v - S k) S += u k^T o = S q
*
* per token, against a paged state cache: the initial state is read from the slot the step's
* tokens leave, and every token writes its own slot. The state stays in registers: one thread
* owns one v row and half its k range, so
*
* * S k and S q are in-lane dot products closed by a single lane<->lane^1 exchange, not a tree;
* * the outer-product update is 64 independent FMAs with no cross-lane traffic;
* * a thread's 64 state elements are contiguous in k, so the load and every store is eight
* 8-byte accesses over one 256-byte run.
*
* The cross-lane exchanges (the l2 norms, the S k and S q closes, the gated-norm wave sum) go
* through LDS, not a shuffle. A DPP shuffle inside the token loop miscompiles on gfx1102: with
* the lane<->lane^1 __shfl_xor in the loop, 48 of the 256 threads drop out and the row's stores
* never land. Routing the same exchange through a __shared__ scratch (one store, a barrier, one
* read of the neighbour) is correct and costs a barrier per token.
*
* This is the non-speculative core: a step's tokens are the cu window (width 1 for a plain
* decode step), the state cache is fp32, and the gated RMS norm is folded into the epilogue
* (z and norm_w present) or omitted. The speculative anchor, the folded decode convolution and
* the folded out-projection quantiser are not part of this row.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_args.h"
#include "r3d_codecs.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdint>
namespace {
constexpr int kK = 128; // head_k
constexpr int kV = 128; // head_v
constexpr int kHK = 64; // k elements per thread (kK / 2)
constexpr int kTHR = kV * 2; // two threads per v row
typedef float ru_f4 __attribute__((ext_vector_type(4)));
template <int NT>
__device__ __forceinline__ void ru_load8(float* d, const float* p)
{
const ru_f4* q = (const ru_f4*)p;
*(ru_f4*)d = NT ? __builtin_nontemporal_load(q) : *q;
*(ru_f4*)(d + 4) = NT ? __builtin_nontemporal_load(q + 1) : *(q + 1);
}
template <int NT>
__device__ __forceinline__ void ru_store8(float* p, const float* d)
{
ru_f4* q = (ru_f4*)p;
if (NT) {
__builtin_nontemporal_store(*(const ru_f4*)d, q);
__builtin_nontemporal_store(*(const ru_f4*)(d + 4), q + 1);
} else {
*q = *(const ru_f4*)d;
*(q + 1) = *(const ru_f4*)(d + 4);
}
}
__device__ __forceinline__ float ru_softplus(float x, float thr)
{
if (x > thr) return x;
return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x))) : __logf(1.0f + __expf(x));
}
template <int ABF16>
__device__ __forceinline__ float ru_ab(const void* p, size_t i)
{
return ABF16 ? bf16_to_f32(((const unsigned short*)p)[i]) : ((const float*)p)[i];
}
__device__ __forceinline__ float ru_act(float z, int kind)
{
const float s = 1.0f / (1.0f + __expf(-z));
return kind ? s : z * s;
}
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
/* norm: 0 = no epilogue norm, 1 = sigmoid, 2 = silu (the row's `act`). ab_bf16: a/b are bf16.
* A plain kernel, not a template: on gfx1102 the template instantiation miscompiles (the device
* code is present and the launch succeeds, but the kernel never runs -- not even a prologue
* sentinel lands, while a plain kernel in the same file runs fine). */
__global__ __launch_bounds__(kTHR)
void r3d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
const unsigned short* __restrict__ k,
const unsigned short* __restrict__ v,
const void* __restrict__ av, const void* __restrict__ bv,
long long ab_stride,
const float* __restrict__ A_log, const float* __restrict__ dt_bias,
float* __restrict__ state,
long long st_slot, long long st_head,
const int* __restrict__ sidx, long long sidx_stride,
const unsigned short* __restrict__ zg, long long zg_pitch,
const float* __restrict__ nw,
unsigned short* __restrict__ o,
const int* __restrict__ cu, int H, int Hg,
float scale, float sp_thr, float neps,
int norm, int ab_bf16)
{
const int tid = threadIdx.x;
const int row = (tid >> 1), half = tid & 1, k0 = half * kHK;
const int n = blockIdx.x, hv = blockIdx.y;
const int bos = cu[n], T = cu[n + 1] - bos;
if (T <= 0) return;
const int hk = hv / (H / Hg);
/* Read early so their latency overlaps the state load. */
const float a_log_h = A_log[hv], dtb = dt_bias[hv];
const float alog = __expf(a_log_h);
float h[kHK];
{
const float* p = state + (size_t)sidx[(size_t)n * sidx_stride] * st_slot
+ (size_t)hv * st_head + (size_t)row * kK + k0;
#pragma unroll
for (int j = 0; j < kHK; j += 8) ru_load8<0>(&h[j], p + j);
}
// LDS scratch for the cross-lane exchanges. ex holds the per-thread value being exchanged
// (lane<->lane^1, or a full wave for the gated norm); wsum holds the eight wave sums.
__shared__ float ex[2 * kTHR];
__shared__ float wsum[kTHR / 32];
for (int t = 0; t < T; ++t) {
const int tok = bos + t;
const unsigned short* qp = q + ((size_t)tok * Hg + hk) * kK + k0;
const unsigned short* kp = k + ((size_t)tok * Hg + hk) * kK + k0;
float qq[kHK], kk[kHK];
for (int j = 0; j < kHK; ++j) { qq[j] = bf16_to_f32(qp[j]); kk[j] = bf16_to_f32(kp[j]); }
// l2 norms: 64 in-lane terms, then one exchange with the lane holding the other half.
// (LDS, not a shuffle -- a DPP in this loop miscompiles on gfx1102.)
float sq = 0.0f, sk = 0.0f;
for (int j = 0; j < kHK; ++j) { sq += qq[j] * qq[j]; sk += kk[j] * kk[j]; }
ex[tid] = sq; ex[tid + kTHR] = sk;
R3D_BARRIER();
sq += ex[tid ^ 1]; sk += ex[tid ^ 1 + kTHR];
const float qs = __frsqrt_rn(sq + 1e-6f) * scale, ks = __frsqrt_rn(sk + 1e-6f);
for (int j = 0; j < kHK; ++j) { qq[j] *= qs; kk[j] *= ks; }
const size_t ab_i = (size_t)tok * ab_stride + hv;
const float ra = ab_bf16 ? bf16_to_f32(((const unsigned short*)av)[ab_i]) : ((const float*)av)[ab_i];
const float rb = ab_bf16 ? bf16_to_f32(((const unsigned short*)bv)[ab_i]) : ((const float*)bv)[ab_i];
const float g = -alog * ru_softplus(ra + dtb, sp_thr);
const float bt = 1.0f / (1.0f + __expf(-rb));
const float eg = __expf(g);
float dot = 0.0f;
for (int j = 0; j < kHK; ++j) { h[j] *= eg; dot += h[j] * kk[j]; }
ex[tid] = dot;
R3D_BARRIER();
dot += ex[tid ^ 1];
const float vraw = bf16_to_f32(v[((size_t)tok * H + hv) * kV + row]);
const float u = (vraw - dot) * bt;
// The outer-product update and the o dot run as separate loops: fused, with the
// third exchange and the o write live, the token loop's o stores stopped landing on
// gfx1102 (a compiler interaction, not reduced to a minimal repro); split, they land.
for (int j = 0; j < kHK; ++j) h[j] += u * kk[j];
float on = 0.0f;
for (int j = 0; j < kHK; ++j) on += h[j] * qq[j];
ex[tid] = on;
R3D_BARRIER();
on += ex[tid ^ 1];
if (norm) {
ex[tid] = (half == 0) ? on * on : 0.0f;
R3D_BARRIER();
const int wave = tid >> 5;
float s = 0.0f;
for (int i = 0; i < 32; ++i) s += ex[wave * 32 + i];
if ((tid & 31) == 0) wsum[wave] = s;
R3D_BARRIER();
float tot = 0.0f;
for (int i = 0; i < kTHR / 32; ++i) tot += wsum[i];
const float sc = __frsqrt_rn(tot * (1.0f / kV) + neps);
const unsigned short zr = zg[(size_t)tok * zg_pitch + (size_t)hv * kV + row];
on *= sc * nw[row] * ru_act(bf16_to_f32(zr), norm);
R3D_BARRIER();
}
const unsigned short ob = f32_to_bf16(on);
if (half == 0) {
// Volatile: the plain store was the one the compiler dropped in the fused form.
volatile unsigned short* ov = o;
ov[((size_t)tok * H + hv) * kV + row] = ob;
}
const int so = sidx[(size_t)n * sidx_stride + t];
if (so >= 0) {
float* p = state + (size_t)so * st_slot + (size_t)hv * st_head
+ (size_t)row * kK + k0;
for (int j = 0; j < kHK; j += 8) ru_store8<0>(p + j, &h[j]);
}
}
}
int r3d_gdn_recurrent_update_launch(const void* q, const void* k, const void* v, const void* a,
const void* b, long long ab_stride, const void* A_log,
const void* dt_bias, void* state, long long st_slot,
long long st_head, const void* sidx, long long sidx_stride,
const void* zg, long long zg_pitch, const void* nw,
void* o, const void* cu, int N, int H, int Hg, int norm,
int ab_bf16, float scale, float sp_thr, float neps,
hipStream_t stream)
{
dim3 grid(N, H), blk(kTHR);
// A plain kernel: norm and ab_bf16 are runtime parameters, not template arguments.
R3D_KLAUNCH(r3d_gdn_recurrent_update_kernel, grid, blk, stream,
(const unsigned short*)q, (const unsigned short*)k, (const unsigned short*)v,
a, b, ab_stride, (const float*)A_log, (const float*)dt_bias, (float*)state,
st_slot, st_head, (const int*)sidx, sidx_stride, (const unsigned short*)zg,
zg_pitch, (const float*)nw, (unsigned short*)o, (const int*)cu, H, Hg,
scale, sp_thr, neps, norm, ab_bf16);
return (int)hipGetLastError();
}
} // namespace
/* ------------------------------------------------------------------ the plugin ABI */
enum { RU_Q = 0, RU_K, RU_V, RU_A, RU_B, RU_ALOG, RU_DTB, RU_STATE, RU_SIDX, RU_NACC, RU_CU,
RU_Z, RU_NORMW, RU_O, RU_OQ, RU_OSCALE };
extern "C" int r3d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const RadTensor* q = r3d_opt(a, RU_Q);
const RadTensor* k = r3d_opt(a, RU_K);
const RadTensor* v = r3d_opt(a, RU_V);
const RadTensor* ta = r3d_opt(a, RU_A);
const RadTensor* tb = r3d_opt(a, RU_B);
const RadTensor* alog = r3d_opt(a, RU_ALOG);
const RadTensor* dtb = r3d_opt(a, RU_DTB);
const RadTensor* st = r3d_opt(a, RU_STATE);
const RadTensor* sidx = r3d_opt(a, RU_SIDX);
const RadTensor* nacc = r3d_opt(a, RU_NACC);
const RadTensor* cu = r3d_opt(a, RU_CU);
const RadTensor* z = r3d_opt(a, RU_Z);
const RadTensor* nw = r3d_opt(a, RU_NORMW);
const RadTensor* o = r3d_opt(a, RU_O);
// o_q and o_scale are the folded quantiser's outputs; this row does not fold it.
if (!r3d_p(q) || !r3d_p(k) || !r3d_p(v) || !r3d_p(ta) || !r3d_p(tb) || !r3d_p(alog) ||
!r3d_p(dtb) || !r3d_wp(st) || !r3d_p(sidx) || !r3d_p(cu) || !r3d_wp(o))
return R3D_NO(RAD_E_INVAL);
if (q->rank != 3 || k->rank != 3 || v->rank != 3 || st->rank != 4 || o->rank != 3)
return R3D_NO(RAD_E_SHAPE);
if (sidx->rank < 2) return R3D_NO(RAD_E_SHAPE);
const long long T = q->shape[0];
const long long Hg = q->shape[1];
const long long K = q->shape[2];
const long long H = v->shape[1];
const long long V = v->shape[2];
if (k->shape[0] != T || k->shape[1] != Hg || k->shape[2] != K) return R3D_NO(RAD_E_SHAPE);
if (v->shape[0] != T || o->shape[0] != T || o->shape[1] != H || o->shape[2] != V)
return R3D_NO(RAD_E_SHAPE);
if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE);
if (K != kK || V != kV) return R3D_NO(RAD_E_SHAPE);
if (!r3d_is_bf16(q) || !r3d_is_bf16(k) || !r3d_is_bf16(v) || !r3d_is_bf16(o))
return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(alog) || !r3d_is_f32(dtb)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(st)) return R3D_NO(RAD_E_DTYPE); // fp32 state cache
if (ta->dtype != RAD_BF16 && ta->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE);
if (tb->dtype != ta->dtype) return R3D_NO(RAD_E_DTYPE);
// state cache [slots, H, V, K]: the per-head and per-slot strides.
if (st->shape[1] != H || st->shape[2] != kV || st->shape[3] != kK) return R3D_NO(RAD_E_SHAPE);
const long long st_head = st->stride[1];
const long long st_slot = st->stride[0];
if (st_head != (long long)kV * kK) return R3D_NO(RAD_E_STRIDE);
// a and b: [T, H] (the ba projection's rows), row pitch in elements.
const long long ab_stride = r3d_row_pitch(ta);
if (ab_stride < 0 || r3d_row_pitch(tb) != ab_stride) return R3D_NO(RAD_E_STRIDE);
const long long sidx_stride = sidx->stride[sidx->rank - 1] == 1 ? sidx->stride[0] : -1;
if (sidx_stride < 0) return R3D_NO(RAD_E_STRIDE);
int N = 0;
if (cu->rank != 1 || cu->shape[0] < 2 || !r3d_contig(cu)) return R3D_NO(RAD_E_SHAPE);
N = (int)(cu->shape[0] - 1);
const float scale = (float)r3d_getf(a, "scale", 1.0 / sqrt((double)kK));
const float sp_thr = (float)r3d_getf(a, "softplus_thr", 20.0);
const float neps = (float)r3d_getf(a, "eps", 1e-6);
// The gated RMS norm epilogue: present when both z and norm_w are given.
int norm = 0;
long long zg_pitch = 0;
if (r3d_p(z) && r3d_p(nw)) {
if (z->rank != 3 || z->shape[0] != T || z->shape[1] != H || z->shape[2] != kV)
return R3D_NO(RAD_E_SHAPE);
if (!r3d_is_bf16(z) || !r3d_is_f32(nw) || r3d_numel(nw) != kV) return R3D_NO(RAD_E_DTYPE);
const int act = r3d_act_code(a, "act", nullptr, 0);
if (act != 0 && act != 1) return R3D_NO(RAD_E_INVAL);
norm = (act == 0) ? 2 : 1; // r3d_act_code: 0=silu, 1=sigmoid; kernel: 2=silu, 1=sigmoid
zg_pitch = z->stride[0];
}
const int e = r3d_gdn_recurrent_update_launch(r3d_p(q), r3d_p(k), r3d_p(v), r3d_p(ta), r3d_p(tb),
ab_stride, r3d_p(alog), r3d_p(dtb), r3d_wp(st),
st_slot, st_head, r3d_p(sidx), sidx_stride,
r3d_p(z), zg_pitch, r3d_p(nw), r3d_wp(o), r3d_p(cu),
N, (int)H, (int)Hg, norm, (ta->dtype == RAD_BF16),
scale, sp_thr, neps, (hipStream_t)s);
/* The launcher's codes are raw: its own negatives and hipGetLastError's positives. The
* plugin ABI takes RadStatus, so normalise. */
if (e < 0) return R3D_NO(RAD_E_INVAL);
return e ? R3D_NO(RAD_E_DEVICE) : RAD_OK;
}
+129
View File
@@ -0,0 +1,129 @@
/* r3d_gelu_mul_quant_i8.hip -- gelu_mul_quant_i8: gelu(gate) * up and the per-row symmetric int8
* quantiser in one pass over the row.
*
* The down projection's input of a GELU-gated feed-forward (Gemma) on a w4a8 grid, replacing the
* gelu_mul + quant_act_i8 pair and byte-identical to it: the product is formed in the tanh form
* with the same constants, rounded to bf16, and the absmax, scale and codes are quant_act_i8's
* over those bf16 values. The absmax is a max, so partitioning does not change it.
*
* gate_up [M][2n] bf16 (gate first) -> q [M][n] i8 (WMMA step order), scale [M] f32, out_bf16?
*
* The codes are written in the int8 WMMA step order (i8_step_pos), the plane the w4a8/w8a8/w2a8
* GEMMs read, so n is a multiple of 16.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr float kTopI8 = 127.0f;
constexpr float kI8Floor = 1e-8f;
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8));
const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8));
const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8));
const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8));
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}
__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) {
return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1);
}
__device__ __forceinline__ float block_max(float v, float* lds) {
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
v = wave_max(v);
if (lane == 0) lds[wave] = v;
__syncthreads();
float t = lds[0];
#pragma unroll
for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]);
return t;
}
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void gelu_mul_quant_i8_kernel(
const uint16_t* __restrict__ gu, uint8_t* __restrict__ q, float* __restrict__ s,
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
extern __shared__ uint16_t ybuf[]; // n bf16 of the product
__shared__ float lm[kWaves];
const uint32_t row = blockIdx.x;
const uint16_t* gr = gu + (size_t)row * gu_ld;
uint8_t* qr = q + (size_t)row * n;
uint16_t* yop = yo ? yo + (size_t)row * y_ld : nullptr;
constexpr float k0 = 0.7978845608028654f, k1 = 0.044715f;
float m = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const float g = ld_bf(gr, i);
const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g)));
const uint16_t y = f32_to_bf16(gelu * ld_bf(gr, n + i));
ybuf[i] = y;
if (yop) yop[i] = y;
m = fmaxf(m, fabsf(bf16_to_f32(y)));
}
m = block_max(m, lm);
const float scale = fmaxf(m, kI8Floor) / kTopI8;
const float inv = 1.0f / scale;
if (threadIdx.x == 0) s[row] = scale;
for (uint32_t c = threadIdx.x * 4; c < n; c += kThreads * 4) {
float v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) v[j] = (c + (uint32_t)j < n) ? bf16_to_f32(ybuf[c + (uint32_t)j])
: 0.0f;
*(uint32_t*)(qr + i8_step_pos(c)) = i8_codes4(v, inv);
}
}
} // namespace
extern "C" {
int r3d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* gu = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2),
*y = r3d_opt(a, 3);
if (!r3d_p(gu) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (gu->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
long long M = 0, n = 0;
if (r3d_rows_of(q, &M, &n) != 0) return R3D_NO(RAD_E_INVAL);
if (n <= 0 || n % 16 || !r3d_contig(q)) return R3D_NO(RAD_E_SHAPE);
// gate_up is [M, 2n]; accept a row pitch of at least 2n. The pitch is the leading stride
// (r3d_row_pitch), which is shape[1] for a rank-2 row and the whole row extent for a rank-3.
const long long gu0 = r3d_row_pitch(gu);
if (gu0 < 2 * n) return R3D_NO(RAD_E_SHAPE);
const uint32_t gu_ld = (uint32_t)gu0;
if (r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE);
uint32_t y_ld = n;
if (y) {
if (y->dtype != RAD_BF16 || r3d_numel(y) < M * n) return R3D_NO(RAD_E_SHAPE);
const long long yp = r3d_row_pitch(y);
if (yp < n) return R3D_NO(RAD_E_STRIDE);
y_ld = (uint32_t)yp;
}
const size_t lds = (size_t)n * sizeof(uint16_t);
if (lds > 60 * 1024) return R3D_NO(RAD_E_SHAPE);
dim3 grid((unsigned)M), blk(kThreads);
R3D_KLAUNCH_S(gelu_mul_quant_i8_kernel, grid, blk, (size_t)lds, (hipStream_t)s,
(const uint16_t*)r3d_p(gu), (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc),
(uint16_t*)(y ? r3d_wp(y) : nullptr), (uint32_t)n, gu_ld, y_ld);
return (int)hipGetLastError();
}
} // extern "C"
+17
View File
@@ -81,6 +81,11 @@
#include <algorithm>
/* The wave-matrix arm's launcher, in r3d_gemm_bf16_nt_m16_wmma.hip: the row's `impl` point 1. */
extern "C" int r3d_gemm_nt_bf16_m16_wmma(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int wv, int nt, long scratch,
long stream);
namespace {
constexpr int kBlockThreads = 256; // eight waves, the default
@@ -331,6 +336,18 @@ extern "C" int r3d_rad_gemm_nt_bf16_m16(const RadArgs* a, RadStream s)
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
if (c.impl == 1) {
/* The wave-matrix arm: same contract, the slab's law at 16 k, its own launcher. The
* alignment and pitch checks above are the arm's too. `c.sk` is the unresolved value
* here -- the arm resolves 0 to its widest legal split and checks its own scratch, so
* the arena goes across whenever the row asked for one. */
const int e = r3d_gemm_nt_bf16_m16_wmma(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M,
(int)N, (int)K, (int)a_ld, (int)y_ld, c.sk, c.wv,
c.nt, (long)(uintptr_t)a->scratch, (long)(uintptr_t)s);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
int wv = c.wv > 0 ? c.wv : kWaves;
if (wv > kWaves) wv = kWaves;
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return R3D_NO(RAD_E_SHAPE);
+251
View File
@@ -0,0 +1,251 @@
/* r3d_gemm_bf16_nt_m16_wmma.hip -- the wave-matrix arm of the skinny bf16 GEMM, M <= 16.
*
* y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store.
*
* The dot2 arm (r3d_gemm_bf16_nt_m16.hip) owns one output element a lane and folds k in
* ascending pairs; this arm issues V_WMMA_F32_16X16X16_BF16 over a 16x16x16 tile, a wave a
* tile, and the two arms are two points of the row's `impl` axis. The tune cache picks the
* point per shape per machine; an untuned install runs the dot2 arm, which is the axis's
* default.
*
* ---- the tile map --------------------------------------------------------------------------
*
* One wave owns a 16-row by 16-column output tile and walks k in 16-wide steps, one wmma a
* step. The ISA's lane map (wave32, the `_w32` builtins):
*
* A fragment: lane L holds row L % 16 of the tile, 16 bf16 in eight packed VGPRs
* B fragment: lane L holds column L % 16 of the tile, 16 bf16 in eight packed VGPRs
* C/D: lane L, VGPR g holds D[g * 2 + L / 16][L % 16], eight f32 a lane
*
* and lanes 0-15 and 16-31 must hold identical A and B data (the replication the ISA
* requires; only L % 16 selects the row or column). The accumulator chain is D = C, so a
* dependent wmma needs no V_NOP between steps: the hazard the ISA names is A/B overlapping
* the next step's D, and the fragments are fresh registers each step.
*
* The k order is the dot2 arm's contract at the tile boundary: tiles are summed in ascending
* k, and within a tile the sixteen products run in the hardware's fixed order. That is the
* arm's exactness statement: sk = 1 agrees with the reference to the last few bits, the way
* the dot2 arm's splits do, and the row's tolerance gate prices it, not a bit-exact claim.
*
* ---- where the bytes come from --------------------------------------------------------------
*
* The activation is staged in LDS in bf16, the checkpoint's own bytes: the bf16 builtin
* takes the tile's bits directly, so the widening the dot2 arm pays once per element
* (bf16x2_to_f16x2 on the way in) is not here at all. One tile is 16 rows x 128 k of bf16,
* the dot2 arm's k tile, 4.25 KiB with the pitch, and carries eight wmma steps. The pitch is
* the dot2 arm's 68 dwords: 68 mod 32 = 4, so the lanes of a ds_read phase land four banks
* apart and the two 16-byte fragment reads a lane issues per step are conflict-free in
* their phases.
*
* The weight streams from global, one 16-byte pair a lane per step (column L % 16 of the
* tile, the step's 16 k), the NT axis choosing the lowering the dot2 arm's header describes.
* Every weight byte is read once per output tile, the same stream the dot2 arm streams; what
* the arm changes is the issue: one wmma where the dot2 arm issues eight dot4 folds.
*
* ---- the register budget --------------------------------------------------------------------
*
* Eight accumulator VGPRs, eight A, eight B and the pointers: about 34 a lane. Eight waves
* a SIMD asks 272 of the 1024 the gfx11 SIMD keeps, so the block default stands and `wv`
* walks the same ladder as the dot2 arm.
*
* ---- split-K --------------------------------------------------------------------------------
*
* The dot2 arm's slabs and partial plane, with one change: a slab is whole wmma steps, so a
* split is legal only when K % (sk * 16) == 0, and the ragged end is not a scalar tail but a
* step whose fragments zero-fill past K -- the products with zero are the identity and the
* k loop stays uniform. sk = 1 serves a ragged K the dot2 arm serves with its scalar tail.
* The reducer is the dot2 arm's, copied here: the two arms must not share a symbol through a
* header, and twelve lines are cheaper than the coupling.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
namespace {
constexpr int kBlockThreads = 256; // eight waves, the default
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kKTile = 128; // k a staged tile covers, eight wmma steps
constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row, the dot2 arm's 68
constexpr int kUnit = 16; // k a wmma step consumes: a slab's law
/* One dword of two bf16 into the fragment's two shorts: the low half first, the high half
* after -- the packed order the builtin's VGPR map expects. A vector element is not a
* modifiable lvalue, so the unpack is a constructor argument, not a reference target. */
#define R3D_U16(w) ((short)((w) & 0xffffu)), ((short)((w) >> 16))
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p)
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
/* y[M,N] = a[M,K] @ b[N,K]^T, one 16x16 tile a wave.
*
* `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the
* narrowed bf16 the caller asked for. With sk > 1 every split writes its own f32 partial,
* dense [sk][M][N], and the reducer adds them in split order. */
template <bool NT, bool SPLIT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_wmma_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ B,
uint16_t* __restrict__ Y, float* __restrict__ Part,
int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab)
{
/* Staged activation in the checkpoint's own bytes, a dword array at the dot2 arm's pitch. */
__shared__ uint32_t s_a[16 * kAPitch];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t waves = blockDim.x / kWave;
const uint32_t r = lane & 15; // the replicated row/column index
const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * 16 + r;
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
const int kbeg = (int)blockIdx.y * kslab;
const int kend = kbeg + kslab < K ? kbeg + kslab : K;
const uint16_t* w = B + (size_t)n_real * w_ld;
v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
for (int kt = kbeg; kt < kend; kt += kKTile) {
const int kl = std::min(kKTile, kend - kt);
/* Stage 16 rows x kl bf16, eight elements a unit, 256 threads. A row past M re-reads
* the last real row, whose products the store drops; a unit past kl zero-fills. */
const int nu = (kl + 7) / 8;
for (int i = (int)tid; i < 16 * nu; i += (int)blockDim.x) {
const int row = i / nu, c = (i % nu) * 8;
const int rr = row < M ? row : M - 1;
const uint16_t* src = A + (size_t)rr * a_ld + kt + c;
uint32_t* dst = s_a + (size_t)row * kAPitch + c / 2;
if (c + 8 <= kl) {
const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src;
*(r3d_u32x4*)dst = q;
} else {
uint32_t p[4] = { 0, 0, 0, 0 };
for (int e = 0; e < kl - c; e += 2) {
const uint32_t lo = ldg_u16(src + e);
const uint32_t hi = (e + 1 < kl - c) ? ldg_u16(src + e + 1) : 0u;
p[e / 2] = lo | (hi << 16);
}
for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e];
}
}
group_barrier();
const uint32_t* ap = s_a + (size_t)r * kAPitch;
for (int k = 0; k < kl; k += 16) {
/* Eight wmma steps per tile: two 16-byte reads a lane, the row's k pair at
* dword k/2 and k/2 + 4, and the column's from global. */
const r3d_u32x4 a0 = *(const r3d_u32x4*)(ap + k / 2);
const r3d_u32x4 a1 = *(const r3d_u32x4*)(ap + k / 2 + 4);
const r3d_u32x4 b0 = ldw<NT>(w + kt + k);
const r3d_u32x4 b1 = ldw<NT>(w + kt + k + 8);
const v16short fa = v16short{ R3D_U16(a0.x), R3D_U16(a0.y), R3D_U16(a0.z),
R3D_U16(a0.w), R3D_U16(a1.x), R3D_U16(a1.y),
R3D_U16(a1.z), R3D_U16(a1.w) };
const v16short fb = v16short{ R3D_U16(b0.x), R3D_U16(b0.y), R3D_U16(b0.z),
R3D_U16(b0.w), R3D_U16(b1.x), R3D_U16(b1.y),
R3D_U16(b1.z), R3D_U16(b1.w) };
acc = wmma_bf16(fa, fb, acc);
}
group_barrier(); // the next tile's stage must not race this one's reads
}
const bool keep = (n0 < (uint32_t)N);
if (!keep) return;
for (int g = 0; g < 8; ++g) {
const int m = g * 2 + (int)(lane >> 4);
if (m >= M) continue;
if constexpr (SPLIT)
Part[((size_t)blockIdx.y * M + m) * N + n0] = acc[g];
else
Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc[g]);
}
}
#undef R3D_U16
/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one
* narrowing. The dot2 arm's, copied: the slab sums bracket the products differently than
* one chain does, and the difference is in the last bits, the split's, not a bug in it. */
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_wmma_split_reduce(
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
{
const int mn = M * N;
const int stride = gridDim.x * kBlockThreads;
for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) {
const int m = i / N, n = i - m * N;
const float* p = Part + (size_t)m * N + n;
float v = p[0];
for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N];
Y[(size_t)m * y_ld + n] = f32_to_bf16(v);
}
}
} // namespace
/* y[M,N] = a[M,K] @ b[N,K]^T, bf16 in and out, f32 accumulate, M <= 16, the wave-matrix arm.
*
* The dot2 arm's contract, with the slab law at 16 k. `sk` splits K (0 = the largest legal
* split), `wv` waves per block (0 = 8), `nt` the weight load's lowering, `scratch` the f32
* partial arena, sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null
* pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */
extern "C" int r3d_gemm_nt_bf16_m16_wmma(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int wv, int nt, long scratch,
long stream)
{
if (!a || !b || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > 16) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (sk == 0) {
static const int kLadder[] = { 16, 8, 4, 2, 1 };
for (int s : kLadder)
if (s > 1 ? K % ((long long)s * kUnit) == 0 : true) { sk = s; break; }
}
if (sk < 1) return -2;
/* The slab is kUnit deep: a ragged tail (K % kUnit) would stage a partial unit
* the tile loop reads whole (stale dwords) and load B fragments past the weight,
* so the shape is refused, as the dot2 arm's pick_sk already does. */
if (K % ((long long)sk * kUnit)) return -2;
if (sk > 1 && !scratch) return -1;
if (wv <= 0) wv = kWaves;
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2;
const int kslab = K / sk;
#define R3D_WNT(NTV) \
do { \
const int nt_ = (N + 15) / 16; \
const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \
if (sk > 1) { \
R3D_KLAUNCH(R3D_KNAME((gemm_m16_wmma_kernel<NTV, true>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \
const int mn = M * N; \
const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \
R3D_KLAUNCH(gemm_m16_wmma_split_reduce, dim3(nb), dim3(kBlockThreads), \
(hipStream_t)stream, (const float*)scratch, (uint16_t*)y, M, N, y_ld, \
sk); \
} else { \
R3D_KLAUNCH(R3D_KNAME((gemm_m16_wmma_kernel<NTV, false>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \
} \
} while (0)
if (nt) R3D_WNT(true);
else R3D_WNT(false);
#undef R3D_WNT
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+298
View File
@@ -0,0 +1,298 @@
/* r3d_gemm_bf16_nt_m64_wmma.hip -- the wave-matrix bf16 GEMM for the M = 17..127 band.
*
* y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store.
*
* The m16 arm (r3d_gemm_bf16_nt_m16_wmma) owns one 16-row tile a wave and stages that tile in
* LDS; above M = 16 a 128-row tiled block wastes half its rows, so this arm takes MT 16-row
* tiles a block and walks them with MT accumulators a wave. The B-fragment (the weight column)
* is loaded once per 16-k step and reused over the MT row tiles, so the weight stream is read
* once per 16-column tile no matter how many row tiles the block carries -- the activation, not
* the weight, is the traffic that grows with MT, and it is read from global (no LDS) so a block
* stays small enough to keep the waves on the SIMD.
*
* ---- the tile map --------------------------------------------------------------------------
*
* One wave owns a 16-column output tile across MT 16-row tiles and walks k in 16-wide steps, one
* wmma a step per row tile. The ISA's lane map (wave32, the `_w32` builtins), the m16 arm's:
*
* A fragment: lane L holds row L % 16 of a row tile, 16 bf16 in eight packed VGPRs
* B fragment: lane L holds column L % 16 of the tile, 16 bf16 in eight packed VGPRs
* C/D: lane L, VGPR g holds D[g * 2 + L / 16][L % 16], eight f32 a lane
*
* ---- split-K --------------------------------------------------------------------------------
*
* The m16 arm's slabs and f32 partial plane, with the same law: a slab is whole 16-k wmma steps,
* so a split is legal only when K % (sk * 16) == 0, and the reducer adds the sk partials in
* ascending split order. sk = 1 serves a ragged K.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
namespace {
constexpr int kBlockThreads = 256; // eight waves, the default
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kUnit = 16; // k a wmma step consumes: a slab's law
#define R3D_U16(w) ((short)((w) & 0xffffu)), ((short)((w) >> 16))
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p)
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
/* y[M,N] = a[M,K] @ b[N,K]^T, MT 16-row tiles a block, one 16-column tile a wave.
*
* `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the
* narrowed bf16 the caller asked for. With sk > 1 every split writes its own f32 partial, dense
* [sk][M][N], and the reducer adds them in split order. */
template <bool NT, int MT, bool SPLIT, bool F16ACC>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m64_wmma_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ B,
uint16_t* __restrict__ Y, float* __restrict__ Part,
int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab)
{
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t waves = blockDim.x / kWave;
const uint32_t r = lane & 15; // the replicated row/column index
const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * 16 + r;
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
const uint32_t mt0 = (uint32_t)blockIdx.y * MT * 16; // this block's first row
const int kbeg = (int)blockIdx.y * 0; // the split is blockIdx.z; see the launch
(void)kbeg;
const uint16_t* w = B + (size_t)n_real * w_ld;
/* The accumulator: f32 for the f32-acc arm, v16short for the bf16-acc arm. The bf16-acc
* builtin's 8 live elements sit in the even indices (opsel = false); the epilogue reads
* only those, the odd half is dead.
*
* PRECISION: the bf16-acc arm is a documented low-precision mode -- the hardware quantises
* the running sum at bf16 precision per wave-matrix step, and the loss grows with the number
* of steps (measured on gfx1102, random data in [-1,1]: ~0.78 abs after 16 k, ~51 after 256
* k, ~622 after 1024 k; integer-valued data stays exact). It measures no throughput gain
* over the f32 arm. It is a register-pressure option for future occupancy work, not a speed
* one; do not select it for accuracy-sensitive shapes. See the README's 16-bit
* wave-matrix accumulate section. */
using AccT = std::conditional_t<F16ACC, v16short, v8float>;
AccT acc[MT];
#pragma unroll
for (int i = 0; i < MT; ++i) {
if constexpr (F16ACC)
acc[i] = v16short{ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
else
acc[i] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
}
// The split's k range: blockIdx.z owns [z*kslab, z*kslab + kslab).
const int kbeg2 = (int)blockIdx.z * kslab;
const int kend = kbeg2 + kslab < K ? kbeg2 + kslab : K;
/* Double-buffered k-walk: the next step's A and B fragments are issued into registers while
* the current step's wmmas run, so the global load latency overlaps the multiply. The first
* step is prefetched before the loop; each iteration consumes the current fragments, issues
* the next step's loads, then swaps. The ragged end (kl < kUnit) keeps the zero-fill. */
const uint16_t* bp = w + kbeg2;
const r3d_u32x4 b0 = ldw<NT>(bp);
const r3d_u32x4 b1 = ldw<NT>(bp + 8);
v16short fb = v16short{ R3D_U16(b0.x), R3D_U16(b0.y), R3D_U16(b0.z),
R3D_U16(b0.w), R3D_U16(b1.x), R3D_U16(b1.y),
R3D_U16(b1.z), R3D_U16(b1.w) };
v16short fa[MT];
#pragma unroll
for (int i = 0; i < MT; ++i) {
const int mrow = (int)mt0 + i * 16 + (int)r;
const uint16_t* ap = A + (size_t)(mrow < M ? mrow : M - 1) * a_ld + kbeg2;
const r3d_u32x4 a0 = ldw<NT>(ap);
const r3d_u32x4 a1 = ldw<NT>(ap + 8);
fa[i] = v16short{ R3D_U16(a0.x), R3D_U16(a0.y), R3D_U16(a0.z),
R3D_U16(a0.w), R3D_U16(a1.x), R3D_U16(a1.y),
R3D_U16(a1.z), R3D_U16(a1.w) };
}
for (int kt = kbeg2; kt < kend; kt += kUnit) {
const int kl = std::min(kUnit, kend - kt);
const int ktn = kt + kUnit;
const bool more = (ktn < kend);
// Issue the next step's fragment loads now, while this step's wmmas run below.
r3d_u32x4 b0n, b1n;
v16short fbn;
v16short fan[MT];
if (more) {
b0n = ldw<NT>(w + ktn);
b1n = ldw<NT>(w + ktn + 8);
fbn = v16short{ R3D_U16(b0n.x), R3D_U16(b0n.y), R3D_U16(b0n.z),
R3D_U16(b0n.w), R3D_U16(b1n.x), R3D_U16(b1n.y),
R3D_U16(b1n.z), R3D_U16(b1n.w) };
#pragma unroll
for (int i = 0; i < MT; ++i) {
const int mrow = (int)mt0 + i * 16 + (int)r;
const uint16_t* apn = A + (size_t)(mrow < M ? mrow : M - 1) * a_ld + ktn;
const r3d_u32x4 a0n = ldw<NT>(apn);
const r3d_u32x4 a1n = ldw<NT>(apn + 8);
fan[i] = v16short{ R3D_U16(a0n.x), R3D_U16(a0n.y), R3D_U16(a0n.z),
R3D_U16(a0n.w), R3D_U16(a1n.x), R3D_U16(a1n.y),
R3D_U16(a1n.z), R3D_U16(a1n.w) };
}
}
// Consume the current step's fragments.
#pragma unroll
for (int i = 0; i < MT; ++i) {
if (kl == kUnit) {
if constexpr (F16ACC) acc[i] = wmma_bf16acc<false>(fa[i], fb, acc[i]);
else acc[i] = wmma_bf16(fa[i], fb, acc[i]);
} else {
v16short fa0 = fa[i];
for (int e = kl; e < 16; ++e) fa0[e] = (short)0;
if constexpr (F16ACC) acc[i] = wmma_bf16acc<false>(fa0, fb, acc[i]);
else acc[i] = wmma_bf16(fa0, fb, acc[i]);
}
}
// Advance: the prefetched next step becomes the current step.
if (more) {
fb = fbn;
#pragma unroll
for (int i = 0; i < MT; ++i) fa[i] = fan[i];
}
}
const bool keep = (n0 < (uint32_t)N);
if (!keep) return;
#pragma unroll
for (int i = 0; i < MT; ++i) {
for (int g = 0; g < 8; ++g) {
const int m = (int)mt0 + i * 16 + g * 2 + (int)(lane >> 4);
if (m >= M) continue;
if constexpr (F16ACC) {
// The bf16-acc arm: the 8 live elements are the even indices (opsel = false).
// Widen the bf16 short to f32 for the split partial; the store re-narrows.
const uint32_t u = ((uint32_t)(uint16_t)acc[i][2 * g]) << 16;
float v; memcpy(&v, &u, 4);
if constexpr (SPLIT)
Part[((size_t)blockIdx.z * M + m) * N + n0] = v;
else
Y[(size_t)m * y_ld + n0] = (uint16_t)((uint16_t)acc[i][2 * g]);
} else {
if constexpr (SPLIT)
Part[((size_t)blockIdx.z * M + m) * N + n0] = acc[i][g];
else
Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc[i][g]);
}
}
}
}
#undef R3D_U16
/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one
* narrowing. The m16 arm's, copied: the two arms must not share a symbol through a header. */
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m64_wmma_split_reduce(
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
{
const int mn = M * N;
const int stride = gridDim.x * kBlockThreads;
for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) {
const int m = i / N, n = i - m * N;
const float* p = Part + (size_t)m * N + n;
float v = p[0];
for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N];
Y[(size_t)m * y_ld + n] = f32_to_bf16(v);
}
}
} // namespace
/* y[M,N] = a[M,K] @ b[N,K]^T, bf16 in and out, f32 accumulate, the M = 17..127 band on the
* wave-matrix. `sk` splits K (0 = the largest legal split), `wv` waves per block (0 = 8), `nt`
* the weight load's lowering, `scratch` the f32 partial arena, sk * M * N * 4 bytes, required
* when the split is on. Returns 0, -1 a null pointer, -2 a shape it does not serve, -4 a launch
* failure. */
extern "C" int r3d_gemm_nt_bf16_m64_wmma(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int wv, int nt, long scratch,
long stream, int acc)
{
if (acc < 0) acc = 0;
if (acc > 1) acc = 1;
if (!a || !b || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
const int w_ld = K;
if (sk == 0) {
static const int kLadder[] = { 8, 4, 2, 1 };
for (int s : kLadder)
if (s > 1 ? K % ((long long)s * kUnit) == 0 : true) { sk = s; break; }
}
if (sk < 1) return -2;
if (sk > 1 && K % ((long long)sk * kUnit)) return -2;
if (sk > 1 && !scratch) return -1;
if (wv <= 0) wv = kWaves;
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2;
const int kslab = K / sk;
const int ntiles = (N + 15) / 16;
const int ncolblk = (ntiles + wv - 1) / wv;
#define R3D_WMT(NTV, MT, ACC) \
do { \
const int mrowblk = (M + MT * 16 - 1) / (MT * 16); \
const dim3 grid(ncolblk, (unsigned)mrowblk, (unsigned)sk), block((unsigned)(wv * kWave)); \
if (sk > 1) { \
R3D_KLAUNCH(R3D_KNAME((gemm_m64_wmma_kernel<NTV, MT, true, ACC>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, w_ld, kslab); \
const int mn = M * N; \
const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \
R3D_KLAUNCH(gemm_m64_wmma_split_reduce, dim3(nb), dim3(kBlockThreads), \
(hipStream_t)stream, (const float*)scratch, (uint16_t*)y, M, N, y_ld, \
sk); \
} else { \
R3D_KLAUNCH(R3D_KNAME((gemm_m64_wmma_kernel<NTV, MT, false, ACC>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, w_ld, kslab); \
} \
} while (0)
#define R3D_WNT(NTV) \
do { \
if (M <= 16) { if (acc) R3D_WMT(NTV, 1, true); else R3D_WMT(NTV, 1, false); } \
else if (M <= 32) { if (acc) R3D_WMT(NTV, 2, true); else R3D_WMT(NTV, 2, false); } \
else { if (acc) R3D_WMT(NTV, 4, true); else R3D_WMT(NTV, 4, false); } \
} while (0)
if (nt) R3D_WNT(true);
else R3D_WNT(false);
#undef R3D_WNT
#undef R3D_WMT
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The RadArgs dispatch: the row's entry. The M = 17..127 band, sk = 1 (the N tiles carry the
* parallelism at prefill widths, so no split and no scratch), wv = 8, nt = 0. */
extern "C" int r3d_rad_gemm_nt_bf16_m64_wmma(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* at = &a->t[0], *wt = &a->t[1], *yt = &a->t[2];
if (!r3d_p(at) || !r3d_p(wt) || !r3d_wp(yt)) return R3D_NO(RAD_E_INVAL);
if (at->dtype != RAD_BF16 || wt->dtype != RAD_BF16 || yt->dtype != RAD_BF16)
return R3D_NO(RAD_E_DTYPE);
long long M = 0, K = 0;
if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
const long long N = (wt->rank >= 2) ? wt->shape[0] : 0;
if (M <= 0 || N <= 0 || K <= 0)
return R3D_NO(RAD_E_SHAPE);
const int a_ld = (int)at->stride[0];
const int y_ld = (int)yt->stride[0];
return r3d_gemm_nt_bf16_m64_wmma((long)(uintptr_t)r3d_p(at), (long)(uintptr_t)r3d_p(wt),
(long)(uintptr_t)r3d_wp(yt), (int)M, (int)N, (int)K, a_ld,
y_ld, 1, 8, 0, 0, (long)(uintptr_t)s, 0);
}
+384
View File
@@ -0,0 +1,384 @@
/* r3d_gemm_f16_nt_m16.hip -- the skinny f16 GEMM, M <= 16: the linear a token is made of.
*
* y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store.
*
* The band is decode and speculative verify, where the weight is the cost and the activation is
* free: the kernel is built so the whole weight plane streams once, and so every output's sum is
* the sum libref forms.
*
* ---- the lane map --------------------------------------------------------------------------
*
* One output element a lane, walking k ascending. A wave covers MT rows of the activation by
* 32/MT rows of the weight: lane l owns (m = l % MT, n = n0 + l / MT), MT being the template
* argument -- the request's M rounded up to 1, 2, 4, 8 or 16. Lanes sharing an n read the same
* weight words, so the wave issues 32/MT loads per step and broadcasts them to MT lanes each;
* lanes sharing an m read the same activation words out of LDS. A lane therefore owns its own
* accumulator from 0 to K and never exchanges a value with another lane: its chain is
*
* acc = 0; for k ascending: acc = dot2(pair k+1, dot2(pair k, acc))
*
* with pairs taken two k at a time, which is `s += a[k]*b[k]` in ascending k, summand for summand,
* the loop r4d_gemm_bf16_nt_tiled's contract quotes and ref_gemm.h's quant_tile runs. There is no
* wave reduction anywhere in this kernel, so nothing reassociates: at sk = 1 the output is
* bit-identical to libref's, not merely within a tolerance.
*
* Rows past M and columns past N are clamped, not skipped -- a tail lane re-reads the last real row
* and its result is dropped at the store -- so the k loop stays uniform and the loads stay
* straight-line.
*
* ---- where the bytes come from --------------------------------------------------------------
*
* The activation is staged in LDS as the checkpoint's own bytes: one row is M <= 16 elements wide
* per k, so a tile is MT * 128 f16 (4.25 KiB at MT = 16) and one 16-byte load a thread. There is
* no widening on the way in at all -- f16 is the pair the dot2 takes, so the stage is a straight
* copy and the bf16 arm's one-convert-per-element price is not here. The pitch is 68 dwords:
* 68 mod 32 = 4, so the eight lanes of a ds_read_b128 phase land on banks 4 apart -- conflict-free
* -- and 68 * 4 = 272 keeps a 16-byte LDS read aligned.
*
* The weight is NOT staged. M is tiny, so a staged tile would be read by 32/MT lanes and then
* thrown away; LDS staging buys reuse a skinny shape does not have. Weight bytes go straight from
* global memory into the dot: a 16-byte read feeds four dot4 folds with no conversion between,
* which is the whole of this kernel's difference from the bf16 arm -- the bf16 arm pays four
* v_cvt_pk_rtz_f16_f32 per eight values because its bytes are not the dot's, and here they are.
* Each wave keeps NT = 32/MT rows resident in L1 (NT lines of 128 B, 4 KiB at MT = 1, the worst
* case), which is what makes 16-byte-per-lane strided reads across NT rows cost what they fetch.
*
* ---- the register budget --------------------------------------------------------------------
*
* A gfx11 SIMD has 1024 VGPRs for a wave32. The loop is one accumulator, four activation pairs,
* four weight dwords, one 16-byte staging quad and a handful of pointers and counters: about 24
* live VGPRs, so the kernel is nowhere near the 128 that R3D_WAVES(8) -- eight waves a SIMD,
* 1024/8 -- asks for. The target is stated for the reason r3d_common.h gives: unstated, the
* scheduler picks the occupancy itself, and this kernel's throughput is waves in flight, since
* every wave is waiting on a memory load that takes hundreds of cycles. Eight waves a block of
* 256 threads is the default, and `wv` is the axis a tuner walks.
*
* ---- split-K --------------------------------------------------------------------------------
*
* At M = 1 a wide N is the only parallelism there is, and N = 48 (a GDN a|b projection) gives three
* waves on a 32-CU card. `sk` splits K into that many contiguous slabs, each owned by one
* blockIdx.y, each writing an f32 partial to the caller's `scratch` arena; a second kernel on the
* same stream adds the partials per output in ascending split order and narrows once.
*
* The order matters and is stated: summing sk per-slab partials is NOT the ascending sum libref
* forms. Each partial is an ascending sum over its own slab, and the slab sums are then added in
* ascending slab order, which brackets the products differently than a single running chain does.
* sk = 1 is the bit-identical case; sk > 1 agrees to the last bits, which is the same contract
* libr4d's tiled row states about its slices. The row is verified at every sk kbench measures.
*
* `sk == 0` means "the largest legal split for this K" off the axis's ladder {16, 8, 4, 2, 1},
* legality being K % (sk * 8) == 0: a slice must end where the inner loop stops, on a group of the
* eight k (four f16 pairs) a lane consumes per step, so a slice boundary never falls inside a
* step. The staged tile is 128 k wide and its last tile is ragged, which is what lets a slice be
* 8 k long, and the cap of 16 is the split the row's scratch hook sizes the arena for.
*
* ---- `nt` -----------------------------------------------------------------------------------
*
* RDNA3 has no global_load_tr_b128 (that is RDNA4) and no cache-swizzle field on a global load. So
* `nt` is an axis that measures a knob the ISA does not special-case: nt = 1 issues the weight
* reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache modifier
* and no swizzle -- a plain stream -- and nt = 0 issues the same 16-byte reads through the generic
* pointer, which lowers to flat_load_dwordx4. Nothing is invented here; the axis exists so kbench
* can price the two lowerings and record that on this card they are the same stream.
*/
/* hip_runtime.h first: it defines __forceinline__, which r3d_codecs.h's R3D_HD spells, and
* r3d_common.h reaches the codecs before it reaches the runtime. */
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
/* The wave-matrix arm's launcher, in r3d_gemm_f16_nt_m16_wmma.hip: the row's `impl` point 1. */
extern "C" int r3d_gemm_nt_f16_m16_wmma(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int wv, int nt, long scratch,
long stream);
namespace {
constexpr int kBlockThreads = 256; // eight waves, the default
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kKTile = 128; // k a staged tile of a covers
constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row
constexpr int kMTMax = 16; // the band's upper bound
/* The split rule, in one place so the launch, the shim and the row's gemm_tune_valid agree.
* `kUnit` is the k a lane's step consumes -- eight elements, four f16 pairs -- and a slice must be
* whole steps, so a split is legal when K divides by sk * kUnit. The ladder is the row's `sk` axis
* descending, and its top is the split the scratch hook sizes for: a wider split the arena cannot
* hold is not a legal default. */
constexpr int kUnit = 8;
inline int pick_sk(long long K, int maxsk)
{
static const int kLadder[] = { 16, 8, 4, 2, 1 };
for (int s : kLadder)
if (s <= maxsk && K % ((long long)s * kUnit) == 0) return s;
return 1;
}
/* A 16-byte weight read. NT true is the address-space-1 form: global_load_b128, no cache modifier,
* no swizzle, the plain stream the row's `nt` axis names. NT false goes through the generic
* pointer, which the compiler lowers to flat_load_dwordx4. */
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p)
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p)
{
return *(const r3d_u32x4*)p;
}
/* y[M,N] = a[M,K] @ b[N,K]^T, one output element a lane.
*
* `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the
* narrowed f16 the caller asked for. With sk > 1 every split writes its own f32 partial, dense
* [sk][M][N], and gemm_split_reduce adds them. */
template <int MT, bool NT, bool SPLIT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ B,
uint16_t* __restrict__ Y, float* __restrict__ Part,
int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab)
{
/* Staged activation in the checkpoint's own bytes: the f16 pair the dot2 takes. One
* allocation for the widest MT: this kernel is instantiated for MT = 1, 2, 4, 8 and 16 and
* 4.25 KiB is not worth a template. */
__shared__ uint32_t s_a[kMTMax * kAPitch];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t waves = blockDim.x / kWave;
constexpr uint32_t kNT = kWave / MT; // weight rows a wave covers
const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * kNT + lane / MT;
const uint32_t m = lane & (MT - 1);
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
const int kbeg = (int)blockIdx.y * kslab;
const int kend = kbeg + kslab < K ? kbeg + kslab : K;
const uint16_t* w = B + (size_t)n_real * w_ld;
float acc = 0.0f;
for (int kt = kbeg; kt < kend; kt += kKTile) {
const int kl = std::min(kKTile, kend - kt);
/* Stage: eight elements a unit, MT * (kl/8) units, 256 threads. A row past M re-reads the
* last real row, whose products the store drops. The copy is straight: the bytes staged
* are the bytes the dot reads. */
const int nu = (kl + 7) / 8;
/* blockDim.x, not the 256-thread default: the wv axis launches one, two, four or eight
* waves, and a stage loop that strides the block constant leaves units staged only for
* the waves that exist -- wv = 1 stages 32 of MT*16 units and the k loop reads the rest of
* the tile out of LDS that was never written. */
for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) {
const int r = i / nu, c = (i % nu) * 8;
const int rr = r < M ? r : M - 1;
const uint16_t* src = A + (size_t)rr * a_ld + kt + c;
uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2;
if (c + 8 <= kl) {
const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src;
*(r3d_u32x4*)dst = q;
} else {
uint32_t p[4] = { 0, 0, 0, 0 };
for (int e = 0; e < kl - c; e += 2) {
const uint32_t lo = ldg_u16(src + e);
const uint32_t hi = (e + 1 < kl) ? ldg_u16(src + e + 1) : 0u;
p[e / 2] = lo | (hi << 16);
}
for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e];
}
}
group_barrier();
const uint32_t* ap = s_a + (size_t)m * kAPitch;
const int kf = kl & ~7;
for (int k = 0; k < kf; k += 8) {
const r3d_u32x4 aw = lds_a(ap + k / 2);
const r3d_u32x4 bw = ldw<NT>(w + kt + k);
/* The weight is the dot's operand as it arrives: f16 is f16, and a 16-byte read feeds
* the four folds with nothing between. The bf16 arm's trap does not exist here --
* there is no other 16-bit format these bytes could be read as -- which is the whole
* of the kernel's gain over it, one conversion group per eight products. */
acc = dot4_f16x4(aw.x, aw.y, bw.x, bw.y, acc);
acc = dot4_f16x4(aw.z, aw.w, bw.z, bw.w, acc);
}
/* The ragged end of the last slab, ascending. A split is legal only when its slab is whole
* tiles, so this runs at sk = 1 with a K that is not a multiple of 128. */
for (int k = kf; k < kl; ++k)
acc = acc + f16_to_f32((uint16_t)ldg_u16(A + (size_t)m_real * a_ld + kt + k))
* f16_to_f32((uint16_t)ldg_u16(w + kt + k));
group_barrier(); // the next tile's stage must not race this one's reads
}
const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M);
if (!keep) return;
if constexpr (SPLIT) {
/* Partial plane [sk][M][N]: split-major, so the reducer reads sk values M*N apart and this
* store keeps the same [M][N] shape at every split. */
Part[((size_t)blockIdx.y * M + m) * N + n0] = acc;
} else {
Y[(size_t)m * y_ld + n0] = f32_to_f16(acc); // narrowed once, here
}
}
/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one narrowing.
*
* This is the order libref's ascending sum produces at sk = 1 and not at sk > 1: each partial is
* ascending over its own slab, and the slab sums bracket the products differently than one chain
* does. The difference is in the last bits and is the split's, not a bug in it. */
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_split_reduce(
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
{
const int mn = M * N;
const int stride = gridDim.x * kBlockThreads;
for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) {
const int m = i / N, n = i - m * N;
const float* p = Part + (size_t)m * N + n;
float v = p[0];
for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N];
Y[(size_t)m * y_ld + n] = f32_to_f16(v);
}
}
} // namespace
/* y[M,N] = a[M,K] @ b[N,K]^T, f16 in and out, f32 accumulate, M <= 16.
*
* a [M][K] f16, `a_ld` elements a row (0 = K)
* b [N][K] f16, row-major, k contiguous
* y [M][N] f16, `y_ld` elements a row (0 = N)
*
* `sk` splits K (0 = the largest legal split), `wv` is waves per block (0 = 8), `nt` picks the
* weight load's lowering (see the file header), and `scratch` is the f32 partial arena,
* sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null pointer, -2 a shape it
* does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */
extern "C" int r3d_gemm_nt_f16_m16(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int wv, int nt, long scratch, long stream)
{
if (!a || !b || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > kMTMax) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (sk == 0) sk = pick_sk(K, 16);
if (sk < 1) return -2;
if (K % ((long long)sk * kUnit)) return -2;
if (sk > 1 && !scratch) return -1;
if (wv <= 0) wv = kWaves;
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2;
const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax;
const int kslab = K / sk;
#define R3D_M16_NT(MTV, NTV) \
do { \
const int nt_ = (N + (kWave / MTV) - 1) / (kWave / MTV); \
const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \
if (sk > 1) { \
R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel<MTV, NTV, true>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \
const int mn = M * N; \
const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \
R3D_KLAUNCH(gemm_split_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \
(const float*)scratch, (uint16_t*)y, M, N, y_ld, sk); \
} else { \
R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel<MTV, NTV, false>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \
} \
} while (0)
#define R3D_M16_MT(MTV) do { if (nt) R3D_M16_NT(MTV, true); else R3D_M16_NT(MTV, false); } while (0)
switch (mt) {
case 1: R3D_M16_MT(1); break;
case 2: R3D_M16_MT(2); break;
case 4: R3D_M16_MT(4); break;
case 8: R3D_M16_MT(8); break;
default: R3D_M16_MT(16); break;
}
#undef R3D_M16_MT
#undef R3D_M16_NT
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* ============================================================== the plugin ABI entry point
*
* gemm_nt's operand list is [a, b, y] and its parameters M, N, K, dtype (libref's pGemm/oGemm). */
enum { G_A = 0, G_B, G_Y };
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
static int dt_f16(const RadTensor* t) { return r3d_is_f16(t) ? RAD_OK : RAD_E_DTYPE; }
extern "C" int r3d_rad_gemm_nt_f16_m16(const RadArgs* a, RadStream s)
{
const RadTensor* A = r3d_opt(a, G_A);
const RadTensor* B = r3d_opt(a, G_B);
const RadTensor* Y = r3d_opt(a, G_Y);
if (!A || !B || !Y) return R3D_NO(RAD_E_INVAL);
R3D_NEED(dt_f16(A));
R3D_NEED(dt_f16(B));
R3D_NEED(dt_f16(Y));
const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1));
const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2));
if (K < 1 || N < 1) return R3D_NO(RAD_E_SHAPE);
/* The row count comes from the output, never from `M`, which is the band's upper bound. */
const long long nel = r3d_numel(Y);
if (nel < N || nel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = nel / N;
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
long long arows = 0, yrows = 0;
const long long a_ld = r3d_rows_pitch(A, K, &arows);
const long long y_ld = r3d_rows_pitch(Y, N, &yrows);
if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE);
/* The weight must be dense: every wave reads b[n][k] at n * K + k, and a pitch the launcher
* does not carry cannot be described to it. */
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
/* 16-byte weight loads, at a row base and at a tile base, both multiples of 8 elements. */
if (a_ld % 8) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
if (c.impl == 1) {
/* The wave-matrix arm: same contract, the slab's law at 16 k, its own launcher. The
* alignment and pitch checks above are the arm's too. `c.sk` is the unresolved value
* here -- the arm resolves 0 to its widest legal split and checks its own scratch, so
* the arena goes across whenever the row asked for one. */
const int e = r3d_gemm_nt_f16_m16_wmma(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M,
(int)N, (int)K, (int)a_ld, (int)y_ld, c.sk, c.wv,
c.nt, (long)(uintptr_t)a->scratch, (long)(uintptr_t)s);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
int wv = c.wv > 0 ? c.wv : kWaves;
if (wv > kWaves) wv = kWaves;
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return R3D_NO(RAD_E_SHAPE);
int sk = c.sk > 0 ? c.sk : pick_sk(K, 16);
if (sk > 16) return R3D_NO(RAD_E_SHAPE); // the scratch hook sizes for 16
if (K % ((long long)sk * kUnit)) return R3D_NO(RAD_E_SHAPE);
if (sk > 1) {
const long long need = (long long)sk * M * N * 4;
if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH);
}
const int e = r3d_gemm_nt_f16_m16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)N,
(int)K, (int)a_ld, (int)y_ld, sk, wv, c.nt,
(long)(uintptr_t)(sk > 1 ? a->scratch : nullptr),
(long)(uintptr_t)s);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
+254
View File
@@ -0,0 +1,254 @@
/* r3d_gemm_f16_nt_m16_wmma.hip -- the wave-matrix arm of the skinny f16 GEMM, M <= 16.
*
* y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store.
*
* The dot2 arm (r3d_gemm_f16_nt_m16.hip) owns one output element a lane and folds k in
* ascending pairs; this arm issues V_WMMA_F32_16X16X16_F16 over a 16x16x16 tile, a wave a
* tile, and the two arms are two points of the row's `impl` axis. The tune cache picks the
* point per shape per machine; an untuned install runs the dot2 arm, which is the axis's
* default.
*
* ---- the tile map --------------------------------------------------------------------------
*
* One wave owns a 16-row by 16-column output tile and walks k in 16-wide steps, one wmma a
* step. The ISA's lane map (wave32, the `_w32` builtins):
*
* A fragment: lane L holds row L % 16 of the tile, 16 f16 in eight packed VGPRs
* B fragment: lane L holds column L % 16 of the tile, 16 f16 in eight packed VGPRs
* C/D: lane L, VGPR g holds D[g * 2 + L / 16][L % 16], eight f32 a lane
*
* and lanes 0-15 and 16-31 must hold identical A and B data (the replication the ISA
* requires; only L % 16 selects the row or column). The accumulator chain is D = C, so a
* dependent wmma needs no V_NOP between steps: the hazard the ISA names is A/B overlapping
* the next step's D, and the fragments are fresh registers each step.
*
* The k order is the dot2 arm's contract at the tile boundary: tiles are summed in ascending
* k, and within a tile the sixteen products run in the hardware's fixed order. That is the
* arm's exactness statement: sk = 1 agrees with the reference to the last few bits, the way
* the dot2 arm's splits do, and the row's tolerance gate prices it, not a bit-exact claim.
*
* ---- where the bytes come from --------------------------------------------------------------
*
* The activation is staged in LDS in f16, the checkpoint's own bytes: the f16 builtin takes
* the tile's bits directly, the way the bf16 arm's does, and where the bf16 arm's dot2 pays
* a widening the f16 arm pays nothing at all. One tile is 16 rows x 128 k of f16, the dot2
* arm's k tile, 4.25 KiB with the pitch, and carries eight wmma steps. The pitch is the
* dot2 arm's 68 dwords: 68 mod 32 = 4, so the lanes of a ds_read phase land four banks
* apart and the two 16-byte fragment reads a lane issues per step are conflict-free in
* their phases.
*
* The weight streams from global, one 16-byte pair a lane per step (column L % 16 of the
* tile, the step's 16 k), the NT axis choosing the lowering the dot2 arm's header describes.
* Every weight byte is read once per output tile, the same stream the dot2 arm streams; what
* the arm changes is the issue: one wmma where the dot2 arm issues eight dot4 folds.
*
* ---- the register budget --------------------------------------------------------------------
*
* Eight accumulator VGPRs, eight A, eight B and the pointers: about 34 a lane. Eight waves
* a SIMD asks 272 of the 1024 the gfx11 SIMD keeps, so the block default stands and `wv`
* walks the same ladder as the dot2 arm.
*
* ---- split-K --------------------------------------------------------------------------------
*
* The dot2 arm's slabs and partial plane, with one change: a slab is whole wmma steps, so a
* split is legal only when K % (sk * 16) == 0, and the ragged end is not a scalar tail but a
* step whose fragments zero-fill past K -- the products with zero are the identity and the
* k loop stays uniform. sk = 1 serves a ragged K the dot2 arm serves with its scalar tail.
* The reducer is the dot2 arm's, copied here: the two arms must not share a symbol through a
* header, and twelve lines are cheaper than the coupling.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
namespace {
constexpr int kBlockThreads = 256; // eight waves, the default
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kKTile = 128; // k a staged tile covers, eight wmma steps
constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row, the dot2 arm's 68
constexpr int kUnit = 16; // k a wmma step consumes: a slab's law
/* One dword of two f16 into the fragment's two halves: the low half first, the high half
* after -- the packed order the builtin's VGPR map expects. The cast is a bit pattern, not
* a value: the fragment is the tile's bytes, and a _Float16-from-integer conversion would
* take the integer's magnitude, not its bits. A vector element is not a modifiable lvalue,
* so the unpack is a constructor argument, not a reference target. */
#define R3D_F16(w) __builtin_bit_cast(_Float16, (uint16_t)((w) & 0xffffu)), \
__builtin_bit_cast(_Float16, (uint16_t)((w) >> 16))
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p)
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
/* y[M,N] = a[M,K] @ b[N,K]^T, one 16x16 tile a wave.
*
* `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the
* narrowed f16 the caller asked for. With sk > 1 every split writes its own f32 partial,
* dense [sk][M][N], and the reducer adds them in split order. */
template <bool NT, bool SPLIT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_wmma_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ B,
uint16_t* __restrict__ Y, float* __restrict__ Part,
int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab)
{
/* Staged activation in the checkpoint's own bytes, a dword array at the dot2 arm's pitch. */
__shared__ uint32_t s_a[16 * kAPitch];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t waves = blockDim.x / kWave;
const uint32_t r = lane & 15; // the replicated row/column index
const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * 16 + r;
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
const int kbeg = (int)blockIdx.y * kslab;
const int kend = kbeg + kslab < K ? kbeg + kslab : K;
const uint16_t* w = B + (size_t)n_real * w_ld;
v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
for (int kt = kbeg; kt < kend; kt += kKTile) {
const int kl = std::min(kKTile, kend - kt);
/* Stage 16 rows x kl f16, eight elements a unit, 256 threads. A row past M re-reads
* the last real row, whose products the store drops; a unit past kl zero-fills. */
const int nu = (kl + 7) / 8;
for (int i = (int)tid; i < 16 * nu; i += (int)blockDim.x) {
const int row = i / nu, c = (i % nu) * 8;
const int rr = row < M ? row : M - 1;
const uint16_t* src = A + (size_t)rr * a_ld + kt + c;
uint32_t* dst = s_a + (size_t)row * kAPitch + c / 2;
if (c + 8 <= kl) {
const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src;
*(r3d_u32x4*)dst = q;
} else {
uint32_t p[4] = { 0, 0, 0, 0 };
for (int e = 0; e < kl - c; e += 2) {
const uint32_t lo = ldg_u16(src + e);
const uint32_t hi = (e + 1 < kl - c) ? ldg_u16(src + e + 1) : 0u;
p[e / 2] = lo | (hi << 16);
}
for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e];
}
}
group_barrier();
const uint32_t* ap = s_a + (size_t)r * kAPitch;
for (int k = 0; k < kl; k += 16) {
/* Eight wmma steps per tile: two 16-byte reads a lane, the row's k pair at
* dword k/2 and k/2 + 4, and the column's from global. */
const r3d_u32x4 a0 = *(const r3d_u32x4*)(ap + k / 2);
const r3d_u32x4 a1 = *(const r3d_u32x4*)(ap + k / 2 + 4);
const r3d_u32x4 b0 = ldw<NT>(w + kt + k);
const r3d_u32x4 b1 = ldw<NT>(w + kt + k + 8);
const v16half fa = v16half{ R3D_F16(a0.x), R3D_F16(a0.y), R3D_F16(a0.z),
R3D_F16(a0.w), R3D_F16(a1.x), R3D_F16(a1.y),
R3D_F16(a1.z), R3D_F16(a1.w) };
const v16half fb = v16half{ R3D_F16(b0.x), R3D_F16(b0.y), R3D_F16(b0.z),
R3D_F16(b0.w), R3D_F16(b1.x), R3D_F16(b1.y),
R3D_F16(b1.z), R3D_F16(b1.w) };
acc = wmma_f16(fa, fb, acc);
}
group_barrier(); // the next tile's stage must not race this one's reads
}
const bool keep = (n0 < (uint32_t)N);
if (!keep) return;
for (int g = 0; g < 8; ++g) {
const int m = g * 2 + (int)(lane >> 4);
if (m >= M) continue;
if constexpr (SPLIT)
Part[((size_t)blockIdx.y * M + m) * N + n0] = acc[g];
else
Y[(size_t)m * y_ld + n0] = f32_to_f16(acc[g]);
}
}
#undef R3D_F16
/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one
* narrowing. The dot2 arm's, copied: the slab sums bracket the products differently than
* one chain does, and the difference is in the last bits, the split's, not a bug in it. */
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_wmma_split_reduce(
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
{
const int mn = M * N;
const int stride = gridDim.x * kBlockThreads;
for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) {
const int m = i / N, n = i - m * N;
const float* p = Part + (size_t)m * N + n;
float v = p[0];
for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N];
Y[(size_t)m * y_ld + n] = f32_to_f16(v);
}
}
} // namespace
/* y[M,N] = a[M,K] @ b[N,K]^T, f16 in and out, f32 accumulate, M <= 16, the wave-matrix arm.
*
* The dot2 arm's contract, with the slab law at 16 k. `sk` splits K (0 = the largest legal
* split), `wv` waves per block (0 = 8), `nt` the weight load's lowering, `scratch` the f32
* partial arena, sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null
* pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */
extern "C" int r3d_gemm_nt_f16_m16_wmma(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int wv, int nt, long scratch,
long stream)
{
if (!a || !b || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > 16) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (sk == 0) {
static const int kLadder[] = { 16, 8, 4, 2, 1 };
for (int s : kLadder)
if (s > 1 ? K % ((long long)s * kUnit) == 0 : true) { sk = s; break; }
}
if (sk < 1) return -2;
/* The slab is kUnit deep: a ragged tail (K % kUnit) would stage a partial unit
* the tile loop reads whole (stale dwords) and load B fragments past the weight,
* so the shape is refused, as the dot2 arm's pick_sk already does. */
if (K % ((long long)sk * kUnit)) return -2;
if (sk > 1 && !scratch) return -1;
if (wv <= 0) wv = kWaves;
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2;
const int kslab = K / sk;
#define R3D_WNT(NTV) \
do { \
const int nt_ = (N + 15) / 16; \
const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \
if (sk > 1) { \
R3D_KLAUNCH(R3D_KNAME((gemm_m16_wmma_kernel<NTV, true>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \
const int mn = M * N; \
const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \
R3D_KLAUNCH(gemm_m16_wmma_split_reduce, dim3(nb), dim3(kBlockThreads), \
(hipStream_t)stream, (const float*)scratch, (uint16_t*)y, M, N, y_ld, \
sk); \
} else { \
R3D_KLAUNCH(R3D_KNAME((gemm_m16_wmma_kernel<NTV, false>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \
} \
} while (0)
if (nt) R3D_WNT(true);
else R3D_WNT(false);
#undef R3D_WNT
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+77 -68
View File
@@ -199,40 +199,22 @@ __device__ __forceinline__ float zero_at_w(const WQ h, int n, int g)
/* code * scale in f16: one v_mul_f16, round to nearest, subnormals kept. Not f16x2_pack, which
* truncates (see the header). */
__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc)
{
const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16);
const _Float16 a = __builtin_bit_cast(_Float16, lo16);
const _Float16 b = __builtin_bit_cast(_Float16, hi16);
const _Float16 s = (_Float16)sc;
const _Float16 rl = a * s, rh = b * s;
return (uint32_t)__builtin_bit_cast(uint16_t, rl) |
((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16);
}
/* Eight codes -> four f16 pairs: E4M3 through the table, int8 through the codec's hardware
* convert (two v_cvt_f32_i8 and a pack). */
/* Eight codes -> four f16 pairs. E4M3 through the ALU decode (ALU=1) or the LDS table (ALU=0);
* int8 through the codec's hardware convert (two v_cvt_f32_i8 and a pack). ALU is a template
* parameter so the two rows (the table and the ALU decode) share the kernel and the tune picks. */
template <int ALU>
__device__ __forceinline__ void codes8(const uint2 c, int cdt, const uint16_t* tbl, uint32_t* w)
{
if (!cdt) { r3d_e4m3x8_ld(tbl, c, w); return; }
if (!cdt) {
r3d_e4m3x8_decode<ALU>(tbl, c, w);
return;
}
const uint32_t d[2] = { c.x, c.y };
#pragma unroll
for (int j = 0; j < 4; ++j)
w[j] = i8x2_to_f16x2((d[j >> 1] >> (16 * (j & 1))) & 0xffffu);
}
template <int NT>
__device__ __forceinline__ uint2 loadc8s(const uint8_t* p)
{
typedef uint32_t __attribute__((ext_vector_type(2))) u8v;
u8v v;
if (NT) v = __builtin_nontemporal_load((const u8v*)p);
else __builtin_memcpy(&v, p, 8);
uint2 r;
__builtin_memcpy(&r, &v, 8);
return r;
}
/*
* The tile: 128 x 128 outputs, 256 threads (eight waves), an 8x8 square a lane (64 f32
* accumulators), grid ceil(N/kTN) x ceil(M/kTM). k is walked in chunks of 32; both sides are
@@ -242,19 +224,20 @@ __device__ __forceinline__ uint2 loadc8s(const uint8_t* p)
* ARM 0 is fp8a8 (E4M3 or int8 weight codes); ARM 1 is the zero-point grid (U2 or U4 codes against
* an int8 activation in step order).
*/
template <int NT, int ARM, int CDT> /* CDT: 0 E4M3, 1 int8, 2 U2, 3 U4 */
template <int NT, int ARM, int CDT, int ALU> /* CDT: 0 E4M3, 1 int8, 2 U2, 3 U4; ALU: 1 decode
* in registers, 0 through the LDS table */
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __restrict__ b, WQ h,
void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld)
{
__shared__ __align__(16) uint16_t sA[kTM * kKC];
__shared__ __align__(16) uint16_t sB[kTN * kKC];
__shared__ __align__(16) uint16_t sA[2][kTM * kKC];
__shared__ __align__(16) uint16_t sB[2][kTN * kKC];
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
const int tid = (int)threadIdx.x;
if (ARM == 0) {
r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* E4M3 -> f16 decoder table */
} else {
if (ARM == 0 && !ALU) {
r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* E4M3 -> f16 decoder table (ALU=0) */
} else if (ARM != 0) {
/* U2 and U4 codes are unsigned integers (at most 16 values): the table holds f16(i). */
for (int i = tid; i < 16; i += kBlockThreads) sTbl[i] = f32_to_f16((float)i);
__syncthreads();
@@ -288,14 +271,17 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest
* plane, so each row costs a whole 64-byte sector, 8x the bytes used. A wider k-chunk (64: 4x,
* 128: 2x) would cut that, at a cost in LDS and occupancy. */
for (int k0 = 0; k0 < K; k0 += kKC) {
const int g = k0 / kGroup; /* one group a chunk: 32 divides 128 */
/* Stage slab KS into the BUF-th LDS plane: the A rows and the B rows (or the sub-byte weight
* codes) for k in [KS, KS + kKC), decoded and scale-folded to f16. The double-buffered walk
* calls it for slab k+1 into the other plane while slab k's dot runs, so the global codes load
* overlaps the multiply. */
auto stage_slab = [&](int BUF, int KS) {
const int g = KS / kGroup; /* one group a chunk: 32 divides 128 */
const float sb = scale_w(h, nb, g); /* one scale for the whole tile */
#pragma unroll
for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) {
const int mm = j / (kKC / 8), c8 = j % (kKC / 8);
const int m = m0 + mm, k = k0 + c8 * 8;
const int m = m0 + mm, k = KS + c8 * 8;
uint4 staged = make_uint4(0, 0, 0, 0);
if (m < M) {
if (ARM == 0) {
@@ -303,9 +289,9 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest
* (`aq.gmode` 0) the group term is selected away without a branch. */
const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)];
uint32_t w[4];
codes8(loadc8s<NT>(a + (long long)m * a_ld + k), 0, sTbl, w);
staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa),
fold_pair(w[2], sa), fold_pair(w[3], sa));
codes8<ALU>(r3d_loadc8<NT>(a + (long long)m * a_ld + k), 0, sTbl, w);
staged = make_uint4(r3d_fold_pair(w[0], sa), r3d_fold_pair(w[1], sa),
r3d_fold_pair(w[2], sa), r3d_fold_pair(w[3], sa));
} else {
/* int8 codes in quant_act_i8's step order, read a dword at the permuted
* address (i8_dw), with one scale per row (ZP_I8_ROW). */
@@ -319,31 +305,31 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest
#pragma unroll
for (int q = 0; q < 4; ++q)
w[q] = i8x2_to_f16x2((d[q >> 1] >> (16 * (q & 1))) & 0xffffu);
staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa),
fold_pair(w[2], sa), fold_pair(w[3], sa));
staged = make_uint4(r3d_fold_pair(w[0], sa), r3d_fold_pair(w[1], sa),
r3d_fold_pair(w[2], sa), r3d_fold_pair(w[3], sa));
}
}
*(uint4*)&sA[srow(mm, c8, kKC)] = staged;
*(uint4*)&sA[BUF][srow(mm, c8, kKC)] = staged;
}
if (ARM == 0) {
#pragma unroll
for (int j = tid; j < kTN * (kKC / 8); j += kBlockThreads) {
const int nn = j / (kKC / 8), c8 = j % (kKC / 8);
const int n = n0 + nn, k = k0 + c8 * 8;
const int n = n0 + nn, k = KS + c8 * 8;
uint4 staged = make_uint4(0, 0, 0, 0);
if (n < N) {
uint32_t w[4];
codes8(loadc8s<NT>(h.codes + (long long)n * h.code_row + k), h.cdt, sTbl, w);
staged = make_uint4(fold_pair(w[0], sb), fold_pair(w[1], sb),
fold_pair(w[2], sb), fold_pair(w[3], sb));
codes8<ALU>(r3d_loadc8<NT>(h.codes + (long long)n * h.code_row + k), h.cdt, sTbl, w);
staged = make_uint4(r3d_fold_pair(w[0], sb), r3d_fold_pair(w[1], sb),
r3d_fold_pair(w[2], sb), r3d_fold_pair(w[3], sb));
}
*(uint4*)&sB[srow(nn, c8, kKC)] = staged;
*(uint4*)&sB[BUF][srow(nn, c8, kKC)] = staged;
}
} else {
/* The sub-byte weight: w2a8 (U2, four codes a byte, K>>2 bytes a row) or w4a8_asym
* (U4, two a byte, K>>1). A thread loads a row's whole 32-code chunk at once, 8 bytes
* of U2 or 16 of U4, aligned because k0 is a multiple of 32. Scale and zero are per
* (row, group), prefetched above. */
* of U2 or 16 of U4, aligned because KS is a multiple of 32. Scale and zero are per
* (row, group), prefetched one slab ahead. */
constexpr int BITS = (CDT == 2) ? 2 : 4;
constexpr int FIELD = 2 * BITS; /* bits a pair of codes occupies */
#pragma unroll
@@ -353,14 +339,14 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest
make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0) };
if (n < N) {
const _Float16 s = s_cur, zf = zf_cur; /* the group's pair, prefetched */
if (b_has && k0 + kKC < K && (k0 + kKC) / kGroup != g) {
const int gn = (k0 + kKC) / kGroup;
if (b_has && KS + kKC < K && (KS + kKC) / kGroup != g) {
const int gn = (KS + kKC) / kGroup;
s_cur = (_Float16)scale_at_w(h, b_row, gn);
zf_cur = (_Float16)zero_at_w(h, b_row, gn);
}
uint32_t d[4] = { 0, 0, 0, 0 };
const uint8_t* cp = h.codes + (long long)n * h.code_row
+ (k0 >> (CDT == 2 ? 2 : 1));
+ (KS >> (CDT == 2 ? 2 : 1));
if (CDT == 2) { uint2 v; __builtin_memcpy(&v, cp, 8); d[0] = v.x; d[1] = v.y; }
else { u16v v; __builtin_memcpy(&v, cp, 16);
d[0] = v.x; d[1] = v.y; d[2] = v.z; d[3] = v.w; }
@@ -379,26 +365,36 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest
st[3] = make_uint4(w[12], w[13], w[14], w[15]);
}
#pragma unroll
for (int q = 0; q < 4; ++q) *(uint4*)&sB[srow(nn, q, kKC)] = st[q];
for (int q = 0; q < 4; ++q) *(uint4*)&sB[BUF][srow(nn, q, kKC)] = st[q];
}
}
__syncthreads();
};
/* The double-buffered k-walk: slab 0 is staged before the loop; each iteration stages slab
* k+1 into the other LDS plane while slab k's dot runs from the current plane, then dots. One
* barrier a slab, after the dot, keeps the next slab's stage clear of the dot's LDS reads. */
int tbuf = 0;
stage_slab(0, 0);
__syncthreads();
for (int k0 = 0; k0 < K; k0 += kKC) {
const int k1 = k0 + kKC;
if (k1 < K) stage_slab(1 - tbuf, k1);
#pragma unroll
for (int kc = 0; kc < kKC; kc += 2) {
uint32_t af[8], bf[8];
#pragma unroll
for (int i = 0; i < 8; ++i)
af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)];
af[i] = *(const uint32_t*)&sA[tbuf][srow_pair(rg * 8 + i, kc, kKC)];
#pragma unroll
for (int j = 0; j < 8; ++j)
bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)];
bf[j] = *(const uint32_t*)&sB[tbuf][srow_pair(cg * 8 + j, kc, kKC)];
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]);
}
__syncthreads();
tbuf = 1 - tbuf;
}
/* y is bf16: one narrowing, 16-byte runs of eight columns. Rows past M write nothing. */
@@ -438,7 +434,8 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest
int launch(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, int group,
int a_ld, long long b_row, int as_ld, long long bs_row, int y_ld, int nt, long stream,
int sdt, int cdt, long zv = 0, long long z_row = 0, int srows = 0, int arm = 0)
int sdt, int cdt, long zv = 0, long long z_row = 0, int srows = 0, int arm = 0,
int alu = 1)
{
if (!av || !asv || !bvc || !bsv || !yv) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
@@ -474,18 +471,19 @@ int launch(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K,
WQ h{ (const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv,
(const uint8_t*)(uintptr_t)zv, b_row, bs_row, z_row, sdt, cdt, srows };
hipStream_t s = (hipStream_t)(uintptr_t)stream;
#define R3D_RUN(ARM, CD) \
#define R3D_RUN(NT, ARM, CD, AL) \
fp8a8_tiled_kernel<NT, ARM, CD, AL><<<grd, blk, 0, s>>>( \
(const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \
h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld)
#define R3D_LAUNCH(ARM, CD) \
do { \
if (nt) fp8a8_tiled_kernel<1, ARM, CD><<<grd, blk, 0, s>>>( \
(const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \
h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); \
else fp8a8_tiled_kernel<0, ARM, CD><<<grd, blk, 0, s>>>( \
(const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \
h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); \
if (alu) { if (nt) R3D_RUN(1, ARM, CD, 1); else R3D_RUN(0, ARM, CD, 1); } \
else { if (nt) R3D_RUN(1, ARM, CD, 0); else R3D_RUN(0, ARM, CD, 0); } \
} while (0)
if (arm == 0) { if (cdt == 1) R3D_RUN(0, 1); else R3D_RUN(0, 0); }
else { if (cdt == 3) R3D_RUN(1, 3); else R3D_RUN(1, 2); }
if (arm == 0) { if (cdt == 1) R3D_LAUNCH(0, 1); else R3D_LAUNCH(0, 0); }
else { if (cdt == 3) R3D_LAUNCH(1, 3); else R3D_LAUNCH(1, 2); }
#undef R3D_RUN
#undef R3D_LAUNCH
const hipError_t le = hipGetLastError();
if (le != hipSuccess) {
if (r3d_trace_on())
@@ -627,7 +625,7 @@ static bool gemm_plan_once(long long M, long long N, long long K, unsigned a_ran
return true;
}
extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s)
static int r3d_fp8a8_tiled_dispatch(const RadArgs* args, RadStream s, int alu)
{
if (!args || args->n_t < 5) return R3D_NO(RAD_E_INVAL);
const RadTensor* A = r3d_opt(args, 0);
@@ -814,7 +812,7 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s)
const int nt = (int)r3d_geti_or(args, "nt", 0);
const int st = launch(r3d_addr(A), r3d_addr(AS), (long)(uintptr_t)bvc, (long)(uintptr_t)bsv,
r3d_addr(Y), (int)M, (int)N, (int)K, (int)group, (int)a_ld, b_row,
(int)as_ld, bs_row, (int)y_ld, nt, (long)s, sdt, cdt);
(int)as_ld, bs_row, (int)y_ld, nt, (long)s, sdt, cdt, 0, 0, 0, 0, alu);
if (st == -1) return R3D_NO(RAD_E_INVAL);
if (st == -2) return R3D_NO(RAD_E_SHAPE);
if (st == -3) return R3D_NO(RAD_E_STRIDE);
@@ -978,3 +976,14 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s)
if (st == -4) return R3D_NO(RAD_E_DEVICE);
return RAD_OK;
}
/* The row's impl axis picks the decode: the table (0) and the ALU formula (1). The _alu entry
* point stays for a checker that names it directly. */
extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* a, RadStream s)
{
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
return r3d_fp8a8_tiled_dispatch(a, s, c.impl);
}
extern "C" int r3d_rad_gemm_nt_q_fp8_tiled_alu(const RadArgs* a, RadStream s)
{ return r3d_fp8a8_tiled_dispatch(a, s, 1); }
+22
View File
@@ -46,6 +46,11 @@
#include "r3d_launch.h"
#include "r3d_args.h"
/* The wave-matrix arm's launcher, in r3d_gemm_inta8_wmma.hip: the row's `impl` point 1. */
extern "C" int r3d_gemm_nt_q_w8a8_m16_wmma(long a, long a_scale, long b, long b_scale, long y,
int M, int N, int K, int a_ld, int y_ld,
long long b_rb, long long sb_rb, int nt, long stream);
namespace {
constexpr int kWave = 32;
@@ -412,6 +417,23 @@ extern "C" int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s)
if (yp < N) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
if (c.impl == 1) {
/* The wave-matrix arm: same contract, the i8 tile's, its own launcher. */
const int rc = r3d_gemm_nt_q_w8a8_m16_wmma(r3d_addr(A), r3d_addr(AS), r3d_addr(B),
r3d_addr(BS), r3d_addr(Y), (int)M, (int)N,
(int)K, (int)ap, (int)yp,
(long long)r3d_row_pitch(B),
(long long)r3d_row_pitch(BS), c.nt, (long)s);
if (rc == -1) return R3D_NO(RAD_E_INVAL);
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
return RAD_OK;
}
const int rc = r3d_gemm_nt_q_w8a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp,
(long long)r3d_row_pitch(B), (long long)r3d_row_pitch(BS),
+219
View File
@@ -0,0 +1,219 @@
/* r3d_gemm_inta8_wmma.hip -- the wave-matrix arm of the w8a8 grid at decode heights.
*
* y[M,N] = a[M,K] @ b[N,K]^T, int8 a against signed int8 codes, M <= 16.
*
* The dot2 arm (r3d_gemm_inta8.hip) owns one output element a lane and folds each 128 group's
* products through f16 pairs; this arm issues V_WMMA_I32_16X16X16_IU8 over a 16x16x16 tile, a
* wave a tile, and the two arms are two points of the row's `impl` axis. The tune cache picks
* the point per shape per machine; an untuned install runs the dot2 arm, which is the axis's
* default.
*
* ---- the group law --------------------------------------------------------------------------
*
* The dot2 arm's exactness is the arm's: a group's 128 products are |a * code| <= 127 * 127,
* and their sum 2,064,512 is an exact integer far inside i32, so the eight wmma steps of a
* group chain an i32 sub-sum with no rounding at all, and the group term is the reference's
*
* acc += (sub * a_scale[m]) * b_scale[n, g]
*
* in f32, in ascending group order -- the same order the dot2 arm's shared-memory walk forms.
* What the arm changes is the issue: eight wmma where the dot2 arm issues its decoded dot4
* folds and a pair fold, and the f16 widening the dot2 arm pays on the codes is not here at
* all, the i8 bytes going into the fragment directly.
*
* ---- where the bytes come from --------------------------------------------------------------
*
* The activation is staged in LDS as plain i8, the step order unpermuting on the way in: the
* container's dword at logical position d sits at byte offset dword_pos(d) (the dot2 arm's
* map, its own inverse), so the staging reads the swapped position and writes the plain one. One k tile is 16 rows x 128 i8, one scale group, 2.1 KiB with the pitch, and
* carries eight wmma steps. The pitch is 33 dwords: 33 mod 32 = 1, so the lanes of a
* ds_read phase land one bank apart and the lane's single 16-byte fragment read is
* conflict-free in its phase.
*
* The weight streams from global, one 16-byte load a lane per step (column L % 16 of the
* tile, the step's 16 k), the NT axis choosing the lowering the bf16 arm's header describes.
* Every weight byte is read once per output tile, the stream the dot2 arm streams.
*
* ---- the register budget --------------------------------------------------------------------
*
* Eight f32 accumulators, eight i32 sub-sums, four A and four B fragment VGPRs and the
* pointers: about 30 a lane. Eight waves a SIMD asks 240 of the 1024 the gfx11 SIMD keeps,
* so the quantised rows' fixed eight-wave block stands.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
#include <algorithm>
namespace {
constexpr int kWaves = 8;
constexpr int kBlockThreads = kWaves * kWave;
constexpr int kGroup = 128; /* the scale group: one k tile, eight wmma steps */
constexpr int kPitch = 33; /* dwords a staged a row: 33 mod 32 = 1, bank-free */
/* Signed i8 in, signed i32 out: the builtin's sign selectors take the operands' signedness as
* compile-time constants, both signed for this grid. */
/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse --
* the dot2 arm's, so the staging's read position is the plain position run through it. */
__device__ __forceinline__ int64_t dword_pos(int64_t d)
{
return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1));
}
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldw(const uint8_t* p)
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
/* y[M,N] = a[M,K] @ b[N,K]^T, one 16x16 tile a wave, one scale group a k tile.
*
* The dot2 arm's contract: K a multiple of the group, the group term the reference's, in
* ascending group order. */
template <bool NT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_w8a8_wmma_kernel(
const int8_t* __restrict__ a, const float* __restrict__ sa,
const uint8_t* __restrict__ B, int b_rb, const uint16_t* __restrict__ sb,
int sb_rb, uint16_t* __restrict__ Y,
int M, int N, int K, int a_ld, int y_ld)
{
__shared__ __align__(16) uint32_t s_a[16 * kPitch];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t r = lane & 15; // the replicated row/column index
const uint32_t n0 = (uint32_t)blockIdx.x * kWaves * 16 + wave * 16 + r;
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
/* The lane's eight output rows, and their activation scales, hoisted: a_scale is a row
* property, constant across the group walk. */
float as[8];
#pragma unroll
for (int g2 = 0; g2 < 8; ++g2) {
const int m = g2 * 2 + (int)(lane >> 4);
as[g2] = sa[m < M ? m : M - 1];
}
const uint8_t* w = B + (size_t)n_real * b_rb;
v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
for (int g = 0; g < K / kGroup; ++g) {
const int kt = g * kGroup;
/* Stage 16 rows x 128 i8, the step order unpermuting on the way in. A row past M
* re-reads the last real row, whose products the store drops. */
for (int i = (int)tid; i < 16 * (kGroup / 4); i += kBlockThreads) {
const int row = i / (kGroup / 4), d = i % (kGroup / 4);
const int rr = row < M ? row : M - 1;
/* The dot2 arm's read: a_ld is in elements (bytes, for i8) and dword_pos is already
* the byte offset, the map's own inverse; kt walks the group along the row. */
const uint32_t src =
*(const uint32_t*)(a + (size_t)rr * a_ld + kt + dword_pos(d));
s_a[(size_t)row * kPitch + d] = src;
}
group_barrier();
const uint32_t* ap = s_a + (size_t)r * kPitch;
v8int sub = v8int{ 0, 0, 0, 0, 0, 0, 0, 0 };
for (int k = 0; k < kGroup; k += 16) {
const r3d_u32x4 aq = *(const r3d_u32x4*)(ap + k / 4);
const r3d_u32x4 bq = ldw<NT>(w + kt + k);
sub = wmma_i8(v4int{ (int)aq.x, (int)aq.y, (int)aq.z, (int)aq.w },
v4int{ (int)bq.x, (int)bq.y, (int)bq.z, (int)bq.w }, sub);
}
/* The group term, the reference's parentheses, in ascending group order. The b_scale
* load, its drain, its convert, and the eight fmacs run as one asm block: the load
* goes straight from global (staging it through LDS lets the scheduler move the
* store past the barrier, so a group reads its predecessor's scale), the drain is a
* vmcnt this asm owns, and the scale's register is written only by this block's
* global_load, so no fragment load can clobber it mid-group. v20 is named in the
* clobber because this LLVM aliases a constrained asm output with a dead input
* register; the clobber keeps every t/acc/sub register out of v20 across the block.
* The hardware f16->f32 is exact for normals; subnormal halves flush to 0, below any
* scale this kernel sees and far below the quantisation noise. */
float t[8];
#pragma unroll
for (int g2 = 0; g2 < 8; ++g2)
t[g2] = (float)sub[g2] * as[g2];
{
const uint64_t ga = (uint64_t)(sb + (size_t)n_real * sb_rb + g);
asm volatile(
"global_load_u16 v20, %[ga], off\n\t"
"s_waitcnt vmcnt(0)\n\t"
"v_cvt_f32_f16_e32 v20, v20.l\n\t"
"v_fmac_f32_e32 %[a0], %[t0], v20\n\t"
"v_fmac_f32_e32 %[a1], %[t1], v20\n\t"
"v_fmac_f32_e32 %[a2], %[t2], v20\n\t"
"v_fmac_f32_e32 %[a3], %[t3], v20\n\t"
"v_fmac_f32_e32 %[a4], %[t4], v20\n\t"
"v_fmac_f32_e32 %[a5], %[t5], v20\n\t"
"v_fmac_f32_e32 %[a6], %[t6], v20\n\t"
"v_fmac_f32_e32 %[a7], %[t7], v20"
: [a0] "+v"(acc[0]), [a1] "+v"(acc[1]), [a2] "+v"(acc[2]), [a3] "+v"(acc[3]),
[a4] "+v"(acc[4]), [a5] "+v"(acc[5]), [a6] "+v"(acc[6]), [a7] "+v"(acc[7])
: [ga] "v"(ga),
[t0] "v"(t[0]), [t1] "v"(t[1]), [t2] "v"(t[2]), [t3] "v"(t[3]),
[t4] "v"(t[4]), [t5] "v"(t[5]), [t6] "v"(t[6]), [t7] "v"(t[7])
: "v20");
}
group_barrier(); // the next tile's stage must not race this one's reads
}
const bool keep = (n0 < (uint32_t)N);
if (!keep) return;
#pragma unroll
for (int g2 = 0; g2 < 8; ++g2) {
const int m = g2 * 2 + (int)(lane >> 4);
if (m < M) Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc[g2]);
}
}
} // namespace
/* y[M,N] = a[M,K] @ b[N,K]^T over the w8a8 grid, the wave-matrix arm.
*
* The dot2 arm's contract: K a multiple of the group, the group term the reference's. `nt`
* picks the weight load's lowering. Returns 0, -1 a null pointer, -2 a shape it does not
* serve, -3 a pitch it cannot read, -4 the HIP launch failed, -5 an alignment it cannot
* read. */
extern "C" int r3d_gemm_nt_q_w8a8_m16_wmma(long a, long a_scale, long b, long b_scale, long y,
int M, int N, int K, int a_ld, int y_ld,
long long b_rb, long long sb_rb, int nt, long stream)
{
if (!a || !a_scale || !b || !b_scale || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > 16) return -2;
if (K % kGroup) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (a_ld % 4) return -3;
if (y_ld < N) return -3;
if (!b_rb) b_rb = K;
if (b_rb < K) return -3;
if (b_rb & 15) return -5;
if (!sb_rb) sb_rb = K / kGroup;
if (sb_rb < K / kGroup) return -3;
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
const dim3 grid((N + kWaves * 16 - 1) / (kWaves * 16)), block(kBlockThreads);
if (nt)
R3D_KLAUNCH(gemm_w8a8_wmma_kernel<true>, grid, block, (hipStream_t)stream,
(const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb,
(const uint16_t*)b_scale, (int)sb_rb, (uint16_t*)y, M, N, K, a_ld, y_ld);
else
R3D_KLAUNCH(gemm_w8a8_wmma_kernel<false>, grid, block, (hipStream_t)stream,
(const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb,
(const uint16_t*)b_scale, (int)sb_rb, (uint16_t*)y, M, N, K, a_ld, y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+62 -77
View File
@@ -120,46 +120,6 @@ __device__ __forceinline__ float e8_scale(uint8_t e)
return (e == 0 || e == 255) ? 0.0f : ldexpf(1.0f, (int)e - 127);
}
/* Four e4m3 bytes (one dword, low byte first) as two f16x2, through the block's table. The
* table entries are f16 bit patterns, so the words are moves, not conversions. */
__device__ __forceinline__ void e4m3x4_to_f16x2(const uint16_t* tbl, uint32_t w, uint32_t* o)
{
o[0] = (uint32_t)tbl[w & 0xffu] | ((uint32_t)tbl[(w >> 8) & 0xffu] << 16);
o[1] = (uint32_t)tbl[(w >> 16) & 0xffu] | ((uint32_t)tbl[(w >> 24) & 0xffu] << 16);
}
/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. Not
* f16x2_pack, which truncates. */
__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc)
{
const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16);
const _Float16 a = __builtin_bit_cast(_Float16, lo16);
const _Float16 b = __builtin_bit_cast(_Float16, hi16);
const _Float16 s = (_Float16)sc;
const _Float16 rl = a * s, rh = b * s;
return (uint32_t)__builtin_bit_cast(uint16_t, rl)
| ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16);
}
/* Eight codes -> eight f16, through the table. gfx11 has no E4M3 convert, so the 256-entry
* f16 table stands in for the instruction. */
__device__ __forceinline__ void codes8(const uint2 c, const uint16_t* tbl, uint32_t* w)
{
r3d_e4m3x8_ld(tbl, c, w);
}
template <int NT>
__device__ __forceinline__ uint2 loadc8s(const uint8_t* p)
{
typedef uint32_t __attribute__((ext_vector_type(2))) u8v;
u8v v;
if (NT) v = __builtin_nontemporal_load((const u8v*)p);
else __builtin_memcpy(&v, p, 8);
uint2 r;
__builtin_memcpy(&r, &v, 8);
return r;
}
/* ================================================================== the tiled row */
struct ActQ {
@@ -182,7 +142,7 @@ struct MxWQ {
* are staged as f16 with their scale folded in. The weight's e2m1 nibbles unpack to e4m3 and are
* staged as f16 without the block scale, which is applied to the partials at the chunk's end.
*/
template <int NT>
template <int NT, int ALU> /* ALU: 1 decode in registers, 0 through the LDS table */
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __restrict__ y,
int M, int N, int K, int a_ld, int y_ld)
@@ -193,7 +153,7 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
__shared__ uint8_t sE8[kTN]; /* the chunk's e8, one per tile row */
const int tid = (int)threadIdx.x;
r3d_e4m3_f16_init(sTbl, tid, kBlockThreads);
if (!ALU) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads);
const int m0 = (int)blockIdx.y * kTM;
const int n0 = (int)blockIdx.x * kTN;
@@ -220,9 +180,9 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
if (m < M) {
const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)];
uint32_t w[4];
codes8(loadc8s<NT>(a + (long long)m * a_ld + k), sTbl, w);
staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa),
fold_pair(w[2], sa), fold_pair(w[3], sa));
r3d_e4m3x8_decode<ALU>(sTbl, r3d_loadc8<NT>(a + (long long)m * a_ld + k), w);
staged = make_uint4(r3d_fold_pair(w[0], sa), r3d_fold_pair(w[1], sa),
r3d_fold_pair(w[2], sa), r3d_fold_pair(w[3], sa));
}
*(uint4*)&sA[srow(mm, c8, kKC)] = staged;
}
@@ -244,8 +204,8 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
for (int q = 0; q < 4; ++q) {
uint32_t lo, hi;
mxfp4_unpack8(d[q], &lo, &hi);
e4m3x4_to_f16x2(sTbl, lo, w + 4 * q);
e4m3x4_to_f16x2(sTbl, hi, w + 4 * q + 2);
r3d_e4m3x4_decode<ALU>(sTbl, lo, w + 4 * q);
r3d_e4m3x4_decode<ALU>(sTbl, hi, w + 4 * q + 2);
}
st[0] = make_uint4(w[0], w[1], w[2], w[3]);
st[1] = make_uint4(w[4], w[5], w[6], w[7]);
@@ -317,7 +277,7 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
* a bijection on 16-quad groups. */
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
template <int MT>
template <int MT, int ALU> /* ALU: 1 decode in registers, 0 through the LDS table */
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ sa, int sa_stride,
const uint8_t* __restrict__ b, const uint8_t* __restrict__ e8,
@@ -342,7 +302,7 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
const int kl = lane / MT;
const int nchunk = K / chunk;
r3d_e4m3_f16_init(sTbl, threadIdx.x, kBlockThreads);
if (!ALU) r3d_e4m3_f16_init(sTbl, threadIdx.x, kBlockThreads);
float acc = 0.0f;
for (int ch = 0; ch < nchunk; ++ch) {
@@ -358,9 +318,9 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
const uint32_t w = *(const uint32_t*)(a + (long long)r * a_pitch + k0);
const float s = sa[(long long)r * sa_stride + k0 / kGroup];
uint32_t w2[2];
e4m3x4_to_f16x2(sTbl, w, w2);
lo = fold_pair(w2[0], s);
hi = fold_pair(w2[1], s);
r3d_e4m3x4_decode<ALU>(sTbl, w, w2);
lo = r3d_fold_pair(w2[0], s);
hi = r3d_fold_pair(w2[1], s);
}
const int q = r * (chunk >> 2) + c;
sA[p_ix(q)] = make_uint2(lo, hi);
@@ -386,7 +346,7 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
#pragma unroll
for (int e = 0; e < 2; ++e) {
uint32_t w2[2];
e4m3x4_to_f16x2(sTbl, e ? ehi : elo, w2);
r3d_e4m3x4_decode<ALU>(sTbl, e ? ehi : elo, w2);
const uint2 av = sA[p_ix(qb + 2 * v + e)];
p = dot4_f16x4(av.x, av.y, w2[0], w2[1], p);
}
@@ -439,7 +399,7 @@ static int mt_for(int M)
extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y,
int M, int N, int K, int group, int a_ld, int y_ld,
long long e8_row, long stream)
long long e8_row, long stream, int alu = 1)
{
if (!a || !a_scale || !b || !b_scale || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
@@ -460,20 +420,19 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_sc
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads);
#define R3D_MXFP4A8_M16(MT) \
#define R3D_MXFP4A8_M16(MT) \
do { \
R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel<MT>)), grid, block, (hipStream_t)stream, \
(const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \
(const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \
y_ld); \
if (alu) \
R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel<MT, 1>)), grid, block, (hipStream_t)stream, \
(const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \
(const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \
y_ld); \
else \
R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel<MT, 0>)), grid, block, (hipStream_t)stream, \
(const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \
(const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \
y_ld); \
} while (0)
switch (mt) {
case 1: R3D_MXFP4A8_M16(1); break;
case 2: R3D_MXFP4A8_M16(2); break;
case 4: R3D_MXFP4A8_M16(4); break;
case 8: R3D_MXFP4A8_M16(8); break;
default: R3D_MXFP4A8_M16(16); break;
}
#undef R3D_MXFP4A8_M16
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -489,7 +448,7 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_sc
int launch_mxfp4a8_tiled(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K,
int group, int a_ld, long long b_row, int as_ld, long long e8_row,
int y_ld, int nt, long stream)
int y_ld, int nt, long stream, int alu = 1)
{
if (!av || !asv || !bvc || !bsv || !yv) return -1;
if (M < kMMin || N < 1 || K < 1) return -2;
@@ -516,20 +475,27 @@ int launch_mxfp4a8_tiled(long av, long asv, long bvc, long bsv, long yv, int M,
ActQ aq{(const float*)(uintptr_t)asv, (long long)as_ld, 1};
MxWQ h{(const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv, b_row, e8_row};
hipStream_t s = (hipStream_t)(uintptr_t)stream;
if (nt) mxfp4a8_tiled_kernel<1><<<grd, blk, 0, s>>>(
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
else mxfp4a8_tiled_kernel<0><<<grd, blk, 0, s>>>(
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
if (alu) {
if (nt) mxfp4a8_tiled_kernel<1,1><<<grd, blk, 0, s>>>(
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
else mxfp4a8_tiled_kernel<0,1><<<grd, blk, 0, s>>>(
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
} else {
if (nt) mxfp4a8_tiled_kernel<1,0><<<grd, blk, 0, s>>>(
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
else mxfp4a8_tiled_kernel<0,0><<<grd, blk, 0, s>>>(
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y,
int M, int N, int K, int group, int a_ld,
long long b_row, int as_ld, long long e8_row,
int y_ld, int nt, long stream)
int y_ld, int nt, long stream, int alu)
{
return launch_mxfp4a8_tiled(a, a_scale, b_codes, b_scale, y, M, N, K, group, a_ld, b_row,
as_ld, e8_row, y_ld, nt, stream);
as_ld, e8_row, y_ld, nt, stream, alu);
}
/* ================================================================== the shims
@@ -560,7 +526,7 @@ static bool e8_scan_once(const void* p, long long n)
return true;
}
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s)
static int r3d_mxfp4a8_m16_dispatch(const RadArgs* a, RadStream s, int alu)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
@@ -620,7 +586,7 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s)
const int rc = r3d_gemm_nt_q_mxfp4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
r3d_addr(Y), (int)M, (int)N, (int)K, kGroup,
(int)ap, (int)yp, (long long)r3d_row_pitch(BS),
(long)s);
(long)s, alu);
if (rc == -1) return R3D_NO(RAD_E_INVAL);
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
@@ -629,7 +595,7 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s)
return RAD_OK;
}
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
static int r3d_mxfp4a8_tiled_dispatch(const RadArgs* a, RadStream s, int alu)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
@@ -708,7 +674,7 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
const int rc = r3d_gemm_nt_q_mxfp4a8_tiled(r3d_addr(A), r3d_addr(AS), r3d_addr(B),
r3d_addr(BS), r3d_addr(Y), (int)M, (int)N,
(int)K, kGroup, (int)ap, cp, (int)as_p, e8p,
(int)yp, nt, (long)s);
(int)yp, nt, (long)s, alu);
if (rc == -1) return R3D_NO(RAD_E_INVAL);
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
@@ -717,4 +683,23 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
return RAD_OK;
}
/* The rows' impl axis picks the E4M3 decode: the LDS table (0) and the per-byte ALU formula (1).
* The _alu entry points stay for a checker that names them directly. */
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s)
{
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
return r3d_mxfp4a8_m16_dispatch(a, s, c.impl);
}
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16_alu(const RadArgs* a, RadStream s)
{ return r3d_mxfp4a8_m16_dispatch(a, s, 1); }
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
{
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
return r3d_mxfp4a8_tiled_dispatch(a, s, c.impl);
}
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled_alu(const RadArgs* a, RadStream s)
{ return r3d_mxfp4a8_tiled_dispatch(a, s, 1); }
} // namespace
+623
View File
@@ -0,0 +1,623 @@
/* r3d_gemm_w4a16_nt_m64.hip -- the 4-bit-weight, f16-activation GEMM, M up to 64.
*
* y[M,N] = a[M,K] @ dequant(wq)[N,K]^T, f32 accumulate, narrowed once by the store.
*
* The band is speculative verify and the small prefill chunks, where M is 8 to 64 and the
* weight is still the cost: a wave owns NPW column tiles by MT row tiles and streams the
* weight once. This is the RDNA3 form of the row's RDNA4 sibling. The instruction is the
* same 16x16x16 f16 tile the card's own f16 row runs, but the tile's fragment map is not
* the RDNA4 one, and the port is what the map implies, not a transcription of the other
* card's kernel:
*
* A fragment: lane L holds row L % 16, the tile's sixteen k, replicated across L / 16
* B fragment: lane L holds column L % 16, the tile's sixteen k, replicated across L / 16
* C / D: lane L, VGPR g, holds D[g * 2 + L / 16][L % 16]
*
* (the map the f16 m16 row states, probed green on this card). RDNA4's tile scatters eight
* k a lane "two runs of four" across the half-wave; this one is k-contiguous. The
* consequence is that the tile's natural load is a row's own bytes, and the weight is read
* in the container's stored order -- no permutation, no relayout, the library's own rule:
* a lane's step load is its column's eight codes, a 64-bit read eight bytes down the row a
* step, and a row's 128-byte cache line serves sixteen of its steps, so the line is fully
* consumed before it goes.
*
* The grid is the asymmetric one: unsigned 4-bit codes, an f16 scale and an integer zero
* per 128 of K, an f16 activation. It is the form the quantisers write (compressed-tensors'
* W4A16_ASYM and AutoRound's) and the one the reference library serves, which is what the
* selftest compares against. The symmetric grid (two's-complement nibbles, the zero fixed at
* 8) is the same kernel with one XOR per dword and a fixed zero in the packer.
*
* ---- the dequant --------------------------------------------------------------------------
*
* The codes run the f16 tile on an offset: `0x6400 | n` is exactly the f16 for 1024 + n
* (1024 = 2^10, n < 16 sits in the f16's low mantissa bits), so a nibble becomes a tile
* element with one or, and the zero point is added as a packed f16 constant, -(1024 + zero).
* The subtraction is exact (integers below 2048 in f16's mantissa), and the group scale is
* applied to the f32 accumulator at the group's end. The scale is NOT folded into the
* fragment: fma(1024 + n, s, -(1024 + z) * s) cancels ~1024*s against a result of ~4*s, an
* error of ~12%.
*
* A is f16 and is staged through LDS one 16-row tile at a time: the block copies the tile's
* 16 x (group/8) 16-byte units (the m16 row's pitch, 128 + 8 f16), a barrier, and the
* fragment reads are two 16-byte LDS loads a lane a step. The stage loop is a count loop
* with a per-iteration guard, not a strided `tid; <; += blockDim` -- this backend
* wave-specialises the strided form at small blocks and the upper wave's iterations vanish
* (probed: the wave-1 rows came back NaN, three loop forms, byte-identical). C is bf16,
* narrowed once at the store.
*
* ---- split-K and the reduction -------------------------------------------------------------
*
* `sk` splits K into contiguous slabs of whole 128-wide groups, one per *block*: grid.y is
* (m-tile group, k-split), the block's columns and row tiles come from its own y index, and
* the partial tiles land in a global scratch plane (a grow-only device pool, no per-call
* sync) that a separate reduce kernel sums and narrows. The block-level form is what the
* wave-matrix m16 row runs; a wave-level split on a block-cooperative A stage is a race in
* one LDS tile (probed: the split wave's row-0 fragment held its sibling's k slab). The
* slab sums bracket the products differently than one chain does; the difference is in the
* last bits and is the split's, not a bug in it.
*
* ---- the register budget --------------------------------------------------------------------
*
* NPW*MT accumulators of eight f32, one A fragment of sixteen f16, one B fragment: at the
* 128-VGPR ceiling of a 1024-thread workgroup the backend cannot carry four column tiles a
* wave with more than one row tile (probed: the wmma expansion's A-fragment loads collapse
* and half the tile's rows come back NaN), so the launcher declines `npw == 4 && mb > 1`
* and the tuning path selects around it. `wv` and `sk` are bounded at 32 each: the block
* is WV*32 threads and the split is grid, not workgroup.
*/
#include <hip/hip_runtime.h>
#include <hip/hip_bf16.h>
#include <hip/hip_fp16.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_codecs.h"
#include "rad_planes.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
namespace {
constexpr int kMaxM = 64; // the band's upper bound
constexpr int kGroup = 128; // K per (scale, zero)
constexpr int kStep = 16; // k a wmma step (a B fragment) covers
constexpr int kWave32 = 32;
constexpr int kAPitch = 68; // dwords per staged A row (128 + 8 f16, the m16 pitch)
/* One dword of two f16 into the fragment's two halves, low first: the packed order the
* builtin's VGPR map wants, a bit pattern not a value (the f16 m16 row's R3D_F16). */
#define R3D_W4_F16(w) __builtin_bit_cast(_Float16, (uint16_t)((w) & 0xffffu)), \
__builtin_bit_cast(_Float16, (uint16_t)((w) >> 16))
/* Two dwords of sixteen 4-bit codes (k 0..7 in w0, k 8..15 in w1) -> one 16x16x16 f16 B
* fragment, minus the zero point. Element e is the code for k = e, the k-contiguous map the
* card's tile wants.
*
* The value is code - zero, computed as an integer and converted once per element: the range
* is [-255, 15], exact in f16. The offset form (1024 + n) + (-(1024 + zero)) looks cheaper
* but is not this card: built through packed half pairs it loses registers across the
* unrolled WMMA chain -- probed, the zero point survived in one half of the first pair and
* the code vanished from the load. Integer math plus a constructor list has no union views
* and no half arithmetic to alias. */
__device__ __forceinline__ v16half dequant(unsigned w0, unsigned w1, int z)
{
const int c0 = (int)(w0 & 0xFu) - z, c1 = (int)((w0 >> 4) & 0xFu) - z;
const int c2 = (int)((w0 >> 8) & 0xFu) - z, c3 = (int)((w0 >> 12) & 0xFu) - z;
const int c4 = (int)((w0 >> 16) & 0xFu) - z, c5 = (int)((w0 >> 20) & 0xFu) - z;
const int c6 = (int)((w0 >> 24) & 0xFu) - z, c7 = (int)((w0 >> 28) & 0xFu) - z;
const int c8 = (int)(w1 & 0xFu) - z, c9 = (int)((w1 >> 4) & 0xFu) - z;
const int c10 = (int)((w1 >> 8) & 0xFu) - z, c11 = (int)((w1 >> 12) & 0xFu) - z;
const int c12 = (int)((w1 >> 16) & 0xFu) - z, c13 = (int)((w1 >> 20) & 0xFu) - z;
const int c14 = (int)((w1 >> 24) & 0xFu) - z, c15 = (int)((w1 >> 28) & 0xFu) - z;
return v16half{ __float2half((float)c0), __float2half((float)c1),
__float2half((float)c2), __float2half((float)c3),
__float2half((float)c4), __float2half((float)c5),
__float2half((float)c6), __float2half((float)c7),
__float2half((float)c8), __float2half((float)c9),
__float2half((float)c10), __float2half((float)c11),
__float2half((float)c12), __float2half((float)c13),
__float2half((float)c14), __float2half((float)c15) };
}
/* A block barrier the backend cannot move. The bare __syncthreads() is not enough on this
* toolchain: in unrolled straight-line regions it reorders LDS traffic across the barrier
* (probed: the stage's stores rotated to after the fragment reads; the reduction's fill
* crossed its barrier and the MB > 1 and split-K cases read stale slots). The empty
* memory-clobbered asm is an opaque side effect no pass moves memory ops across. */
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
/* y[M,N] = a[M,K] @ dequant(wq)[N,K]^T. MT row tiles a block, NPW column tiles a wave, SK
* split-K slabs a wave group; the slab partials reduce in the block's dynamic LDS.
*
* Wq is the codes in the container's order, [N][K/2] bytes, row n's k contiguous. Bsz is
* the joined (scale, zero) operand, rad.planes: off_scale and off_zero are the byte
* offsets of the scale plane, [N][K/128] f16, and the zero plane, [N][K/128] u8. */
/* minBlocks 1: the bare 1024 bound caps the register file at ~16 VGPRs a thread (32 waves a
* CUA), which spills every accumulator to the stack and the spill traffic corrupts the LDS
* fill (probed: the split-K plane came back half-filled and the MB > 1 tiles mispaired). */
template <int MT, int NPW, bool NT>
__global__ __launch_bounds__(1024, 1) void r3d_w4a16_m64_kernel(
const unsigned short* __restrict__ A, const unsigned char* __restrict__ Wq,
const unsigned char* __restrict__ Bsz, size_t off_scale, size_t off_zero,
__hip_bfloat16* __restrict__ C, float* __restrict__ Scr,
int M, int K, int N, int a_ld, int y_ld, int WV, int SK, int MTb)
{
/* Staged activation, the f16 m16 row's formulation, one 16-row tile: the row tiles run
* as an outer loop over this single stage (the 16*MT stage miscompiles, probed).
* Function scope: a block-scoped __shared__ here makes the backend's LDS alias analysis
* drop most of the stage's stores (probed: the fragment reads came back stale and
* row-independent). Pitch 136 f16 (68 dwords) = 128 + 8, the m16 pitch. */
__shared__ uint32_t s_a[16 * kAPitch];
/* The split is a BLOCK split, the f16 m16 row's formulation: blockIdx.y = (m tile,
* k split). A wave-level split cannot share the block-cooperative A stage -- two split
* waves staging their own slabs into the one LDS tile race and each wave's fragments
* come back row-mixed (probed: a split wave's row-0 fragment held the other split's
* k slab). */
const int tid = threadIdx.x, wave = tid / kWave32, lane = tid % kWave32;
const int col_local = wave;
const int ksplit = blockIdx.y % SK;
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
const int n0 = nt0 * 16;
const int mt0 = (blockIdx.y / SK) * MT;
const int Ks = K / SK;
const int steps = Ks / kStep;
const int kbase = ksplit * Ks;
const int G = K / kGroup;
v8float acc[NPW][MT];
#pragma unroll
for (int j = 0; j < NPW; j++)
#pragma unroll
for (int i = 0; i < MT; i++) acc[j][i] = (v8float)(0.f);
if (n0 < N) {
/* Weight: the lane's column, eight bytes a step, eight bytes down the row a step.
* The half-wave above replicates the same column. */
const int ntlast = N / 16 - 1;
const unsigned char* pw[NPW];
const unsigned short* ps[NPW];
const unsigned char* pz[NPW];
#pragma unroll
for (int j = 0; j < NPW; j++) {
const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast;
const size_t row = (size_t)t * 16 + (lane & 15);
pw[j] = Wq + row * (K / 2) + kbase / 2;
ps[j] = (const unsigned short*)(Bsz + off_scale) + row * G;
pz[j] = (Bsz + off_zero) + row * G;
}
/* Activation staged in LDS, the f16 m16 row's formulation. Streaming the fragments
* straight from global miscompiles on this toolchain: the unrolled chain's per-step
* loads fold the runtime row stride to the tile's width, so every lane reads the
* first rows and the products come out row-mixed (probed flat across all rows).
* Through LDS the fragment address is a constexpr pitch -- no runtime stride in the
* read the wmma chain consumes.
*
* The stage is ONE 16-row tile and the row tiles run as an outer loop: a
* 16*MT-row stage with the tile index in the fragment read is a miscompile trap
* (probed: the MT > 1 fragments came back e-row mixed, half the tile NaN). One
* tile at a time is the shape the MT == 1 path proves, and it costs the W codes a
* re-read per tile, which L2 serves. */
const int spg = kGroup / kStep; // steps per group
const int spg_rt = (K % kGroup) + kGroup / kStep;
const int ngroups = steps / spg;
for (int i = 0; i < MT; i++) {
const int mrow_base = (mt0 + i) * 16;
for (int g = 0; g < ngroups; g++) {
/* Stage 16 rows x 128 f16 of the group's slab, eight f16 a unit. A row past
* M re-reads the last real row, whose products the store drops.
*
* The unit count is carried as a runtime value the way the f16 m16 row does:
* with a compile-time divisor the backend's i/16 strength reduction drops
* the pitch multiply from the 64-bit LDS offset (probed: the stage stored
* every unit at dword i/16 and the fragments came back stale). K % kGroup
* is 0 by the launcher's contract, so this is 16. */
const int kslab = kbase + g * kGroup;
const int nu = (K % kGroup) + kGroup / 8;
const int nunits = 16 * nu;
/* The stage runs an explicit wave loop: a strided block loop with more than
* one iteration a thread is a trap at small blocks -- the backend
* wave-specialises it and the upper wave's iterations vanish behind its
* exec mask (probed at 64 threads: the wave-1 rows staged nothing and came
* back NaN, identically across three loop forms). With the wave spelled out
* the per-wave work is a distinct loop nest and nothing to CSE away; the
* cost is that every thread walks every wave's units and the guard keeps
* the non-owning threads from storing. */
const int nwaves = (int)blockDim.x / kWave32;
const int nstride = (int)blockDim.x;
const int niter = (nunits + nstride - 1) / nstride;
#pragma unroll 1
for (int w = 0; w < nwaves; w++) {
const int wtid = w * kWave32 + lane;
#pragma unroll 1
for (int k = 0; k < niter; k++) {
const int ui = wtid + k * nstride;
/* No per-wave ownership: a wave whose column group is past N skips
* the whole block, so with an ownership guard the tile's tail rows
* never stage and the D rows they feed come out corrupt (probed:
* N = 64, an eight-wave block, four live column groups, every row
* off by the missing A rows). The tile is 16 x 128 f16 and the
* extra stores are same-value duplicates, ordered by the barrier. */
if (ui < nunits) {
const int row = ui / nu, c = (ui % nu) * 8;
const int mrow = mrow_base + row;
const int mr = mrow < M ? mrow : M - 1;
/* The offset in one 32-bit sum, one 64-bit add: a 64-bit
* add *chain* (mr*K + kslab + c, each term promoted) is a
* trap here -- the kslab term dropped from the lowering
* (probed: a split block's A slab read from kbase 0 while
* its W codes read from the right base). */
const unsigned short* src = A + (size_t)(mr * a_ld + kslab + c);
uint32_t* dst = s_a + (size_t)row * kAPitch + c / 2;
*(r3d_u32x4*)dst = *(const r3d_u32x4*)src;
}
}
}
R3D_BARRIER();
float sc[NPW];
int z[NPW];
/* The planes are indexed by the absolute group; g is the block's local
* group, so a split block must offset by its base (probed: split block 1
* dequantised with group 0's scale and zero and the partials summed wrong). */
const int g_abs = kbase / kGroup + g;
#pragma unroll
for (int j = 0; j < NPW; j++) {
/* The codec's integer conversion, not __half2float: this toolchain's
* builtin returns the raw half bits as a float (probed: 0x3C00 came
* back as 15360.0), which silently scales every group by the bits. */
sc[j] = f16_to_f32((uint16_t)ps[j][(size_t)g_abs]);
z[j] = (int)pz[j][(size_t)g_abs];
}
/* The first WMMA of a group takes an inline zero for C, so no clear is
* needed. The step count is a runtime value, the way the f16 m16 row keeps
* its k loop: with a compile-time count the steps unroll to a
* straight-line block and the backend rotates the group loop, moving the
* stage past the barrier to after the reads. */
v8float g_acc[NPW];
for (int s = 0; s < spg_rt; s++) {
const int u = g * spg + s;
unsigned long long wb[NPW];
#pragma unroll
for (int j = 0; j < NPW; j++) {
/* Eight bytes a step: sixteen 4-bit codes, eight of them a dword. */
wb[j] = NT ? __builtin_nontemporal_load((const unsigned long long*)(pw[j] + 8 * u))
: *(const unsigned long long*)(pw[j] + 8 * u);
}
#pragma unroll
for (int j = 0; j < NPW; j++) {
const v16half bfrag =
dequant((unsigned)wb[j], (unsigned)(wb[j] >> 32), z[j]);
const uint32_t* ap = s_a + (size_t)(lane & 15) * kAPitch + s * 8;
const r3d_u32x4 a0 = *(const r3d_u32x4*)ap;
const r3d_u32x4 a1 = *(const r3d_u32x4*)(ap + 4);
const v16half afrag = v16half{ R3D_W4_F16(a0.x), R3D_W4_F16(a0.y),
R3D_W4_F16(a0.z), R3D_W4_F16(a0.w),
R3D_W4_F16(a1.x), R3D_W4_F16(a1.y),
R3D_W4_F16(a1.z), R3D_W4_F16(a1.w) };
g_acc[j] = s == 0 ? wmma_f16(afrag, bfrag, (v8float)(0.f))
: wmma_f16(afrag, bfrag, g_acc[j]);
}
}
/* All-runtime loops. This toolchain's unrolled index math is a miscompile
* trap (probed across builds: an unrolled fold mispaired e == 0 with the
* previous tile's e == 7 register). Runtime trip counts keep the register
* handling honest; the loop is tiny. */
for (int j = 0; j < NPW; j++)
for (int e = 0; e < kWave32 / 4; e++)
acc[j][i][e] = fmaf(g_acc[j][e], sc[j], acc[j][i][e]);
R3D_BARRIER(); // the next slab's stage must not race these reads
}
}
}
/* Epilogue. The D map: acc element e is output row 2e + lane/16, column lane%16.
*
* Store straight from the lane's registers, to the output (SK == 1) or to the global
* split-partial arena (SK > 1, summed by r3d_w4a16_split_reduce). The dynamic-LDS
* partial plane this used to run through is a miscompile trap on this toolchain,
* probed across many builds: the fill fused with the read loop, an e * 32 stride
* collapsed to e * 8, a lane * 8 index lost its lane / 16 bit. Global stores have
* none of that surface. */
const int ncols = WV * NPW;
for (int i = 0; i < MT; i++) {
const int m0 = (mt0 + i) * 16;
for (int j = 0; j < NPW; j++) {
const int n0 = (nt0 + j) * 16;
const int col_g = blockIdx.x * ncols + (col_local * NPW + j);
for (int e = 0; e < kWave32 / 4; e++) {
const int m = m0 + 2 * e + (lane >> 4);
const int n = n0 + (lane & 15);
if (SK == 1) {
/* Integer-narrowed store: a bf16-typed store on this toolchain lowers
* through a numeric f32->bf16->integer conversion that replaces the
* half bits with the rounded value's bits; the codec's bit manipulation
* returns the bits straight. */
if (m < M && n < N)
((uint16_t*)C)[(size_t)m * y_ld + n] = f32_to_bf16(acc[j][i][e]);
} else {
/* The partial plane is fully sized: clamped rows store too, the reduce
* drops them. The pool is sized for ntiles, and the grid's last column
* group strides past it when ntiles % ncols != 0. */
if (col_g < N / 16) {
const size_t o =
(((size_t)col_g * SK + ksplit) * MTb + i) * 256 + (e * kWave32 + lane);
Scr[o] = acc[j][i][e];
}
}
}
}
}
}
/* The f16-accumulator arm is shelved, and the reason is the card's, probed on this one:
* the f16-acc instruction takes a compile-time column selector and computes a 16-wide
* column window of the 32-column space, and its 16x16 D tile carries only 15 rows --
* rows 1..15 of the A tile, row 0 absent (the 256 fragment slots hold 15 rows x 16
* columns and 16 pass-through halves). A 16-row M tile loses a row on every tile
* boundary, which no staging shift fixes without a 17-row overlap the block-cooperative
* stage does not have. The row runs the f32 arm; `acc` stays a tuning axis with the f32
* point, the f16 point joins when a row-overlapping stage is measured to pay.
*/
/* The split-K reduce: y = the SK partial tiles summed, narrowed once. One thread per
* (column tile, row tile, tile element); the element's (m, n) is the D map inverted. */
__global__ void r3d_w4a16_split_reduce(const float* __restrict__ Scr,
__hip_bfloat16* __restrict__ C,
int M, int N, int y_ld, int SK, int MTb, int ntiles)
{
const int total = ntiles * MTb * 256;
for (int idx = blockIdx.x * blockDim.x + threadIdx.x; idx < total;
idx += gridDim.x * blockDim.x) {
const int tile = idx / 256, off = idx % 256;
const int i = tile % MTb, col_g = tile / MTb;
float v = 0.f;
for (int s = 0; s < SK; s++)
v += Scr[(((size_t)col_g * SK + s) * MTb + i) * 256 + off];
const int l = off & 31, e = off >> 5;
const int m = i * 16 + 2 * e + (l >> 4), n = col_g * 16 + (l & 15);
if (m < M && n < N) ((uint16_t*)C)[(size_t)m * y_ld + n] = f32_to_bf16(v);
}
}
} // namespace
/* y[M,N] = a[M,K] @ dequant(wq)[N,K]^T, f16 a, bf16 y, M <= 64.
*
* a [M][K] f16, k contiguous
* wq [N][K/2] the codes in the container's order
* bsz the joined (scale, zero) operand: the f16 scale plane, [N][K/128], then the u8
* zero plane, [N][K/128], at off_scale and off_zero
* y [M][N] bf16, row-major
*
* `wv` waves per block (0 = 8), `sk` the K split (0 = 1), `mb` row tiles per block (0 = 1),
* `npw` column tiles a wave (0 = 1; 1 or 4), `nt` the weight load's lowering, `acc` the
* accumulator (0 = the f32 arm, the arm served; 1 = the f16 arm, declined, see the
* shelved-arm note; negative-for-absent = 0). Returns 0, -1 a null pointer, -2 a shape it
* does not serve, -4 the HIP launch failed. */
/* The split-partial pool: file scope, grown only, so a call never syncs the stream. */
static float* s_scratch_pool = nullptr;
static size_t s_scratch_sz = 0;
extern "C" int r3d_gemm_nt_q_w4a16_m64(long a, long wq, long bsz, size_t off_scale,
size_t off_zero, long y, int M, int N, int K,
int a_ld, int y_ld,
int wv, int sk, int mb, int npw, int nt, int acc,
long stream)
{
if (!a || !wq || !bsz || !y) return -1;
if (M < 1 || M > kMaxM) return -2;
if (N < 16 || N % 16) return -2;
if (K < kGroup || K % kGroup) return -2;
if (wv <= 0) wv = 8;
if (sk <= 0) sk = 1;
if (mb <= 0) mb = 1;
if (npw <= 0) npw = 1;
if (acc < 0) acc = 0;
if (acc > 1) return -2;
if (wv > 32 || sk > 32) return -2;
if (mb < 1 || mb > 4) return -2;
if (npw != 1 && npw != 4) return -2;
if (K % (sk * kGroup)) return -2;
/* npw=4 with mb>1 is the shape the backend cannot lower: at the 128-VGPR ceiling the
* wmma expansion's A-fragment loads collapse (probed: the 64-thread <2,4> tile came
* back with half its rows NaN). The tuning path selects around it: npw=4 with mb=1,
* or npw=1 with the mb it wants. The f16 arm is shelved (its tile drops a row, probed):
* the axis carries no f16 point, the launcher declines it. */
if (npw == 4 && mb > 1) return -2;
if (acc == 1) return -2;
const int ntiles = N / 16, mtiles = (M + 15) / 16;
const int ncols = wv * npw;
const dim3 grid((ntiles + ncols - 1) / ncols, ((mtiles + mb - 1) / mb) * sk),
block(wv * kWave32);
/* Split partials live in a grow-only device pool: a per-call hipMalloc/Free would
* synchronise the stream. */
float* scr = nullptr;
if (sk > 1) {
const size_t bytes = (size_t)ntiles * sk * mb * 256 * sizeof(float);
if (bytes > s_scratch_sz) {
if (s_scratch_pool) hipFree(s_scratch_pool);
if (hipMalloc(&s_scratch_pool, bytes) != hipSuccess) return -4;
s_scratch_sz = bytes;
}
scr = s_scratch_pool;
}
#define R3D_W4L(MT, NP, TT) \
R3D_KLAUNCH_S(R3D_KNAME((r3d_w4a16_m64_kernel<MT, NP, TT>)), grid, block, 0, \
(hipStream_t)stream, (const unsigned short*)a, (const unsigned char*)wq, \
(const unsigned char*)bsz, off_scale, off_zero, (__hip_bfloat16*)y, scr, \
M, K, N, a_ld, y_ld, wv, sk, mb)
#define R3D_W4L_MB(NP, TT) \
do { switch (mb) { \
case 1: R3D_W4L(1, NP, TT); break; \
case 2: R3D_W4L(2, NP, TT); break; \
case 3: R3D_W4L(3, NP, TT); break; \
default: R3D_W4L(4, NP, TT); break; } } while (0)
if (npw == 1) { if (nt) R3D_W4L_MB(1, true); else R3D_W4L_MB(1, false); }
else { if (nt) R3D_W4L_MB(4, true); else R3D_W4L_MB(4, false); }
#undef R3D_W4L_MB
#undef R3D_W4L
if (hipGetLastError() != hipSuccess) return -4;
if (sk > 1) {
const int total = ntiles * mb * 256;
const int rblock = 256;
const int rgrid = (total + rblock - 1) / rblock;
R3D_KLAUNCH_S(R3D_KNAME((r3d_w4a16_split_reduce)), dim3(rgrid), rblock, 0,
(hipStream_t)stream, scr, (__hip_bfloat16*)y, M, N, y_ld, sk, mb, ntiles);
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* ==================================================================== the plugin ABI entry point
*
* gemm_nt_q's operand list is [a, a_scale, b, b_scale, y, a_sum, b_ref]; this row takes a,
* b, b_scale and y, and declines the rest. b is the codes plane in the container's order;
* b_scale is the (scale, zero) pair in rad.planes' joined form. */
enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF };
extern "C" int r3d_rad_gemm_nt_q_w4a16_m64(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
if (!dt || std::strcmp(dt, "w4a16_asym") != 0) return R3D_NO(RAD_E_DTYPE);
const RadTensor* A = r3d_opt(a, Q_A);
const RadTensor* AS = r3d_opt(a, Q_ASCALE);
const RadTensor* B = r3d_opt(a, Q_B);
const RadTensor* BS = r3d_opt(a, Q_BSCALE);
const RadTensor* Y = r3d_opt(a, Q_Y);
const RadTensor* AU = r3d_opt(a, Q_ASUM);
const RadTensor* BR = r3d_opt(a, Q_BREF);
if (!r3d_p(A) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL);
/* Any other operand would read plausible but wrong numbers. */
if (r3d_has(AS) || r3d_has(AU) || r3d_has(BR)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f16(A)) return R3D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_U4) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
if (N % 16) return R3D_NO(RAD_E_SHAPE);
if (K % kGroup) return R3D_NO(RAD_E_SHAPE);
const long long ynel = r3d_numel(Y);
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = ynel / N;
if (M < 1 || M > kMaxM) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(B) < (N * K) / 2) return R3D_NO(RAD_E_SHAPE);
/* The joined form, read at launch: the scale and zero planes, and their byte offsets. */
const RadPlanesEntry* es = nullptr, *ez = nullptr;
const uint8_t* sc_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "scale", &es);
const uint8_t* z_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "zero", &ez);
if (!sc_b || !z_b || es->dtype != RAD_F16 || ez->dtype != RAD_U8)
return R3D_NO(RAD_E_DTYPE);
if (es->rows < N || ez->rows < N) return R3D_NO(RAD_E_SHAPE);
const long long ap = r3d_row_pitch(A);
if (ap < K) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
if (yp < N || yrows < M) return R3D_NO(RAD_E_STRIDE);
/* 16-byte A fragment reads and 8-byte weight reads, both at aligned bases. */
if (!r3d_aligned(r3d_p(A), 16) || !r3d_aligned(r3d_p(B), 8)) return R3D_NO(RAD_E_ALIGN);
const int wv = (int)r3d_geti_or(a, "wv", 8);
const int sk = (int)r3d_geti_or(a, "sk", 1);
const int mb = (int)r3d_geti_or(a, "mb", 1);
const int npw = (int)r3d_geti_or(a, "npw", 1);
const int nt = (int)r3d_geti_or(a, "nt", 1);
const int acc = (int)r3d_geti_or(a, "acc", 0);
const int e = r3d_gemm_nt_q_w4a16_m64(r3d_addr(A), r3d_addr(B), r3d_addr(BS),
(size_t)(sc_b - (const uint8_t*)r3d_p(BS)),
(size_t)(z_b - (const uint8_t*)r3d_p(BS)),
r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp,
wv, sk, mb, npw, nt, acc, (long)(uintptr_t)s);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE : RAD_E_DEVICE);
}
/* ==================================================================== the (scale, zero) pair
*
* The weight's scale and zero are two planes behind the one b_scale operand, and the mapped
* tier places a weight only when a loaded library can read it in place. This is the scoped
* exception to the library's "no layout hooks, no repacking" rule, transcribed from the
* reference's own hook:
*
* if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
* the grid's dtype is "w4a16_asym";
* the affine encoding: U4 codes block {1,1}, f16 scale block {1, group}, u8 zero block
* {1, group}; the transform empty or beginning "givens";
* sel names "scale" and "zero", in order;
* return rad_planes_layout(enc, sel, planes, n, out);
*
* NOTHING HERE MOVES A BYTE: the writer is rad_planes_relayout, and the codes plane is read
* where it lies -- the kernel's load is the container's order, which is the point.
*/
extern "C" int r3d_layout_gemm_nt_q_w4a16(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out)
{
if (n < 2 || operand != Q_BSCALE) return RAD_E_UNSUPPORTED;
const char* d = r3d_pgets(p, n_p, "dtype");
if (!d || std::strcmp(d, "w4a16_asym") != 0) return RAD_E_DTYPE;
const long long group = r3d_pgeti_or(p, n_p, "group", kGroup);
if (group <= 0) return RAD_E_DTYPE;
if (!enc || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
if (enc->n_planes < 3) return RAD_E_DTYPE;
if (n != 2) return RAD_E_DTYPE;
for (int i = 0; i < 2; ++i) {
const char* want = i == 0 ? "scale" : "zero";
if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_DTYPE;
if (std::strncmp(enc->plane[sel[i]].role, want, RAD_ENC_STR) != 0) return RAD_E_DTYPE;
}
/* The codes plane is the one this operand does not take: U4, block {1,1}. */
int codes = -1;
for (int i = 0; i < enc->n_planes; ++i)
if (std::strncmp(enc->plane[i].role, "codes", RAD_ENC_STR) == 0) { codes = i; break; }
if (codes < 0 || enc->plane[codes].dtype != RAD_U4 ||
enc->plane[codes].block[0] != 1 || enc->plane[codes].block[1] != 1)
return RAD_E_DTYPE;
for (int i = 0; i < 2; ++i) {
const RadEncPlane* q = &enc->plane[sel[i]];
if (q->kind != RAD_PLANE_TILED || q->block[0] != 1 || q->block[1] != group)
return RAD_E_DTYPE;
if (i == 0 && q->dtype != RAD_F16) return RAD_E_DTYPE;
if (i == 1 && q->dtype != RAD_U8) return RAD_E_DTYPE;
}
return rad_planes_layout(enc, sel, pl, n, out);
}
/* The writer for the joined operand this hook names: scale and zero as the plan's one
* rad.planes weight, assembled by rad_planes_relayout. The ABI's contract is that a query
* answering RAD_OK is a promise the loader keeps on the row's word (rad_abi.h). */
extern "C" int r3d_relayout_gemm_nt_q_w4a16(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
int64_t dst_bytes)
{
(void)p; (void)n_p;
if (operand != Q_BSCALE) return RAD_E_UNSUPPORTED;
return rad_planes_relayout(enc, sel, pl, n, dst, dst_bytes);
}
+509
View File
@@ -0,0 +1,509 @@
/* r3d_gemm_w5a16_nt_m64.hip -- the 5-bit-weight skinny GEMM, M up to 64.
*
* The w4a16 row with a fifth bit per weight, for ParoQuant's int5 (asymmetric: an f16 scale and
* a 5-bit integer zero per 128 of K). The weight arrives as three planes behind the one
* b_scale operand, joined rad.planes, the codes as the B operand in the container's order:
*
* codes [N][K/2] u4, the w4a16 fragment order (element e is k = e)
* scale [N][K/128] f16
* zero [N][K/128] u8, 0..31
* hi [N/16][K/2] u32: word (t, kb, lane) holds the fifth bits of tile t's k block
* kb, lane's 32 weights: byte s is k step s of the 64-wide block, bit e is
* fragment element e
*
* The dequant is the w4a16's integer code minus the zero point, the code widened with its fifth
* bit (0..31, exact in f16 after the subtract: the range is [-31, 31]). The rest of the
* kernel is the w4a16 row's, and its header notes apply: the block-level split, the
* block-cooperative LDS stage, the runtime trip counts, the pinned barriers, the 128-VGPR
* ceiling's npw==4 && mb>1 refusal.
*/
#include <hip/hip_runtime.h>
#include <hip/hip_bf16.h>
#include <hip/hip_fp16.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_codecs.h"
#include "rad_planes.h"
#include <algorithm>
#include <cstring>
namespace {
constexpr int kMaxM = 64;
constexpr int kGroup = 128;
constexpr int kStep = 16;
constexpr int kWave32 = 32;
constexpr int kAPitch = 68; // dwords per staged A row (128 + 8 f16, the m16 pitch)
/* One dword of two f16 into the fragment's two halves, low first: the packed order the
* builtin's VGPR map wants, a bit pattern not a value. */
#define R3D_W5_F16(w) __builtin_bit_cast(_Float16, (uint16_t)((w) & 0xffffu)), \
__builtin_bit_cast(_Float16, (uint16_t)((w) >> 16))
/* Two dwords of sixteen 4-bit codes plus the two bytes of their fifth bits -> one 16x16x16
* f16 B fragment, minus the zero point. Element e is the code for k = e, the k-contiguous
* map the card's tile wants: nibble 2e (e < 4), 2(e-4)+1 (e < 8), then w1's 2(e-8),
* 2(e-12)+1.
*
* The fifth bits: a byte covers eight k, the even ones in its low four bits (bit l/2), the
* odd in its high four (bit 4 + l/2), l the k within the eight -- the reference
* quantiser's spread16 form. The step's sixteen k are two bytes: hb0 is k 0..7, hb1 is
* k 8..15.
*
* The value is code - zero as an integer, converted once per element: the range is
* [-31, 31], exact in f16. No offset form, no half arithmetic: the w4a16 row's probe
* history is the reason (the packed-half construction lost registers across the unrolled
* WMMA chain). */
__device__ __forceinline__ v16half dequant5(unsigned w0, unsigned w1, unsigned hb0,
unsigned hb1, int z)
{
/* The bits are extracted inline, not materialised: sixteen named bit registers push
* the kernel over the 128-VGPR ceiling and the A fragment loads collapse.
*
* The nibbles are k-contiguous (w0 = kk 0..7, w1 = kk 8..15) but the fifth-bit
* words are the reference layout's lh split: h0 holds kk 0,1,2,3,8,9,10,11 at
* bits 0,2,4,6,1,3,5,7 and h1 holds kk 4,5,6,7,12,13,14,15 at the same bit
* order. Element e is kk e, so the bit source crosses the e 8 boundary: e 4..7
* and 12..15 take h1, e 8..11 take h0 (probe C7: a k-dependent A exposes the
* mispairing a per-row-constant A erases). */
const unsigned h0 = hb0 & 0xFFu, h1 = hb1 & 0xFFu;
const int c0 = (int)((w0 & 0xFu) | (((h0 >> 0) & 1u) << 4)) - z;
const int c1 = (int)(((w0 >> 4) & 0xFu) | (((h0 >> 2) & 1u) << 4)) - z;
const int c2 = (int)(((w0 >> 8) & 0xFu) | (((h0 >> 4) & 1u) << 4)) - z;
const int c3 = (int)(((w0 >> 12) & 0xFu) | (((h0 >> 6) & 1u) << 4)) - z;
const int c4 = (int)(((w0 >> 16) & 0xFu) | (((h1 >> 0) & 1u) << 4)) - z;
const int c5 = (int)(((w0 >> 20) & 0xFu) | (((h1 >> 2) & 1u) << 4)) - z;
const int c6 = (int)(((w0 >> 24) & 0xFu) | (((h1 >> 4) & 1u) << 4)) - z;
const int c7 = (int)(((w0 >> 28) & 0xFu) | (((h1 >> 6) & 1u) << 4)) - z;
const int c8 = (int)((w1 & 0xFu) | (((h0 >> 1) & 1u) << 4)) - z;
const int c9 = (int)(((w1 >> 4) & 0xFu) | (((h0 >> 3) & 1u) << 4)) - z;
const int c10 = (int)(((w1 >> 8) & 0xFu) | (((h0 >> 5) & 1u) << 4)) - z;
const int c11 = (int)(((w1 >> 12) & 0xFu) | (((h0 >> 7) & 1u) << 4)) - z;
const int c12 = (int)(((w1 >> 16) & 0xFu) | (((h1 >> 1) & 1u) << 4)) - z;
const int c13 = (int)(((w1 >> 20) & 0xFu) | (((h1 >> 3) & 1u) << 4)) - z;
const int c14 = (int)(((w1 >> 24) & 0xFu) | (((h1 >> 5) & 1u) << 4)) - z;
const int c15 = (int)(((w1 >> 28) & 0xFu) | (((h1 >> 7) & 1u) << 4)) - z;
return v16half{ __float2half((float)c0), __float2half((float)c1),
__float2half((float)c2), __float2half((float)c3),
__float2half((float)c4), __float2half((float)c5),
__float2half((float)c6), __float2half((float)c7),
__float2half((float)c8), __float2half((float)c9),
__float2half((float)c10), __float2half((float)c11),
__float2half((float)c12), __float2half((float)c13),
__float2half((float)c14), __float2half((float)c15) };
}
/* A block barrier the backend cannot move; see the w4a16 row's note. */
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
/* y[M,N] = a[M,K] @ dequant(wq, hi)[N,K]^T. The w4a16 row's kernel with the fifth-bit
* plane: per group the two 64-wide blocks' words, one a lane, then the step's byte. */
template <int MT, int NPW, bool NT>
__global__ __launch_bounds__(1024, 1) void r3d_w5a16_m64_kernel(
const unsigned short* __restrict__ A, const unsigned char* __restrict__ Wq,
const unsigned char* __restrict__ Bsz, size_t off_scale, size_t off_zero, size_t off_hi,
__hip_bfloat16* __restrict__ C, float* __restrict__ Scr,
int M, int K, int N, int a_ld, int y_ld, int WV, int SK, int MTb)
{
__shared__ uint32_t s_a[16 * kAPitch];
const int tid = threadIdx.x, wave = tid / kWave32, lane = tid % kWave32;
const int col_local = wave;
const int ksplit = blockIdx.y % SK;
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
const int n0 = nt0 * 16;
const int mt0 = (blockIdx.y / SK) * MT;
const int Ks = K / SK;
const int steps = Ks / kStep;
const int kbase = ksplit * Ks;
const int G = K / kGroup;
v8float acc[NPW][MT];
#pragma unroll
for (int j = 0; j < NPW; j++)
#pragma unroll
for (int i = 0; i < MT; i++) acc[j][i] = (v8float)(0.f);
if (n0 < N) {
/* Weight: the lane's column, eight bytes a step; the fifth bits, one word a
* 64-wide block; the planes indexed by the absolute group. */
const int ntlast = N / 16 - 1;
const unsigned char* pw[NPW];
const unsigned short* ps[NPW];
const unsigned char* pz[NPW];
size_t hibase[NPW];
#pragma unroll
for (int j = 0; j < NPW; j++) {
const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast;
const size_t row = (size_t)t * 16 + (lane & 15);
pw[j] = Wq + row * (K / 2) + kbase / 2;
ps[j] = (const unsigned short*)(Bsz + off_scale) + row * G;
pz[j] = (Bsz + off_zero) + row * G;
/* The hi plane's byte base for this tile: [N/16][K/2] u32, the tile's
* words are (K/2) u32 = K/2*4 bytes. */
hibase[j] = (size_t)t * (K / 2) * 4;
}
const int spg = kGroup / kStep;
const int spg_rt = (K % kGroup) + kGroup / kStep;
const int ngroups = steps / spg;
for (int i = 0; i < MT; i++) {
const int mrow_base = (mt0 + i) * 16;
for (int g = 0; g < ngroups; g++) {
/* Stage 16 rows x 128 f16 of the group's slab, eight f16 a unit; the
* w4a16 row's guarded wave loop, its notes apply. */
const int kslab = kbase + g * kGroup;
const int nu = (K % kGroup) + kGroup / 8;
const int nunits = 16 * nu;
const int nwaves = (int)blockDim.x / kWave32;
const int nstride = (int)blockDim.x;
const int niter = (nunits + nstride - 1) / nstride;
#pragma unroll 1
for (int w = 0; w < nwaves; w++) {
const int wtid = w * kWave32 + lane;
#pragma unroll 1
for (int k = 0; k < niter; k++) {
const int ui = wtid + k * nstride;
if (ui < nunits && (w * kWave32) <= tid) {
const int row = ui / nu, c = (ui % nu) * 8;
const int mrow = mrow_base + row;
const int mr = mrow < M ? mrow : M - 1;
const unsigned short* src = A + (size_t)(mr * a_ld + kslab + c);
uint32_t* dst = s_a + (size_t)row * kAPitch + c / 2;
*(r3d_u32x4*)dst = *(const r3d_u32x4*)src;
}
}
}
R3D_BARRIER();
float sc[NPW];
int z[NPW];
const int g_abs = kbase / kGroup + g;
#pragma unroll
for (int j = 0; j < NPW; j++) {
sc[j] = f16_to_f32((uint16_t)ps[j][(size_t)g_abs]);
z[j] = (int)pz[j][(size_t)g_abs];
}
/* The group's fifth-bit bytes, one a lane: the group is 128 wide, eight
* steps: steps 0..3 are 64-block 2g, steps 4..7 are block 2g+1. The
* lane's words are (t, kb, column) and (t, kb, 16 + column), the
* reference layout's lh split; the byte pointer is the word's first
* byte. */
const int kb0 = kbase / (kGroup / 2) + 2 * g;
/* The step's two fifth-bit bytes, loaded from global memory as bytes at
* plain runtime addresses -- the form the W loads use and the card
* honours. Every select shape tried before this is miscompiled: a
* runtime shift by the step's amount drops the bytes, an if/else chain
* leaks a branch into the other steps, a stack-array index collapses to
* 0, a mask-OR select leaks a value (probe C6). Two blocks of four
* steps; the block's byte pointer is set once per block. */
v8float g_acc[NPW];
#pragma unroll
for (int j = 0; j < NPW; j++) g_acc[j] = (v8float)(0.f);
for (int b2 = 0; b2 < 2; b2++) {
for (int j = 0; j < NPW; j++) {
const unsigned char* p0 = (const unsigned char*)(Bsz + off_hi)
+ hibase[j]
+ (size_t)(kb0 + b2) * kWave32 * 4 + (lane & 15) * 4;
const unsigned char* p1 = p0 + 16 * 4;
for (int sb = 0; sb < 4; sb++) {
const int s = 4 * b2 + sb;
const int u = g * spg + s;
const unsigned long long wbj =
NT ? __builtin_nontemporal_load((const unsigned long long*)(pw[j] + 8 * u))
: *(const unsigned long long*)(pw[j] + 8 * u);
const unsigned hb0 = (unsigned)*(p0 + sb);
const unsigned hb1 = (unsigned)*(p1 + sb);
const v16half bfrag =
dequant5((unsigned)wbj, (unsigned)(wbj >> 32), hb0, hb1, z[j]);
const uint32_t* ap = s_a + (size_t)(lane & 15) * kAPitch + s * 8;
const r3d_u32x4 a0 = *(const r3d_u32x4*)ap;
const r3d_u32x4 a1 = *(const r3d_u32x4*)(ap + 4);
const v16half afrag = v16half{ R3D_W5_F16(a0.x), R3D_W5_F16(a0.y),
R3D_W5_F16(a0.z), R3D_W5_F16(a0.w),
R3D_W5_F16(a1.x), R3D_W5_F16(a1.y),
R3D_W5_F16(a1.z), R3D_W5_F16(a1.w) };
g_acc[j] = wmma_f16(afrag, bfrag, g_acc[j]);
}
}
}
for (int j = 0; j < NPW; j++)
for (int e = 0; e < kWave32 / 4; e++)
acc[j][i][e] = fmaf(g_acc[j][e], sc[j], acc[j][i][e]);
R3D_BARRIER(); // the next slab's stage must not race these reads
}
}
}
/* Epilogue: the w4a16 row's D map and store; the notes apply. */
const int ncols = WV * NPW;
for (int i = 0; i < MT; i++) {
const int m0 = (mt0 + i) * 16;
for (int j = 0; j < NPW; j++) {
const int n0 = (nt0 + j) * 16;
const int col_g = blockIdx.x * ncols + (col_local * NPW + j);
for (int e = 0; e < kWave32 / 4; e++) {
const int m = m0 + 2 * e + (lane >> 4);
const int n = n0 + (lane & 15);
if (SK == 1) {
if (m < M && n < N)
((uint16_t*)C)[(size_t)m * y_ld + n] = f32_to_bf16(acc[j][i][e]);
} else {
/* The pool is sized for ntiles; the grid's last column group strides
* past it when ntiles % ncols != 0. */
if (col_g < N / 16) {
const size_t o =
(((size_t)col_g * SK + ksplit) * MTb + i) * 256 + (e * kWave32 + lane);
Scr[o] = acc[j][i][e];
}
}
}
}
}
}
/* The split-K reduce: the w4a16 row's, the D map inverted. */
__global__ void r3d_w5a16_split_reduce(const float* __restrict__ Scr,
__hip_bfloat16* __restrict__ C,
int M, int N, int y_ld, int SK, int MTb, int ntiles)
{
const int total = ntiles * MTb * 256;
for (int idx = blockIdx.x * blockDim.x + threadIdx.x; idx < total;
idx += gridDim.x * blockDim.x) {
const int tile = idx / 256, off = idx % 256;
const int i = tile % MTb, col_g = tile / MTb;
float v = 0.f;
for (int s = 0; s < SK; s++)
v += Scr[(((size_t)col_g * SK + s) * MTb + i) * 256 + off];
const int l = off & 31, e = off >> 5;
const int m = i * 16 + 2 * e + (l >> 4), n = col_g * 16 + (l & 15);
if (m < M && n < N) ((uint16_t*)C)[(size_t)m * y_ld + n] = f32_to_bf16(v);
}
}
/* ==================================================================== the launcher
* y[M,N] = a[M,K] @ dequant(wq, hi)[N,K]^T:
*
* a [M][K] f16
* wq [N][K/2] u4 codes, the fragment order
* bsz the joined (scale, zero, hi) operand, rad.planes
* y [M][N] bf16, row-major
*
* `wv` waves per block (0 = 8), `sk` the K split (0 = 1), `mb` row tiles per block (0 = 1),
* `npw` column tiles a wave (0 = 1; 1 or 4), `nt` the weight load's lowering. Returns 0,
* -1 a null pointer, -2 a shape it does not serve, -4 the HIP launch failed. */
static float* s_scratch_pool = nullptr;
static size_t s_scratch_sz = 0;
extern "C" int r3d_gemm_nt_q_w5a16_m64(long a, long wq, long bsz, size_t off_scale,
size_t off_zero, size_t off_hi, long y, int M, int N,
int K, int a_ld, int y_ld,
int wv, int sk, int mb, int npw, int nt,
long stream)
{
if (!a || !wq || !bsz || !y) return -1;
if (M < 1 || M > kMaxM) return -2;
if (N < 16 || N % 16) return -2;
if (K < kGroup || K % kGroup) return -2;
if (wv <= 0) wv = 8;
if (sk <= 0) sk = 1;
if (mb <= 0) mb = 1;
if (npw <= 0) npw = 1;
if (wv > 32 || sk > 32) return -2;
if (mb < 1 || mb > 4) return -2;
if (npw != 1 && npw != 4) return -2;
if (K % (sk * kGroup)) return -2;
/* npw=4 with mb>1 is the shape the backend cannot lower at the 128-VGPR ceiling; the
* w4a16 row's probe and refusal apply. */
if (npw == 4 && mb > 1) return -2;
const int ntiles = N / 16, mtiles = (M + 15) / 16;
const int ncols = wv * npw;
const dim3 grid((ntiles + ncols - 1) / ncols, ((mtiles + mb - 1) / mb) * sk),
block(wv * kWave32);
float* scr = nullptr;
if (sk > 1) {
const size_t bytes = (size_t)ntiles * sk * mb * 256 * sizeof(float);
if (bytes > s_scratch_sz) {
if (s_scratch_pool) hipFree(s_scratch_pool);
if (hipMalloc(&s_scratch_pool, bytes) != hipSuccess) return -4;
s_scratch_sz = bytes;
}
scr = s_scratch_pool;
}
#define R3D_W5L(MT, NP, TT) \
R3D_KLAUNCH_S(R3D_KNAME((r3d_w5a16_m64_kernel<MT, NP, TT>)), grid, block, 0, \
(hipStream_t)stream, (const unsigned short*)a, (const unsigned char*)wq, \
(const unsigned char*)bsz, off_scale, off_zero, off_hi, (__hip_bfloat16*)y, \
scr, M, K, N, a_ld, y_ld, wv, sk, mb)
#define R3D_W5L_MB(NP, TT) \
do { switch (mb) { \
case 1: R3D_W5L(1, NP, TT); break; \
case 2: R3D_W5L(2, NP, TT); break; \
case 3: R3D_W5L(3, NP, TT); break; \
default: R3D_W5L(4, NP, TT); break; } } while (0)
if (npw == 1) { if (nt) R3D_W5L_MB(1, true); else R3D_W5L_MB(1, false); }
else { if (nt) R3D_W5L_MB(4, true); else R3D_W5L_MB(4, false); }
#undef R3D_W5L_MB
#undef R3D_W5L
if (hipGetLastError() != hipSuccess) return -4;
if (sk > 1) {
const int total = ntiles * mb * 256;
const int rblock = 256;
const int rgrid = (total + rblock - 1) / rblock;
R3D_KLAUNCH_S(R3D_KNAME((r3d_w5a16_split_reduce)), dim3(rgrid), rblock, 0,
(hipStream_t)stream, scr, (__hip_bfloat16*)y, M, N, y_ld, sk, mb, ntiles);
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
} // namespace
/* ==================================================================== the plugin ABI */
enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF };
extern "C" int r3d_rad_gemm_nt_q_w5a16_m64(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
if (!dt || std::strcmp(dt, "w5a16") != 0) return R3D_NO(RAD_E_DTYPE);
const RadTensor* A = r3d_opt(a, Q_A);
const RadTensor* AS = r3d_opt(a, Q_ASCALE);
const RadTensor* B = r3d_opt(a, Q_B);
const RadTensor* BS = r3d_opt(a, Q_BSCALE);
const RadTensor* Y = r3d_opt(a, Q_Y);
const RadTensor* AU = r3d_opt(a, Q_ASUM);
const RadTensor* BR = r3d_opt(a, Q_BREF);
if (!r3d_p(A) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL);
if (r3d_has(AS) || r3d_has(AU) || r3d_has(BR)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f16(A)) return R3D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_U4) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
if (N % 16) return R3D_NO(RAD_E_SHAPE);
if (K % kGroup) return R3D_NO(RAD_E_SHAPE);
const long long ynel = r3d_numel(Y);
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = ynel / N;
if (M < 1 || M > kMaxM) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
/* The joined form: the scale and zero planes, the hi plane, and their byte offsets. */
const RadPlanesEntry* es = nullptr, *ez = nullptr, *eh = nullptr;
const uint8_t* sc_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "scale", &es);
const uint8_t* z_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "zero", &ez);
const uint8_t* h_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "hi", &eh);
if (!sc_b || !z_b || !h_b || es->dtype != RAD_F16 || ez->dtype != RAD_U8 ||
eh->dtype != RAD_U32)
return R3D_NO(RAD_E_DTYPE);
if (es->rows < N || ez->rows < N || es->cols < K / kGroup || ez->cols < K / kGroup)
return R3D_NO(RAD_E_SHAPE);
if (eh->rows < N / 16) return R3D_NO(RAD_E_SHAPE);
const long long ap = r3d_row_pitch(A);
if (ap < K) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
if (yp < N || yrows < M) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 16) || !r3d_aligned(r3d_p(B), 8) ||
!r3d_aligned(h_b, 4))
return R3D_NO(RAD_E_ALIGN);
const int wv = (int)r3d_geti_or(a, "wv", 8);
const int sk = (int)r3d_geti_or(a, "sk", 1);
const int mb = (int)r3d_geti_or(a, "mb", 1);
const int npw = (int)r3d_geti_or(a, "npw", 1);
const int nt = (int)r3d_geti_or(a, "nt", 1);
const int e = r3d_gemm_nt_q_w5a16_m64(r3d_addr(A), r3d_addr(B), r3d_addr(BS),
(size_t)(sc_b - (const uint8_t*)r3d_p(BS)),
(size_t)(z_b - (const uint8_t*)r3d_p(BS)),
(size_t)(h_b - (const uint8_t*)r3d_p(BS)),
r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp,
wv, sk, mb, npw, nt, (long)(uintptr_t)s);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE : RAD_E_DEVICE);
}
/* ==================================================================== the layout hooks
*
* The w4a16 row's scoped exception with a third plane: the codes are read where they lie
* (the B operand, the container's order), and the scale, zero and hi planes join behind
* the b_scale operand. NOTHING HERE MOVES A BYTE.
*/
extern "C" int r3d_layout_gemm_nt_q_w5a16(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out)
{
if (n < 2 || operand != Q_BSCALE) return RAD_E_UNSUPPORTED;
const char* d = r3d_pgets(p, n_p, "dtype");
if (!d || std::strcmp(d, "w5a16") != 0) return RAD_E_DTYPE;
const long long group = r3d_pgeti_or(p, n_p, "group", kGroup);
if (group <= 0) return RAD_E_DTYPE;
if (!enc || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
if (enc->n_planes < 3) return RAD_E_DTYPE;
if (n != 3) return RAD_E_DTYPE;
const char* want[3] = { "scale", "zero", "hi" };
for (int i = 0; i < 3; ++i) {
if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_DTYPE;
if (std::strncmp(enc->plane[sel[i]].role, want[i], RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
}
/* The codes plane is the one this operand does not take: U4, block {1,1}. */
int codes = -1;
for (int i = 0; i < enc->n_planes; ++i)
if (std::strncmp(enc->plane[i].role, "codes", RAD_ENC_STR) == 0) { codes = i; break; }
if (codes < 0 || enc->plane[codes].dtype != RAD_U4 ||
enc->plane[codes].block[0] != 1 || enc->plane[codes].block[1] != 1)
return RAD_E_DTYPE;
for (int i = 0; i < 3; ++i) {
const RadEncPlane* q = &enc->plane[sel[i]];
if (q->kind != RAD_PLANE_TILED) return RAD_E_DTYPE;
if (i < 2 && (q->block[0] != 1 || q->block[1] != group)) return RAD_E_DTYPE;
if (i == 0 && q->dtype != RAD_F16) return RAD_E_DTYPE;
if (i == 1 && q->dtype != RAD_U8) return RAD_E_DTYPE;
if (i == 2 && q->dtype != RAD_U32) return RAD_E_DTYPE;
}
/* The hi plane's extent: one word a (tile, 64-wide k block, lane). */
const long long N = r3d_pgeti_or(p, n_p, "N", 0), K = r3d_pgeti_or(p, n_p, "K", 0);
if (N > 0 && K > 0) {
const RadTensor* h = &pl[sel[2]];
if (h->rank < 2 || h->shape[0] < N / 16 || h->shape[1] < K / 2)
return RAD_E_SHAPE;
}
return rad_planes_layout(enc, sel, pl, n, out);
}
/* The writer for the joined operand: the planes copied, the header and entries filled. */
extern "C" int r3d_relayout_gemm_nt_q_w5a16(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
int64_t dst_bytes)
{
(void)p; (void)n_p;
if (operand != Q_BSCALE) return RAD_E_UNSUPPORTED;
return rad_planes_relayout(enc, sel, pl, n, dst, dst_bytes);
}
+284
View File
@@ -0,0 +1,284 @@
/* r3d_gemm_w8a8_nt_m64.hip -- the wave-matrix arm of the w8a8 grid at the M = 17..127 band.
*
* y[M,N] = a[M,K] @ b[N,K]^T, int8 a against signed int8 codes, the scale group 128.
*
* The m16 arm (r3d_gemm_inta8_wmma) owns one 16-row tile a wave; above M = 16 this arm takes
* MT = 2 16-row tiles a wave and walks them with MT accumulators. The B-fragment (the weight
* column) is loaded once per 16-k step and reused over the MT row tiles, so the weight stream
* is read once per 16-column tile no matter how many row tiles the wave carries -- the
* activation, not the weight, is the traffic that grows with MT.
*
* ---- the group law --------------------------------------------------------------------------
*
* The m16 arm's exactness: a group's 128 products are |a * code| <= 127 * 127, their sum
* 2,064,512 an exact integer far inside i32, so the eight wmma steps of a group chain an i32
* sub-sum with no rounding, and the group term is the reference's
*
* acc += (sub * a_scale[m]) * b_scale[n, g]
*
* in f32, in ascending group order -- the same order the dot2 arm's shared-memory walk forms.
*
* ---- the B pointer --------------------------------------------------------------------------
*
* The weight row base `w = B + n_real * b_rb` carries NO group offset; the group's k-base
* enters the fragment read exactly once, as `w + kt + k` with kt = g * 128. Adding the group
* offset to the row base AND the step read doubles it and reads a foreign weight slice -- the
* per-n blow-up the prior draft hit. The A is staged per group into LDS, so its fragment read
* is the group-local step offset; both operands land on the same logical k.
*
* ---- the register budget --------------------------------------------------------------------
*
* MT = 2: two f32 accumulators, two i32 sub-sums, sixteen A and sixteen B fragment VGPRs, the
* scales and the pointers, about 66 a lane. Eight waves a SIMD ask 528 of the 1024 the gfx11
* SIMD keeps, so the eight-wave block stands. (A four-tile draft reached ~130 a lane, 1040 for
* eight waves, and the overflow miscompiled the sub-sum chain.)
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
#include <algorithm>
namespace {
constexpr int kWaves = 8;
constexpr int kBlockThreads = kWaves * kWave;
constexpr int kGroup = 128; /* the scale group: one k tile, eight wmma steps */
constexpr int kPitch = 33; /* dwords a staged a row: 33 mod 32 = 1, bank-free */
constexpr int MT = 2; /* 16-row tiles a wave: 32 rows a block */
/* Signed i8 in, signed i32 out: the builtin's sign selectors take the operands' signedness as
* compile-time constants, both signed for this grid. */
/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse. */
__device__ __forceinline__ int64_t dword_pos(int64_t d)
{
return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1));
}
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldw(const uint8_t* p)
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
/* y[M,N] = a[M,K] @ b[N,K]^T, MT 16-row tiles a wave, one 16-column tile a wave, one scale
* group a k tile. The dot2 arm's contract: K a multiple of the group, the group term the
* reference's, in ascending group order. */
template <bool NT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_w8a8_wmma_m64_kernel(
const int8_t* __restrict__ a, const float* __restrict__ sa,
const uint8_t* __restrict__ B, int b_rb, const uint16_t* __restrict__ sb,
int sb_rb, uint16_t* __restrict__ Y,
int M, int N, int K, int a_ld, int y_ld)
{
__shared__ __align__(16) uint32_t s_a[MT * 16 * kPitch];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t r = lane & 15; // the replicated row/column index
const uint32_t n0 = (uint32_t)blockIdx.x * kWaves * 16 + wave * 16 + r;
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
const int mbase = (int)blockIdx.y * MT * 16; // this block's first row
/* The lane's eight output rows per tile, and their activation scales, hoisted: a_scale is a
* row property, constant across the group walk. */
float as[MT][8];
#pragma unroll
for (int i = 0; i < MT; ++i)
#pragma unroll
for (int g2 = 0; g2 < 8; ++g2) {
const int m = mbase + i * 16 + g2 * 2 + (int)(lane >> 4);
as[i][g2] = sa[m < M ? m : M - 1];
}
const uint8_t* w = B + (size_t)n_real * b_rb; // the row base: NO group offset
v8float acc[MT];
#pragma unroll
for (int i = 0; i < MT; ++i) acc[i] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
for (int g = 0; g < K / kGroup; ++g) {
const int kt = g * kGroup;
/* Stage MT*16 rows x 128 i8, the step order unpermuting on the way in. A row past M
* re-reads the last real row, whose products the store drops. */
for (int i = (int)tid; i < MT * 16 * (kGroup / 4); i += kBlockThreads) {
const int row = i / (kGroup / 4), d = i % (kGroup / 4);
const int rr = mbase + row;
const uint32_t src =
*(const uint32_t*)(a + (size_t)(rr < M ? rr : M - 1) * a_ld + kt + dword_pos(d));
s_a[(size_t)row * kPitch + d] = src;
}
group_barrier();
#pragma unroll
for (int i = 0; i < MT; ++i) {
const uint32_t* ap = s_a + (size_t)(i * 16 + r) * kPitch;
v8int sub = v8int{ 0, 0, 0, 0, 0, 0, 0, 0 };
for (int k = 0; k < kGroup; k += 16) {
const r3d_u32x4 aq = *(const r3d_u32x4*)(ap + k / 4);
// The group's k-base enters once (kt); the row base carries none.
const r3d_u32x4 bq = ldw<NT>(w + kt + k);
sub = wmma_i8(v4int{ (int)aq.x, (int)aq.y, (int)aq.z, (int)aq.w },
v4int{ (int)bq.x, (int)bq.y, (int)bq.z, (int)bq.w }, sub);
}
/* The group term, the reference's parentheses. The b_scale load, its drain, its
* convert, and the eight fmacs run as one asm block: the load goes straight from
* global, the drain is a vmcnt this asm owns, and the scale's register is written
* only by this block's global_load, so no fragment load can clobber it mid-group.
* v20 is named in the clobber because this LLVM aliases a constrained asm output
* with a dead input register; the clobber keeps every t/acc/sub register out of
* v20 across the block. The hardware f16->f32 is exact for normals. */
float t[8];
#pragma unroll
for (int g2 = 0; g2 < 8; ++g2)
t[g2] = (float)sub[g2] * as[i][g2];
{
const uint64_t ga = (uint64_t)(sb + (size_t)n_real * sb_rb + g);
asm volatile(
"global_load_u16 v20, %[ga], off\n\t"
"s_waitcnt vmcnt(0)\n\t"
"v_cvt_f32_f16_e32 v20, v20.l\n\t"
"v_fmac_f32_e32 %[a0], %[t0], v20\n\t"
"v_fmac_f32_e32 %[a1], %[t1], v20\n\t"
"v_fmac_f32_e32 %[a2], %[t2], v20\n\t"
"v_fmac_f32_e32 %[a3], %[t3], v20\n\t"
"v_fmac_f32_e32 %[a4], %[t4], v20\n\t"
"v_fmac_f32_e32 %[a5], %[t5], v20\n\t"
"v_fmac_f32_e32 %[a6], %[t6], v20\n\t"
"v_fmac_f32_e32 %[a7], %[t7], v20"
: [a0] "+v"(acc[i][0]), [a1] "+v"(acc[i][1]), [a2] "+v"(acc[i][2]),
[a3] "+v"(acc[i][3]), [a4] "+v"(acc[i][4]), [a5] "+v"(acc[i][5]),
[a6] "+v"(acc[i][6]), [a7] "+v"(acc[i][7])
: [ga] "v"(ga),
[t0] "v"(t[0]), [t1] "v"(t[1]), [t2] "v"(t[2]), [t3] "v"(t[3]),
[t4] "v"(t[4]), [t5] "v"(t[5]), [t6] "v"(t[6]), [t7] "v"(t[7])
: "v20");
}
}
group_barrier(); // the next tile's stage must not race this one's reads
}
const bool keep = (n0 < (uint32_t)N);
if (!keep) return;
#pragma unroll
for (int i = 0; i < MT; ++i)
#pragma unroll
for (int g2 = 0; g2 < 8; ++g2) {
const int m = mbase + i * 16 + g2 * 2 + (int)(lane >> 4);
if (m < M) Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc[i][g2]);
}
}
} // namespace
/* y[M,N] = a[M,K] @ b[N,K]^T over the w8a8 grid, the wave-matrix arm at the M = 17..127 band.
*
* The dot2 arm's contract: K a multiple of the group, the group term the reference's. `nt`
* picks the weight load's lowering. Returns 0, -1 a null pointer, -2 a shape it does not
* serve, -3 a pitch it cannot read, -4 the HIP launch failed, -5 an alignment it cannot
* read. */
extern "C" int r3d_gemm_nt_q_w8a8_m64_wmma(long a, long a_scale, long b, long b_scale, long y,
int M, int N, int K, int a_ld, int y_ld,
long long b_rb, long long sb_rb, int nt, long stream)
{
if (!a || !a_scale || !b || !b_scale || !y) return -1;
if (M < 17 || N < 1 || K < 1) return -2;
if (M > 127) return -2;
if (K % kGroup) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (a_ld % 4) return -3;
if (y_ld < N) return -3;
if (!b_rb) b_rb = K;
if (b_rb < K) return -3;
if (b_rb & 15) return -5;
if (!sb_rb) sb_rb = K / kGroup;
if (sb_rb < K / kGroup) return -3;
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
const int mrowblk = (M + MT * 16 - 1) / (MT * 16);
const dim3 grid((N + kWaves * 16 - 1) / (kWaves * 16), (unsigned)mrowblk), block(kBlockThreads);
if (nt)
R3D_KLAUNCH(gemm_w8a8_wmma_m64_kernel<true>, grid, block, (hipStream_t)stream,
(const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb,
(const uint16_t*)b_scale, (int)sb_rb, (uint16_t*)y, M, N, K, a_ld, y_ld);
else
R3D_KLAUNCH(gemm_w8a8_wmma_m64_kernel<false>, grid, block, (hipStream_t)stream,
(const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb,
(const uint16_t*)b_scale, (int)sb_rb, (uint16_t*)y, M, N, K, a_ld, y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* ==================================================================================================
* The RadArgs shim. Schema positions: a 0, a_scale 1, b 2, b_scale 3, y 4, a_sum 5, b_ref 6. The
* m64 band is 17 <= M <= 127; M <= 16 is the m16 arm's, so the two rows never compete.
* ================================================================================================== */
extern "C" int r3d_rad_gemm_nt_q_w8a8_m64(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
if (dt && std::strcmp(dt, "w8a8") != 0) return R3D_NO(RAD_E_DTYPE);
const RadTensor* A = r3d_opt(a, 0);
const RadTensor* AS = r3d_opt(a, 1);
const RadTensor* B = r3d_opt(a, 2);
const RadTensor* BS = r3d_opt(a, 3);
const RadTensor* Y = r3d_opt(a, 4);
const RadTensor* ASUM = r3d_opt(a, 5);
const RadTensor* BREF = r3d_opt(a, 6);
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
return R3D_NO(RAD_E_INVAL);
if (r3d_has(ASUM) || r3d_has(BREF)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_i8(A)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE);
if (BS->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
if (K % kGroup) return R3D_NO(RAD_E_SHAPE);
const long long ynel = r3d_numel(Y);
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = ynel / N;
if (M < 17 || M > 127) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(AS) < M) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(BS) < N * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
const long long ap = r3d_row_pitch(A);
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
if (yp < N) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
const int rc = r3d_gemm_nt_q_w8a8_m64_wmma(r3d_addr(A), r3d_addr(AS), r3d_addr(B),
r3d_addr(BS), r3d_addr(Y), (int)M, (int)N,
(int)K, (int)ap, (int)yp,
(long long)r3d_row_pitch(B),
(long long)r3d_row_pitch(BS), c.nt, (long)s);
if (rc == -1) return R3D_NO(RAD_E_INVAL);
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
return RAD_OK;
}
+119
View File
@@ -0,0 +1,119 @@
/* r3d_had_quant_act_fp8.hip -- had_quant_act_fp8: a 128-wide block Hadamard, then per-group E4M3.
*
* The rotated form of quant_act_fp8: the 128-wide Hadamard shrinks the group maximum, so e4m3's
* four exponent bits carry the outliers better after the rotation. The transform is the wave-local
* FWHT of r3d_fwht.h (unnormalised; the scale carries the 1/sqrt(128) so the dequantised value is
* the orthonormal rotation). Normalisation is folded into the scale: S = absmax * (1/sqrt(128)) /
* 448, codes of (v * (128/absmax)) clamped to +-448.
*
* A separate op, not a parameter: it writes different numbers than quant_act_fp8, so a swapped
* graph would run as a different model. The codes are row-major (the fp8 GEMM reads stored order).
*
* gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles here
* (a non-first wave drops out -- the same bug as the GDN recurrent kernel, the MoE router, and the
* int8 Hadamard quantisers). This serves the single-group form, n == group == 128: one wave runs
* the whole FWHT with no group loop. A wider n is declined.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_fwht.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr float kTopE4M3 = 448.0f;
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
__device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) {
const uint32_t lo = e4m3x2_pack(clamp_top(v[0] * inv, kTopE4M3), clamp_top(v[1] * inv, kTopE4M3));
const uint32_t hi = e4m3x2_pack(clamp_top(v[2] * inv, kTopE4M3), clamp_top(v[3] * inv, kTopE4M3));
return lo | (hi << 16);
}
__device__ __forceinline__ float wave_max_f(float v) {
v = fmaxf(v, r3d_xor_lane<16>(v));
v = fmaxf(v, r3d_xor_lane<8>(v));
v = fmaxf(v, r3d_xor_lane<4>(v));
v = fmaxf(v, r3d_xor_lane<2>(v));
v = fmaxf(v, r3d_xor_lane<1>(v));
return v;
}
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void had_quant_act_fp8_kernel(
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n) {
constexpr int HAD = 128, VPL = HAD / 32;
__shared__ float lds[128];
__shared__ float red[kWaves];
const uint32_t row = blockIdx.x;
const uint16_t* a = x + (size_t)row * n;
uint8_t* qr = q + (size_t)row * n;
const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
float m = 0.0f;
if (wave == 0) { // one wave does the whole single-group FWHT (no group loop, gfx1102)
const int base = lane * VPL;
float v[VPL];
#pragma unroll
for (int j = 0; j < VPL; ++j) v[j] = (base + j < (int)n) ? ld_bf(a, base + j) : 0.0f;
r3d_fwht_wave<HAD>(v, lane);
#pragma unroll
for (int j = 0; j < VPL; ++j) { lds[base + j] = v[j]; m = fmaxf(m, fabsf(v[j])); }
}
m = wave_max_f(m);
if (lane == 0) red[wave] = m;
__syncthreads();
m = red[0];
#pragma unroll
for (uint32_t w = 1; w < kWaves; ++w) m = fmaxf(m, red[w]);
const float scale = m > 0.0f ? m * (1.0f / kTopE4M3) : 1.0f;
const float inv = 1.0f / scale;
if (threadIdx.x == 0) s[row] = scale * (1.0f / sqrtf((float)HAD));
for (uint32_t c = lane * 4; c < n; c += kWave * 4) {
if (wave == 0) {
float v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) v[j] = lds[c + (uint32_t)j];
*(uint32_t*)(qr + c) = e4m3_codes4(v, inv);
}
}
}
} // namespace
extern "C" {
int r3d_rad_had_quant_act_fp8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2);
if (!r3d_p(x) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || q->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(x)) return R3D_NO(RAD_E_STRIDE);
long long M = 0, K = 0;
if (r3d_rows_of(x, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
if (K <= 0 || K % 4) return R3D_NO(RAD_E_SHAPE);
const long long grp = r3d_geti_or(a, "group", 128);
// gfx1102: single-group form (see the file header).
if (grp != 128 || K != 128) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(q) < M * K || r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE);
dim3 grid((unsigned)M), blk(kThreads);
R3D_KLAUNCH(had_quant_act_fp8_kernel, grid, blk, (hipStream_t)s, (const uint16_t*)r3d_p(x),
(uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)K);
return (int)hipGetLastError();
}
} // extern "C"
+144
View File
@@ -0,0 +1,144 @@
/* r3d_had_quant_act_i8.hip -- had_quant_act_i8: a block Hadamard along K, then per-row symmetric
* int8 quantisation, written in the int8 WMMA step order.
*
* The rotation: plain per-token int8 activations are unusable on these models (KL against bf16 an
* order of magnitude worse than per-token e4m3); a block Hadamard first makes int8 several times
* better than e4m3. A rotation fixes range, not precision: int8 spends its grid covering a few
* outlier channels, and mixing each value with HAD-1 others removes them. It must happen before
* the absmax, since the benefit is a smaller row maximum, so it belongs in the quantiser.
*
* The transform is the wave-local FWHT of r3d_fwht.h: one wave owns a HAD-wide block, VPL = HAD/32
* contiguous values per lane. Normalisation is folded into the scale: the stages compute the
* unnormalised transform (sqrt(HAD) times the orthonormal one), and S[row] = absmax * (1/sqrt(HAD))
* / 127 undoes it while inv = 127/absmax gives the normalised codes.
*
* gfx1102 note: the FWHT's cross-lane stages are DPP exchanges, and a DPP exchange inside a loop
* body miscompiles on gfx1102 (a non-first wave drops out of the loop; the same bug as the GDN
* recurrent kernel and the MoE router). This kernel therefore serves the single-block form,
* K == group: one wave runs the whole FWHT with no block loop, the rest quantise from LDS. A
* wider K (several rotation blocks) would put the transform in a loop and is declined.
*
* The codes are written in the int8 WMMA step order (i8_step_pos, r3d_quant_fp8.hip), the same
* plane the w4a8/w8a8/w2a8 GEMMs read, so n is a multiple of 16.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_fwht.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr float kTopI8 = 127.0f;
constexpr float kI8Floor = 1e-8f;
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8));
const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8));
const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8));
const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8));
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}
__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) {
return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1);
}
__device__ __forceinline__ float block_max(float v, float* lds) {
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
v = wave_max(v);
if (lane == 0) lds[wave] = v;
__syncthreads();
float t = lds[0];
#pragma unroll
for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]);
return t;
}
template <int HAD>
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void had_quant_act_i8_kernel(
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n,
float rnorm) {
constexpr int VPL = HAD / 32;
__shared__ float lds[1024]; // the transformed row (n <= 1024)
__shared__ float red[kWaves];
const uint32_t row = blockIdx.x;
const uint16_t* a = x + (size_t)row * n;
uint8_t* qr = q + (size_t)row * n;
const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
// One wave does the whole single-block FWHT: no block loop, so its DPP cross-lane stages stay
// out of a loop body (a DPP exchange in a loop miscompiles on gfx1102 -- see the file header).
float m = 0.0f;
if (wave == 0) {
const int base = lane * VPL;
float v[VPL];
#pragma unroll
for (int j = 0; j < VPL; ++j) v[j] = ld_bf(a, base + j);
r3d_fwht_wave<HAD>(v, lane);
#pragma unroll
for (int j = 0; j < VPL; ++j) { lds[base + j] = v[j]; m = fmaxf(m, fabsf(v[j])); }
}
m = block_max(m, red);
m = fmaxf(m, kI8Floor);
const float inv = kTopI8 / m;
if (threadIdx.x == 0) s[row] = m * rnorm / kTopI8;
// Write the codes in the WMMA step order, reading the transformed row from LDS.
for (uint32_t c = threadIdx.x * 4; c < n; c += kThreads * 4) {
float v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) v[j] = (c + (uint32_t)j < n) ? lds[c + (uint32_t)j] : 0.0f;
*(uint32_t*)(qr + i8_step_pos(c)) = i8_codes4(v, inv);
}
}
} // namespace
extern "C" {
int r3d_rad_had_quant_act_i8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2);
if (!r3d_p(x) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (!r3d_contig(x) || !r3d_contig(q) || !r3d_contig(sc)) return R3D_NO(RAD_E_STRIDE);
long long M = 0, K = 0;
if (r3d_rows_of(x, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
if (K <= 0 || K % 16) return R3D_NO(RAD_E_SHAPE);
const long long had = r3d_geti_or(a, "group", 128);
if (had != 128 && had != 256 && had != 512) return R3D_NO(RAD_E_SHAPE);
// gfx1102: the FWHT is DPP and must not run in a block loop (see the file header), so this
// serves the single-block form, K == group. A wider K (several rotation blocks) is declined.
if (K != had) return R3D_NO(RAD_E_SHAPE);
const float rnorm = 1.0f / sqrtf((float)had);
dim3 grid((unsigned)M), blk(kThreads);
const uint32_t n = (uint32_t)K;
switch (had) {
case 256: R3D_KLAUNCH(had_quant_act_i8_kernel<256>, grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(x), (uint8_t*)r3d_wp(q),
(float*)r3d_wp(sc), n, rnorm); break;
case 512: R3D_KLAUNCH(had_quant_act_i8_kernel<512>, grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(x), (uint8_t*)r3d_wp(q),
(float*)r3d_wp(sc), n, rnorm); break;
default: R3D_KLAUNCH(had_quant_act_i8_kernel<128>, grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(x), (uint8_t*)r3d_wp(q),
(float*)r3d_wp(sc), n, rnorm); break;
}
return (int)hipGetLastError();
}
} // extern "C"
+117
View File
@@ -0,0 +1,117 @@
/* r3d_had_quant_act_i8g.hip -- had_quant_act_i8g: a 128-wide block Hadamard, then per-group int8.
*
* The rotated int8 form for the int8 trunk GEMMs (i8a8): the 128-wide Hadamard shrinks the group
* maximum, and the codes are row-major (the i8a8 dot2 GEMM reads stored order), with one scale per
* (row, group). This is quant_act_i8g with the rotation; the unrotated form is a separate op.
*
* A separate op, not a parameter: it writes different numbers and a different code layout than
* quant_act_i8 (step-ordered) or had_quant_act_i8 (step-ordered), so a swapped graph would run as
* a different model. The normalisation (1/sqrt(128)) is folded into the scale.
*
* gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles here
* (a non-first wave drops out). This serves the single-group form, n == group == 128: one wave runs
* the whole FWHT with no group loop. A wider n is declined.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_fwht.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr float kTopI8 = 127.0f;
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8));
const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8));
const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8));
const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8));
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}
__device__ __forceinline__ float wave_max_f(float v) {
v = fmaxf(v, r3d_xor_lane<16>(v));
v = fmaxf(v, r3d_xor_lane<8>(v));
v = fmaxf(v, r3d_xor_lane<4>(v));
v = fmaxf(v, r3d_xor_lane<2>(v));
v = fmaxf(v, r3d_xor_lane<1>(v));
return v;
}
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void had_quant_act_i8g_kernel(
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n) {
constexpr int HAD = 128, VPL = HAD / 32;
__shared__ float lds[128];
__shared__ float red[kWaves];
const uint32_t row = blockIdx.x;
const uint16_t* a = x + (size_t)row * n;
uint8_t* qr = q + (size_t)row * n;
const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
float m = 0.0f;
if (wave == 0) { // one wave does the whole single-group FWHT (no group loop, gfx1102)
const int base = lane * VPL;
float v[VPL];
#pragma unroll
for (int j = 0; j < VPL; ++j) v[j] = (base + j < (int)n) ? ld_bf(a, base + j) : 0.0f;
r3d_fwht_wave<HAD>(v, lane);
#pragma unroll
for (int j = 0; j < VPL; ++j) { lds[base + j] = v[j]; m = fmaxf(m, fabsf(v[j])); }
}
m = wave_max_f(m);
if (lane == 0) red[wave] = m;
__syncthreads();
m = red[0];
#pragma unroll
for (uint32_t w = 1; w < kWaves; ++w) m = fmaxf(m, red[w]);
m = m > 0.0f ? m : 1e-8f;
const float inv = kTopI8 / m;
if (threadIdx.x == 0) s[row] = m * (1.0f / sqrtf((float)HAD)) / kTopI8;
if (wave == 0)
for (uint32_t c = lane * 4; c < n; c += kWave * 4) {
float v[4];
#pragma unroll
for (int j = 0; j < 4; ++j) v[j] = lds[c + (uint32_t)j];
*(uint32_t*)(qr + c) = i8_codes4(v, inv); // row-major (the i8a8 GEMM's layout)
}
}
} // namespace
extern "C" {
int r3d_rad_had_quant_act_i8g(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2);
if (!r3d_p(x) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(x)) return R3D_NO(RAD_E_STRIDE);
long long M = 0, K = 0;
if (r3d_rows_of(x, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
if (K <= 0 || K % 4) return R3D_NO(RAD_E_SHAPE);
const long long grp = r3d_geti_or(a, "group", 128);
if (grp != 128 || K != 128) return R3D_NO(RAD_E_SHAPE); // single-group form (gfx1102)
if (r3d_numel(q) < M * K || r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE);
dim3 grid((unsigned)M), blk(kThreads);
R3D_KLAUNCH(had_quant_act_i8g_kernel, grid, blk, (hipStream_t)s, (const uint16_t*)r3d_p(x),
(uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)K);
return (int)hipGetLastError();
}
} // extern "C"
+52
View File
@@ -0,0 +1,52 @@
/* r3d_kv_len_trim.hip -- kv_len_trim: a batch's per-sequence context lengths less `trim`.
*
* The prefill overlap runs attention per slice of a one-sequence step: slice A's rows are the step's
* first rows, so its attention must see the context ending at its own last row, not the step's (rows
* past it are not yet in the cache). `trim` is the rows after the slice, a runtime count carried by
* the extent of operand `tail`, whose values are never read.
*
* in [n] i32, tail (extent = trim) -> out [n] i32, out[i] = max(in[i] - trim, 0)
*
* n <= 64 (a batch), one workgroup.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_launch.h"
namespace {
__global__ __launch_bounds__(64) void kv_len_trim_kernel(const int32_t* __restrict__ in,
int32_t* __restrict__ out, int n,
int trim) {
const int i = (int)threadIdx.x;
if (i < n) {
const int v = in[i] - trim;
out[i] = v > 0 ? v : 0;
}
}
} // namespace
extern "C" {
int r3d_rad_kv_len_trim(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* in = r3d_opt(a, 0), *tail = r3d_opt(a, 1), *out = r3d_opt(a, 2);
if (!r3d_p(in) || !r3d_wp(out)) return R3D_NO(RAD_E_INVAL);
if (in->dtype != RAD_I32 || out->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE);
const long long n = r3d_numel(in);
if (n < 1 || n > 64 || r3d_numel(out) < n) return R3D_NO(RAD_E_SHAPE);
const long long trim = tail ? r3d_numel(tail) : 0;
if (trim < 0 || trim > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
R3D_KLAUNCH(kv_len_trim_kernel, dim3(1), dim3(64), (hipStream_t)s, (const int32_t*)r3d_p(in),
(int32_t*)r3d_wp(out), (int)n, (int)trim);
return (int)hipGetLastError();
}
} // extern "C"
+6
View File
@@ -15,6 +15,12 @@
#ifndef R3D_KLAUNCH
#define R3D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<<grid, block, 0, stream>>>(__VA_ARGS__)
#endif
/* The same launch with a dynamic-LDS byte count, for the rows whose stage is sized by the launch
* rather than a template constant. */
#ifndef R3D_KLAUNCH_S
#define R3D_KLAUNCH_S(kernel, grid, block, smem, stream, ...) \
kernel<<<grid, block, smem, stream>>>(__VA_ARGS__)
#endif
#ifndef R3D_DYN_LDS
#define R3D_DYN_LDS(type, name) extern __shared__ type name[]
#endif
+205
View File
@@ -0,0 +1,205 @@
/* r3d_moe_gather.hip -- moe_gather / moe_gather_inv: fold the expert outputs back to the token.
*
* y[t, c] = sum_j expert_w[t, j] * y_expert[slot(t, j), c]
*
* summed in ascending slot order (reproducibility: the expert-sorted order would differ in the last
* bits). One block per token; the slot table (slot(t, j) and the weight) is hoisted to LDS so the
* per-column `ye` loads pipeline.
*
* Two arms:
* - moe_gather: `slot` is the inverse of `sorted_tok`; the block scans `sorted` for its token's
* slots (the self-scan form, no prepass).
* - moe_gather_inv: `slot` is the `inverse` table moe_scatter_inv wrote (read straight).
*
* An optional shared arm adds `shared[t, c] * act(gate[t])` (two narrows, matching the unfused
* scale_rows pair). `act` is "sigmoid" (the only form we take; "none" is refused, absent = the
* identity).
*
* The wide-prefill form (a wave per token, 8 cols/lane) is not implemented; this is the decode and
* short-pass form (one block per token), which covers every height the engine routes here.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include <cstdlib>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
namespace {
constexpr uint32_t kGatherThr = 256;
constexpr uint32_t kGatherSlots = 64; // top_k <= 64 for the LDS-cached slot table
template <bool F32W>
__device__ __forceinline__ float gather_weight(const void* ew, size_t i) {
if constexpr (F32W) return ((const float*)ew)[i];
else return bf16_to_f32(((const uint16_t*)ew)[i]);
}
/* One enum arg (not two bools) so the launch macro sees a single, comma-free template argument. */
enum class Gk { bf16_sorted, bf16_inv, f32_sorted, f32_inv };
template <Gk MODE>
__global__ __launch_bounds__(kGatherThr) void gather_kernel(
const uint16_t* __restrict__ ye, const void* __restrict__ ew,
const int32_t* __restrict__ inv, uint16_t* __restrict__ y,
uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld,
const int32_t* __restrict__ sorted, uint32_t T,
const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg,
uint32_t sh_ld, uint32_t sg_ld, int sig) {
constexpr bool F32W = (MODE == Gk::f32_sorted || MODE == Gk::f32_inv);
constexpr bool GIVEN = (MODE == Gk::bf16_inv || MODE == Gk::f32_inv);
__shared__ int32_t s_i[kGatherSlots];
__shared__ float s_w[kGatherSlots];
const uint32_t t = blockIdx.x;
if (t >= M) return;
const bool cached = top_k <= kGatherSlots;
float gate = 0.0f;
if (sh) {
const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]);
gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
}
if (!GIVEN) {
/* The self-scan form: scan `sorted` for this token's slots. An unclaimed slot reads -1, so
* the fill and the scan are separated by a barrier. */
for (uint32_t j = threadIdx.x; j < top_k; j += kGatherThr) s_i[j] = -1;
__syncthreads();
const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k;
for (uint32_t i = threadIdx.x; i < T; i += kGatherThr) {
const int32_t f = sorted[i];
if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i;
}
for (uint32_t j = threadIdx.x; j < top_k; j += kGatherThr)
s_w[j] = gather_weight<F32W>(ew, (size_t)t * ew_ld + j);
__syncthreads();
} else if (cached) {
for (uint32_t j = threadIdx.x; j < top_k; j += kGatherThr) {
s_i[j] = inv[t * top_k + j];
s_w[j] = gather_weight<F32W>(ew, (size_t)t * ew_ld + j);
}
__syncthreads();
}
for (uint32_t c = blockIdx.y * kGatherThr + threadIdx.x; c < n; c += kGatherThr * gridDim.y) {
float acc = 0.0f;
for (uint32_t j = 0; j < top_k; ++j) {
const int32_t i = cached ? s_i[j] : inv[t * top_k + j];
if (i < 0) continue;
const float wj = cached ? s_w[j] : gather_weight<F32W>(ew, (size_t)t * ew_ld + j);
acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]);
}
const uint16_t g = f32_to_bf16(acc);
if (!sh) { y[(size_t)t * y_ld + c] = g; continue; }
const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate);
y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g));
}
}
} // namespace
extern "C" {
int r3d_rad_moe_gather(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* ye = r3d_opt(a, 0), *ew = r3d_opt(a, 1), *sorted = r3d_opt(a, 2),
*y = r3d_opt(a, 5);
if (!r3d_p(ye) || !r3d_p(ew) || !r3d_p(sorted) || !r3d_wp(y)) return R3D_NO(RAD_E_INVAL);
if (ye->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
if (ew->dtype != RAD_BF16 && ew->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE);
if (sorted->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE);
const long long M = r3d_geti_or(a, "M", 0), n = r3d_geti_or(a, "n", 0),
top_k = r3d_geti_or(a, "top_k", 0);
if (M <= 0 || n <= 0 || top_k <= 0) return R3D_NO(RAD_E_SHAPE);
if (top_k > kGatherSlots) return R3D_NO(RAD_E_SHAPE); // the LDS-cached form only
const uint32_t ye_ld = (uint32_t)(ye->rank >= 2 ? ye->shape[1] : ye->stride[0]);
const uint32_t ew_ld = (uint32_t)(ew->rank >= 2 ? ew->shape[1] : ew->stride[0]);
const uint32_t y_ld = (uint32_t)(y->rank >= 2 ? y->shape[1] : y->stride[0]);
const uint32_t T = (uint32_t)r3d_numel(sorted);
if (T < M * top_k) return R3D_NO(RAD_E_SHAPE);
// The optional shared arm (operands 3 and 4, present together).
const RadTensor* sh = r3d_opt(a, 3), *sg = r3d_opt(a, 4);
const uint16_t* shp = sh ? (const uint16_t*)r3d_p(sh) : nullptr;
const uint16_t* sgp = sg ? (const uint16_t*)r3d_p(sg) : nullptr;
if (sh && !sg) return R3D_NO(RAD_E_INVAL);
const uint32_t sh_ld = sh ? (uint32_t)(sh->rank >= 2 ? sh->shape[1] : sh->stride[0]) : 0;
const uint32_t sg_ld = sg ? (uint32_t)(sg->rank >= 1 ? sg->shape[0] : sg->stride[0]) : 1;
int sig = 0;
if (const char* act = r3d_gets(a, "act")) {
if (std::string(act) == "sigmoid") sig = 1;
else if (std::string(act) == "none") return R3D_NO(RAD_E_INVAL);
}
const bool f32w = (ew->dtype == RAD_F32);
dim3 grid((unsigned)M, (unsigned)((n + kGatherThr - 1) / kGatherThr)), blk(kGatherThr);
if (f32w)
R3D_KLAUNCH(gather_kernel<Gk::f32_sorted>, grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(ye), r3d_p(ew), (const int32_t*)r3d_p(sorted),
(uint16_t*)r3d_wp(y), (uint32_t)M, (uint32_t)n, (uint32_t)top_k, ye_ld, ew_ld,
y_ld, (const int32_t*)r3d_p(sorted), T, shp, sgp, sh_ld, sg_ld, sig);
else
R3D_KLAUNCH(gather_kernel<Gk::bf16_sorted>, grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(ye), r3d_p(ew), (const int32_t*)r3d_p(sorted),
(uint16_t*)r3d_wp(y), (uint32_t)M, (uint32_t)n, (uint32_t)top_k, ye_ld, ew_ld,
y_ld, (const int32_t*)r3d_p(sorted), T, shp, sgp, sh_ld, sg_ld, sig);
return (int)hipGetLastError();
}
int r3d_rad_moe_gather_inv(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* ye = r3d_opt(a, 0), *ew = r3d_opt(a, 1), *inv = r3d_opt(a, 2),
*y = r3d_opt(a, 5);
if (!r3d_p(ye) || !r3d_p(ew) || !r3d_p(inv) || !r3d_wp(y)) return R3D_NO(RAD_E_INVAL);
if (ye->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
if (ew->dtype != RAD_BF16 && ew->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE);
if (inv->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE);
const long long M = r3d_geti_or(a, "M", 0), n = r3d_geti_or(a, "n", 0),
top_k = r3d_geti_or(a, "top_k", 0);
if (M <= 0 || n <= 0 || top_k <= 0) return R3D_NO(RAD_E_SHAPE);
if (top_k > kGatherSlots) return R3D_NO(RAD_E_SHAPE); // the LDS-cached form only
const uint32_t ye_ld = (uint32_t)(ye->rank >= 2 ? ye->shape[1] : ye->stride[0]);
const uint32_t ew_ld = (uint32_t)(ew->rank >= 2 ? ew->shape[1] : ew->stride[0]);
const uint32_t y_ld = (uint32_t)(y->rank >= 2 ? y->shape[1] : y->stride[0]);
const uint32_t T = (uint32_t)r3d_numel(inv);
if (T < M * top_k) return R3D_NO(RAD_E_SHAPE);
const RadTensor* sh = r3d_opt(a, 3), *sg = r3d_opt(a, 4);
const uint16_t* shp = sh ? (const uint16_t*)r3d_p(sh) : nullptr;
const uint16_t* sgp = sg ? (const uint16_t*)r3d_p(sg) : nullptr;
if (sh && !sg) return R3D_NO(RAD_E_INVAL);
const uint32_t sh_ld = sh ? (uint32_t)(sh->rank >= 2 ? sh->shape[1] : sh->stride[0]) : 0;
const uint32_t sg_ld = sg ? (uint32_t)(sg->rank >= 1 ? sg->shape[0] : sg->stride[0]) : 1;
int sig = 0;
if (const char* act = r3d_gets(a, "act")) {
if (std::string(act) == "sigmoid") sig = 1;
else if (std::string(act) == "none") return R3D_NO(RAD_E_INVAL);
}
const bool f32w = (ew->dtype == RAD_F32);
dim3 grid((unsigned)M, (unsigned)((n + kGatherThr - 1) / kGatherThr)), blk(kGatherThr);
if (f32w)
R3D_KLAUNCH(gather_kernel<Gk::f32_inv>, grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(ye), r3d_p(ew), (const int32_t*)r3d_p(inv),
(uint16_t*)r3d_wp(y), (uint32_t)M, (uint32_t)n, (uint32_t)top_k, ye_ld, ew_ld,
y_ld, (const int32_t*)nullptr, T, shp, sgp, sh_ld, sg_ld, sig);
else
R3D_KLAUNCH(gather_kernel<Gk::bf16_inv>, grid, blk, (hipStream_t)s,
(const uint16_t*)r3d_p(ye), r3d_p(ew), (const int32_t*)r3d_p(inv),
(uint16_t*)r3d_wp(y), (uint32_t)M, (uint32_t)n, (uint32_t)top_k, ye_ld, ew_ld,
y_ld, (const int32_t*)nullptr, T, shp, sgp, sh_ld, sg_ld, sig);
return (int)hipGetLastError();
}
} // extern "C"
+340
View File
@@ -0,0 +1,340 @@
/* r3d_moe_gemm_bf16.hip -- moe_gemm_bf16: the grouped GEMM with unquantised bf16 experts.
*
* y[i, n] = sum_k a[tok(i), k] * w_e[n, k], e = the expert of sorted row i
*
* One block per 16 expert-sorted rows, walking the runs (contiguous rows per expert) in its tile.
* bf16 activation, bf16 weight as the checkpoint stores it ([n_expert, N, K] row-major, no layout
* hook, every expert in class 0), f32 accumulate over the whole of K, bf16 out. The 16-row tile is
* the same run-walk / gather structure as moe_gemm_q, minus the E4M3 decode and the scale fold:
* the operands are bf16, so they stage to LDS and load straight into the bf16 wave-matrix
* fragments (v_wmma_f32_16x16x16_bf16, f32 accumulate).
*
* K is walked in 64-deep tiles (four 16-wide wave-matrix steps); N and K are multiples of 16.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
namespace {
constexpr int kThreads = 256; // eight waves
constexpr int kWaves = kThreads / kWave;
constexpr int kNBlock = 128; // eight waves x 16 cols
constexpr int kKT = 64; // a k tile: four 16-wide wmma steps
constexpr int kDW = kKT / 2; // dwords a row: 64 bf16 are 32 dwords (two bf16 a dword)
constexpr int kPitch = kDW + 1; // dwords a staged row: +1, bank-free
constexpr int kStageW = kNBlock * kDW / kThreads; // ...and of the weight (128 cols)
/* MROWS is the block's row count (16, 32 or 64), the tune's point: a taller block reads the
* weight T/MROWS times, so the tune picks per shape -- 16 for decode, 64 for a tall prefill. */
/* The kernel, emitted once per (row count, register budget) point. amdgpu_num_vgpr takes a
* literal, so the budget cannot live on a template; and the definitions stay monolithic, because
* the allocator schedules the inlined-body form (a __device__ helper) noticeably worse.
*
* Register budgets (gfx11: 1024 VGPRs/SIMD, 8 waves needs <= 128; measured on gfx1102 at
* T=N=K=4096 NE=8, median of 15 launches):
* (32, 128): 144 VGPR, 6 spills = 7 waves -- +38% vs (32, 512) at 171 VGPR = 5 waves: the middle
* height is latency-bound, so the extra waves beat the spill traffic.
* (16, 128) and (64, 128) measure 7-8% SLOWER (145/8 and 193/54 spills), so those rows keep the
* natural allocation only.
* Re-measure before touching a budget here; occupancy is a means to hide latency, not a goal
* (GPUOpen, "Occupancy explained": only latency-bound work benefits, and spills can cost more). */
/* The accumulator's mode (the tune's `acc` axis): 0 = f32, 1 = the bf16-precision WMMA
* accumulator (the 16x16x16_bf16 builtin, OPSEL false: the 8 live values in the even indices of
* a v16, 4 VGPRs). `blk` is the per-k-tile accumulator; it is folded into the f32 `acc` after
* each 64-wide k tile, so the half-precision span is one tile, not the whole K.
*
* PRECISION (measured on gfx1102, random bf16 in [-1,1], K = 128): the acc=1 arm deviates from
* the f32 reference by up to ~0.36 absolute (~3% of a typical |y| ~ 11; larger relative to
* near-zero outputs). The 16-bit WMMA accumulator is a documented low-precision mode (AMD ROCm
* Optimization Guide, RDNA3 dense WMMA builtins; the same builtin chain AMD's ck uses): the
* hardware quantises the running sum at 16-bit precision per step, and the loss grows with the
* number of steps. Exact on integer-valued data (e.g. +/-1 inputs). There is NO throughput gain
* from the acc=1 arm (measured +0.05%..-0.2%): it exists as a register-pressure option for
* future occupancy work, not a speed one. Do not select acc=1 for accuracy-sensitive shapes;
* the f32 arm (acc=0) is the correct default. */
template <bool ACC>
struct R3dMoeAcc { using type = std::conditional_t<ACC, v16short, v8float>; };
template <bool ACC>
__device__ __forceinline__ void r3d_moe_acc_init(typename R3dMoeAcc<ACC>::type& x)
{
if constexpr (ACC) x = v16short{ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
else x = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
}
template <bool ACC>
__device__ __forceinline__ typename R3dMoeAcc<ACC>::type r3d_moe_wmma_bf16(
const v16short& fa, const v16short& fb, const typename R3dMoeAcc<ACC>::type& c)
{
if constexpr (ACC) return wmma_bf16acc<false>(fa, fb, c);
else return wmma_bf16(fa, fb, c);
}
template <bool ACC>
__device__ __forceinline__ float r3d_moe_acc_read(const typename R3dMoeAcc<ACC>::type& x, int g)
{
if constexpr (ACC) {
const uint32_t u = (uint32_t)(uint16_t)x[2 * g] << 16; /* the bf16 bits -> f32 */
return *(const float*)&u;
}
return x[g];
}
#define R3D_MBE_BODY \
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) \
__attribute__((amdgpu_num_vgpr(MBE_VGPR))) void MBE_KNAME( \
const uint16_t* __restrict__ a, \
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, \
const uint16_t* __restrict__ w, \
uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int w_ld, int y_ld, \
int n_expert, int top_k) \
{ \
constexpr int kMBlock = MBE_MR; /* a block is MBE_MR rows x 128 cols */ \
constexpr int kRB = MBE_MR / 16; /* row-blocks a wave accumulates */ \
constexpr int kStageA = MBE_MR * kDW / kThreads; /* dwords a thread stages of the activation */ \
__shared__ __align__(16) uint32_t s_a[2][kMBlock * kPitch]; /* double-buffered activation (32 rows) */ \
__shared__ __align__(16) uint32_t s_w[2][kNBlock * kPitch]; /* ...and weight (128 cols) */ \
__shared__ int32_t s_tok[kMBlock]; \
__shared__ int32_t s_nruns; \
__shared__ int32_t s_rs[kMBlock], s_re[kMBlock], s_e[kMBlock]; \
\
const uint32_t tid = threadIdx.x; \
const uint32_t lane = tid & (kWave - 1); \
const uint32_t wv = tid / kWave; /* the wave index (0..7): owns cols wv*16..wv*16+16 */ \
const uint32_t r = lane & 15; \
\
const uint32_t r0 = (uint32_t)blockIdx.y * kMBlock; /* the block's sorted rows */ \
const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock; \
const uint32_t r1 = (r0 + kMBlock < (uint32_t)T) ? r0 + kMBlock : (uint32_t)T; \
\
/* The block's rows' source tokens (the gather). -1 marks a dropped slot. */ \
if (tid < kMBlock) { \
const uint32_t i = r0 + tid; \
const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; \
s_tok[tid] = (f < 0) ? -1 : (f / top_k); \
} \
/* The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them. */ \
if (tid == 0) { \
int nruns = 0, i = (int)r0; \
while (i < (int)r1) { \
int32_t ee = -1; \
for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x; \
const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1); \
s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee; \
++nruns; i = re; \
} \
s_nruns = nruns; \
} \
group_barrier(); \
const int nruns = s_nruns; \
\
const uint32_t nc = n0 + wv * 16 + r; /* this wave's output column */ \
const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1); \
\
/* One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the */ \
/* run does not own are padding (reading the run's first row) and their output is dropped. */ \
for (int run = 0; run < nruns; ++run) { \
const int rs = s_rs[run], re = s_re[run], e = s_e[run]; \
v8float acc[kRB]; \
_Pragma("unroll") \
for (int rb = 0; rb < kRB; ++rb) \
acc[rb] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; \
if (e >= 0) { \
const uint16_t* wbase = w + (size_t)e * (size_t)N * w_ld; \
\
const int ntile = (K + kKT - 1) / kKT; \
/* Prologue: stage tile 0 into buffer 0. */ \
for (int i = (int)tid; i < kMBlock * kDW; i += kThreads) { \
const int row = i / kDW, d = i % kDW; \
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] \
: s_tok[rs - (int)r0]; \
const int rr = (src < 0) ? 0 : src; \
s_a[0][(size_t)row * kPitch + d] = *(const uint32_t*)(a + (size_t)rr * a_ld + 2 * d); \
} \
for (int i = (int)tid; i < kNBlock * kDW; i += kThreads) { \
const int col = i / kDW, d = i % kDW; \
const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); \
s_w[0][(size_t)col * kPitch + d] = *(const uint32_t*)(wbase + (size_t)nn * w_ld + 2 * d); \
} \
group_barrier(); \
/* Pipelined: the next tile's global loads are issued into registers before this tile's WMMA, */ \
/* so the ~300-cycle VRAM latency is hidden behind the matrix-core work; they land in the */ \
/* other buffer after the WMMA (the s_waitcnt of the LDS store waits on the in-flight loads). */ \
for (int t = 0; t < ntile; ++t) { \
const int b = t & 1, nb = b ^ 1; \
uint32_t ra[kStageA], rw[kStageW]; \
if (t + 1 < ntile) { \
const int kt1 = (t + 1) * kKT; \
_Pragma("unroll") \
for (int i = (int)tid; i < kMBlock * kDW; i += kThreads) { \
const int li = (i - (int)tid) / kThreads; \
const int row = i / kDW, d = i % kDW; \
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] \
: s_tok[rs - (int)r0]; \
const int rr = (src < 0) ? 0 : src; \
ra[li] = *(const uint32_t*)(a + (size_t)rr * a_ld + kt1 + 2 * d); \
} \
for (int i = (int)tid; i < kNBlock * kDW; i += kThreads) { \
const int li = (i - (int)tid) / kThreads; \
const int col = i / kDW, d = i % kDW; \
const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); \
rw[li] = *(const uint32_t*)(wbase + (size_t)nn * w_ld + kt1 + 2 * d); \
} \
} \
const uint32_t* wp = s_w[b] + (size_t)(wv * 16 + r) * kPitch; /* this wave's 16 cols */ \
_Pragma("unroll") \
for (int rb = 0; rb < kRB; ++rb) { /* the 16-row blocks; the B-fragment is shared */ \
const uint32_t* ap = s_a[b] + (size_t)(rb * 16 + r) * kPitch; \
typename R3dMoeAcc<MBE_ACC>::type blk; \
r3d_moe_acc_init<MBE_ACC>(blk); \
_Pragma("unroll") \
for (int k = 0; k < kKT; k += 16) { \
v16short fa, fb; \
_Pragma("unroll") \
for (int g = 0; g < 8; ++g) { \
const uint32_t dw = ap[k / 2 + g]; \
fa[2 * g] = (short)(dw & 0xffffu); fa[2 * g + 1] = (short)(dw >> 16); \
const uint32_t dwb = wp[k / 2 + g]; \
fb[2 * g] = (short)(dwb & 0xffffu); fb[2 * g + 1] = (short)(dwb >> 16); \
} \
blk = r3d_moe_wmma_bf16<MBE_ACC>(fa, fb, blk); \
} \
_Pragma("unroll") \
for (int g = 0; g < 8; ++g) acc[rb][g] += r3d_moe_acc_read<MBE_ACC>(blk, g); \
} \
if (t + 1 < ntile) { \
for (int i = (int)tid; i < kMBlock * kDW; i += kThreads) { \
const int li = (i - (int)tid) / kThreads; \
const int row = i / kDW, d = i % kDW; \
s_a[nb][(size_t)row * kPitch + d] = ra[li]; \
} \
for (int i = (int)tid; i < kNBlock * kDW; i += kThreads) { \
const int li = (i - (int)tid) / kThreads; \
const int col = i / kDW, d = i % kDW; \
s_w[nb][(size_t)col * kPitch + d] = rw[li]; \
} \
} \
group_barrier(); \
} \
\
} \
/* Store only the run's rows, as bf16, across the 16-row blocks. */ \
_Pragma("unroll") \
for (int rb = 0; rb < kRB; ++rb) \
_Pragma("unroll") \
for (int g = 0; g < 8; ++g) { \
const int row = (int)(rb * 16 + g * 2 + (lane >> 4)); \
const int m = (int)(r0 + row); \
if (rs <= m && m < re && nc < (uint32_t)N) \
y[(size_t)m * y_ld + nc] = f32_to_bf16(acc[rb][g]); \
} \
} \
}
#define MBE_KNAME moe_bf16_kernel16
#define MBE_MR 16
#define MBE_VGPR 512
#define MBE_ACC 0
R3D_MBE_BODY
#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC
#define MBE_KNAME moe_bf16_kernel16_a1
#define MBE_MR 16
#define MBE_VGPR 512
#define MBE_ACC 1
R3D_MBE_BODY
#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC
#define MBE_KNAME moe_bf16_kernel32
#define MBE_MR 32
#define MBE_VGPR 512
#define MBE_ACC 0
R3D_MBE_BODY
#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC
#define MBE_KNAME moe_bf16_kernel32_a1
#define MBE_MR 32
#define MBE_VGPR 512
#define MBE_ACC 1
R3D_MBE_BODY
#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC
#define MBE_KNAME moe_bf16_kernel32_c128
#define MBE_MR 32
#define MBE_VGPR 128
#define MBE_ACC 0
R3D_MBE_BODY
#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC
#define MBE_KNAME moe_bf16_kernel32_c128_a1
#define MBE_MR 32
#define MBE_VGPR 128
#define MBE_ACC 1
R3D_MBE_BODY
#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC
#define MBE_KNAME moe_bf16_kernel64
#define MBE_MR 64
#define MBE_VGPR 512
#define MBE_ACC 0
R3D_MBE_BODY
#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC
#define MBE_KNAME moe_bf16_kernel64_a1
#define MBE_MR 64
#define MBE_VGPR 512
#define MBE_ACC 1
R3D_MBE_BODY
#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC
#undef R3D_MBE_BODY
} // namespace
extern "C" {
int r3d_rad_moe_gemm_bf16(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL);
const RadTensor* at = r3d_opt(a, 0), *wt = r3d_opt(a, 1), *st = r3d_opt(a, 2),
*ot = r3d_opt(a, 3), *yt = r3d_opt(a, 4);
if (!r3d_p(at) || !r3d_p(wt) || !r3d_p(st) || !r3d_p(ot) || !r3d_wp(yt))
return R3D_NO(RAD_E_INVAL);
long long M = 0, K = 0;
if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
const long long T = (st->rank >= 1) ? st->shape[0] : 0;
const long long N = (wt->rank >= 3) ? wt->shape[1] : 0;
if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || (K & 63)) return R3D_NO(RAD_E_SHAPE); // N tail clamps
const int n_expert = (int)r3d_geti_or(a, "n_expert", 1);
const int top_k = (int)r3d_geti_or(a, "top_k", 1);
const int a_ld = (int)at->stride[0];
const int w_ld = (int)wt->shape[2];
const int y_ld = (int)yt->stride[0];
R3dMoeCfg c; r3d_cfg_moe(a, &c); // the tune's row count (16, 32 or 64), 64 untuned
#define R3D_LM(MR, KERN) \
do { \
dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + MR - 1) / MR)), \
blk(kThreads); \
KERN<<<grid, blk, 0, (hipStream_t)s>>>( \
(const uint16_t*)r3d_p(at), (const int32_t*)r3d_p(st), (const int32_t*)r3d_p(ot), \
(const uint16_t*)r3d_p(wt), (uint16_t*)r3d_wp(yt), (int)T, (int)N, (int)K, a_ld, w_ld, \
y_ld, n_expert, top_k); \
} while (0)
if (c.mrows <= 16) {
if (c.acc) R3D_LM(16, moe_bf16_kernel16_a1);
else R3D_LM(16, moe_bf16_kernel16);
}
else if (c.mrows <= 32) {
if (c.vgpr == 128) {
if (c.acc) R3D_LM(32, moe_bf16_kernel32_c128_a1);
else R3D_LM(32, moe_bf16_kernel32_c128);
}
else {
if (c.acc) R3D_LM(32, moe_bf16_kernel32_a1);
else R3D_LM(32, moe_bf16_kernel32);
}
}
else {
if (c.acc) R3D_LM(64, moe_bf16_kernel64_a1);
else R3D_LM(64, moe_bf16_kernel64);
}
#undef R3D_LM
return (int)hipGetLastError();
}
} // extern "C"
+342
View File
@@ -0,0 +1,342 @@
/* r3d_moe_gemm_fp8_f32scale.hip -- moe_gemm_q (the wave-matrix form): the grouped GEMM with E4M3
* experts and exact F32 block scales.
*
* y[i, n] = sum_g as[tok(i), g] * wsb[e, n/grid_rows][g] * sum_{k in g} a[tok(i), k] * w_e[n, k]
*
* The moe_gemm_q contract: a and the weight planes are E4M3, one F32 scale per (row, 128 of K)
* for the activation and one per (plane expert, n/grid_rows, 128 of K) for the weight; the even
* experts live in w / w_scale and the odd in w_odd / w_odd_scale, at index e/2; y is f32 in sorted
* order. E4M3 activation and E4M3 weight (the checkpoint stores the plane as [n_expert/2, N, K]
* row-major, one byte a code). f32 accumulate over the whole of K.
*
* gfx11 has no native FP8 wave-matrix, so the codes widen to f16 (exact: every E4M3 grid point is
* an f16 grid point) and the multiply runs on the 16x16x16 f16 tile. K is walked in 128-deep
* tiles (the scale group); each tile's eight 16-wide steps accumulate into a fresh f32 partial,
* which is folded as raw * (activation scale * weight scale) into the running sum. The 16-row
* tile is the same run-walk / gather structure as moe_gemm_bf16.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_fp8_dequant.h"
#include "r3d_launch.h"
namespace {
constexpr int kThreads = 256; // eight waves
constexpr int kWaves = kThreads / kWave;
constexpr int kNBlock = 128; // eight waves x 16 cols
constexpr int kKT = 128; // a k tile: one scale group (eight 16-wide wmma steps)
constexpr int kDW = kKT / 4; // dwords a row: 128 fp8 are 32 dwords (four fp8 a dword)
constexpr int kPitch = kDW + 1; // dwords a staged row: +1, bank-free
constexpr int kStageW = kNBlock * kDW / kThreads;
constexpr int kP16 = kKT + 1; // f16 halfs a staged row: 128 + 1, bank-free
/* The kernel, emitted once per register-budget point. amdgpu_num_vgpr takes a literal, so the
* budget cannot live on a template; and the definitions stay monolithic, because the allocator
* schedules the inlined-body form (a __device__ helper) noticeably worse.
*
* Register budgets (gfx11: 1024 VGPRs/SIMD, 8 waves needs <= 128; measured on gfx1102 at
* T=N=K=4096 NE=8, median of 15 launches): the natural 155 VGPRs give 6 waves; the 128 cap lands
* at 103 with zero spills = 8 waves, +2-4%. The tune exposes both points (tMoeGemmFp8) and
* defaults to the cap. Re-measure before changing a budget here. */
/* The accumulator's mode (the tune's `acc` axis): 0 = f32, 1 = the f16-precision WMMA
* accumulator (the 16x16x16_f16 builtin, OPSEL false: the 8 live values in the even indices of a
* v16, 4 VGPRs). `blk` is the per-k-tile accumulator; it is folded (with the per-row scale) into
* the f32 `acc` after each 128-wide k tile, so the half-precision span is one tile, not the K.
*
* PRECISION (measured on gfx1102): the acc=1 arm quantises the per-tile f16 partial sum at 16-bit
* precision per wave-matrix step (the hardware's documented low-precision mode, same builtin
* chain AMD's ck uses). On exactly-representable E4M3 code data (0.5/1.0) it is bit-exact to the
* f32 arm (store rounding only); on arbitrary f16 data the deviation grows with the k-tile depth
* (~0.17 abs over 4 steps of 16-wide random f16 in [-1,1], measured). No throughput gain from
* acc=1 (measured +0.2%..-1%). It exists as a register-pressure option, not a speed one; acc=0
* is the correct default for accuracy-sensitive shapes. */
template <bool ACC>
struct R3dMoeAccF16 { using type = std::conditional_t<ACC, v16half, v8float>; };
template <bool ACC>
__device__ __forceinline__ void r3d_moe_acc_f16_init(typename R3dMoeAccF16<ACC>::type& x)
{
if constexpr (ACC) x = v16half{ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
else x = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
}
template <bool ACC>
__device__ __forceinline__ typename R3dMoeAccF16<ACC>::type r3d_moe_wmma_f16(
const v16half& fa, const v16half& fb, const typename R3dMoeAccF16<ACC>::type& c)
{
if constexpr (ACC) return wmma_f16acc<false>(fa, fb, c);
else return wmma_f16(fa, fb, c);
}
template <bool ACC>
__device__ __forceinline__ float r3d_moe_acc_f16_read(const typename R3dMoeAccF16<ACC>::type& x, int g)
{
/* Direct f16 -> f32 value conversion. NOT a bit-cast: type-punning the OPSEL
* (16-bit-accumulator) vector through a union breaks the srcC == result physical-
* register constraint, and the compiler then reads the wmma result from the stale
* srcC copy (measured: the accumulated tile comes back as zero). */
if constexpr (ACC) return (float)x[2 * g];
return x[g];
}
#define R3D_MFS_BODY \
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) \
__attribute__((amdgpu_num_vgpr(MFS_VGPR))) void MFS_KNAME( \
const uint8_t* __restrict__ a, const float* __restrict__ as, \
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, \
const uint8_t* __restrict__ w, const float* __restrict__ ws, \
const uint8_t* __restrict__ w_odd, const float* __restrict__ w_ws, \
float* __restrict__ y, int T, int N, int K, int a_ld, int w_ld, int y_ld, \
int n_expert, int top_k, int grid_rows) \
{ \
constexpr int kMBlock = 16; \
constexpr int kRB = 1; \
__shared__ __align__(16) uint16_t s_a[kMBlock * kP16]; /* activation f16 (128 per row) */ \
__shared__ __align__(16) uint16_t s_w[kNBlock * kP16]; /* weight f16 (128 per row) */ \
__shared__ uint16_t s_tbl[256]; /* the e4m3 -> f16 table */ \
__shared__ int32_t s_tok[kMBlock]; \
__shared__ int32_t s_nruns; \
__shared__ int32_t s_rs[kMBlock], s_re[kMBlock], s_e[kMBlock]; \
\
const uint32_t tid = threadIdx.x; \
const uint32_t lane = tid & (kWave - 1); \
const uint32_t wv = tid / kWave; \
const uint32_t r = lane & 15; \
\
/* The e4m3 -> f16 table: filled once before any lane reads it. */ \
r3d_e4m3_f16_init(s_tbl, (int)tid, (int)kThreads); \
\
const uint32_t r0 = (uint32_t)blockIdx.y * kMBlock; \
const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock; \
const uint32_t r1 = (r0 + kMBlock < (uint32_t)T) ? r0 + kMBlock : (uint32_t)T; \
\
if (tid < kMBlock) { \
const uint32_t i = r0 + tid; \
const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; \
s_tok[tid] = (f < 0) ? -1 : (f / top_k); \
} \
if (tid == 0) { \
int nruns = 0, i = (int)r0; \
while (i < (int)r1) { \
int32_t ee = -1; \
for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x; \
const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1); \
s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee; \
++nruns; i = re; \
} \
s_nruns = nruns; \
} \
group_barrier(); \
const int nruns = s_nruns; \
\
const uint32_t nc = n0 + wv * 16 + r; \
const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1); \
\
for (int run = 0; run < nruns; ++run) { \
const int rs = s_rs[run], re = s_re[run], e = s_e[run]; \
float acc[kRB][8]; \
_Pragma("unroll") \
for (int rb = 0; rb < kRB; ++rb) \
_Pragma("unroll") \
for (int g = 0; g < 8; ++g) acc[rb][g] = 0.f; \
if (e >= 0) { \
/* Expert e's plane: even e in w / ws, odd e in w_odd / w_ws, at index e/2. */ \
const int e2 = e >> 1; \
const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld \
: w + (size_t)e2 * (size_t)N * w_ld; \
const float* wsb = (e & 1) ? w_ws + (size_t)e2 * (size_t)(N / grid_rows) * ((K + 127) / 128) \
: ws + (size_t)e2 * (size_t)(N / grid_rows) * ((K + 127) / 128); \
\
\
const int ntile = (K + kKT - 1) / kKT; \
for (int t = 0; t < ntile; ++t) { \
const int kt = t * kKT; \
/* Stage the activation and weight for this 128-k tile, dequantizing E4M3 -> f16 */ \
/* through the table (the mxfp4a8 pattern: f16 in LDS, WMMA reads f16 directly). */ \
for (int i = (int)tid; i < kMBlock * kKT; i += kThreads) { \
const int row = i / kKT, k = i % kKT; \
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] \
: s_tok[rs - (int)r0]; \
const int rr = (src < 0) ? 0 : src; \
s_a[(size_t)row * kP16 + k] = s_tbl[a[(size_t)rr * a_ld + kt + k]]; \
} \
for (int i = (int)tid; i < kNBlock * kKT; i += kThreads) { \
const int col = i / kKT, k = i % kKT; \
const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); \
s_w[(size_t)col * kP16 + k] = s_tbl[wbase[(size_t)nn * w_ld + kt + k]]; \
} \
group_barrier(); \
/* The activation scale for this tile (per row) and the weight scale (per grid_rows cols). */ \
const float wscale = wsb[(size_t)(n_real / grid_rows) * ((K + 127) / 128) + t]; \
/* Eight 16-wide f16 WMMA steps; f16 values read directly from LDS. The fragment */ \
/* elements are f16 BIT PATTERNS, so the LDS halfs must be bit-cast into the */ \
/* _Float16 vector: any assignment from a uint16_t source into a _Float16 (a plain */ \
/* `fa[j] = ap[k+j]`, or a union whose half members are uint16_t) is a VALUE */ \
/* conversion (code 0x4300, i.e. f16 3.5, would become the number 17152.0) and */ \
/* corrupts every product. The union's half members must themselves be _Float16. */ \
_Pragma("unroll") \
for (int rb = 0; rb < kRB; ++rb) { \
typename R3dMoeAccF16<MFS_ACC>::type blk; \
r3d_moe_acc_f16_init<MFS_ACC>(blk); \
const uint16_t* ap = s_a + (size_t)(rb * 16 + r) * kP16; \
const uint16_t* wp = s_w + (size_t)(wv * 16 + r) * kP16; \
_Pragma("unroll") \
for (int k = 0; k < kKT; k += 16) { \
v16half fa, fb; \
const uint32_t* ap32 = (const uint32_t*)(ap + k); \
const uint32_t* wp32 = (const uint32_t*)(wp + k); \
_Pragma("unroll") \
for (int j = 0; j < 8; ++j) { \
union { uint32_t u; _Float16 h[2]; } ca, cb; \
ca.u = ap32[j]; cb.u = wp32[j]; \
fa[2 * j] = ca.h[0]; fa[2 * j + 1] = ca.h[1]; \
fb[2 * j] = cb.h[0]; fb[2 * j + 1] = cb.h[1]; \
} \
blk = r3d_moe_wmma_f16<MFS_ACC>(fa, fb, blk); \
} \
/* Fold: raw * (activation scale * weight scale). Each output g is for a different */ \
/* row (rb*16 + g*2 + (lane>>4)), so each needs its own source token and scale. */ \
_Pragma("unroll") \
for (int g = 0; g < 8; ++g) { \
const int row = rb * 16 + g * 2 + (int)(lane >> 4); \
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) \
? s_tok[row] : s_tok[rs - (int)r0]; \
const float ascale = (src < 0) ? 0.f : as[(size_t)src * ((K + 127) / 128) + t] * wscale; \
acc[rb][g] += r3d_moe_acc_f16_read<MFS_ACC>(blk, g) * ascale; \
} \
} \
group_barrier(); \
} \
} \
/* Store only the run's rows (f32: the moe_gemm_q contract's output). */ \
_Pragma("unroll") \
for (int rb = 0; rb < kRB; ++rb) \
_Pragma("unroll") \
for (int g = 0; g < 8; ++g) { \
const int m = (int)r0 + rb * 16 + g * 2 + (int)(lane >> 4); \
if (m < re && m >= rs) \
y[(size_t)m * y_ld + nc] = acc[rb][g]; \
} \
} \
}
#define MFS_KNAME moe_fp8_f32scale_kernel16
#define MFS_VGPR 512
#define MFS_ACC 0
R3D_MFS_BODY
#undef MFS_KNAME MFS_VGPR MFS_ACC
#define MFS_KNAME moe_fp8_f32scale_kernel16_a1
#define MFS_VGPR 512
#define MFS_ACC 1
R3D_MFS_BODY
#undef MFS_KNAME MFS_VGPR MFS_ACC
#define MFS_KNAME moe_fp8_f32scale_kernel16_c128
#define MFS_VGPR 128
#define MFS_ACC 0
R3D_MFS_BODY
#undef MFS_KNAME MFS_VGPR MFS_ACC
#define MFS_KNAME moe_fp8_f32scale_kernel16_c128_a1
#define MFS_VGPR 128
#define MFS_ACC 1
R3D_MFS_BODY
#undef MFS_KNAME MFS_VGPR MFS_ACC
#undef R3D_MFS_BODY
} // namespace
static int r3d_moe_gemm_fp8_f32scale_v(long a, long as, long sorted, long off, long w, long ws,
long w_odd, long w_ws, long y,
int T, int N, int K, int a_ld, int w_ld, int y_ld,
int n_expert, int top_k, int grid_rows, int vgpr, int acc,
long stream)
{
if (!a || !as || !sorted || !off || !w || !ws || !w_odd || !w_ws || !y) return -1;
if (T < 1 || N < 1 || K < 1 || grid_rows < 1) return -2;
if (!a_ld) a_ld = K;
if (!w_ld) w_ld = K;
if (!y_ld) y_ld = N;
if (K % kKT) return -2;
const int ntiles = (N + kNBlock - 1) / kNBlock;
const int mrowblk = (T + 16 - 1) / 16;
const dim3 grid(ntiles, mrowblk), block(kThreads);
if (vgpr == 128) {
if (acc)
R3D_KLAUNCH(moe_fp8_f32scale_kernel16_c128_a1, grid, block, (hipStream_t)stream,
(const uint8_t*)a, (const float*)as, (const int32_t*)sorted,
(const int32_t*)off, (const uint8_t*)w, (const float*)ws,
(const uint8_t*)w_odd, (const float*)w_ws, (float*)y,
T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows);
else
R3D_KLAUNCH(moe_fp8_f32scale_kernel16_c128, grid, block, (hipStream_t)stream,
(const uint8_t*)a, (const float*)as, (const int32_t*)sorted,
(const int32_t*)off, (const uint8_t*)w, (const float*)ws,
(const uint8_t*)w_odd, (const float*)w_ws, (float*)y,
T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows);
}
else {
if (acc)
R3D_KLAUNCH(moe_fp8_f32scale_kernel16_a1, grid, block, (hipStream_t)stream,
(const uint8_t*)a, (const float*)as, (const int32_t*)sorted,
(const int32_t*)off, (const uint8_t*)w, (const float*)ws,
(const uint8_t*)w_odd, (const float*)w_ws, (float*)y,
T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows);
else
R3D_KLAUNCH(moe_fp8_f32scale_kernel16, grid, block, (hipStream_t)stream,
(const uint8_t*)a, (const float*)as, (const int32_t*)sorted,
(const int32_t*)off, (const uint8_t*)w, (const float*)ws,
(const uint8_t*)w_odd, (const float*)w_ws, (float*)y,
T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows);
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The direct launcher: the tune's default budget (128, the 8-wave cap). */
extern "C" int r3d_moe_gemm_fp8_f32scale(long a, long as, long sorted, long off, long w, long ws,
long w_odd, long w_ws, long y,
int T, int N, int K, int a_ld, int w_ld, int y_ld,
int n_expert, int top_k, int grid_rows, long stream)
{
return r3d_moe_gemm_fp8_f32scale_v(a, as, sorted, off, w, ws, w_odd, w_ws, y, T, N, K, a_ld,
w_ld, y_ld, n_expert, top_k, grid_rows, 128, 0, stream);
}
/* The RadArgs dispatch: the row's entry. The tensors are a, a_scale, sorted_tok, expert_offset,
* w, w_scale, w_odd, w_odd_scale, y (the moe_gemm_q contract: even experts in w / w_scale, odd in
* w_odd / w_odd_scale, at index e/2; y is f32). The params are n_expert, top_k, grid_rows. */
extern "C" int r3d_moe_gemm_fp8_f32scale_run(const RadArgs* a, RadStream s, int vgpr, int acc)
{
if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL);
const RadTensor* at = &a->t[0], *ast = &a->t[1], *st = &a->t[2], *ot = &a->t[3];
const RadTensor* wt = &a->t[4], *wst = &a->t[5], *wot = &a->t[6], *wost = &a->t[7];
const RadTensor* yt = &a->t[8];
if (!r3d_p(at) || !r3d_p(ast) || !r3d_p(st) || !r3d_p(ot) ||
!r3d_p(wt) || !r3d_p(wst) || !r3d_p(wot) || !r3d_p(wost) || !r3d_wp(yt))
return R3D_NO(RAD_E_INVAL);
long long M = 0, K = 0;
if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
const long long T = (st->rank >= 1) ? st->shape[0] : 0;
const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; // the plane is [n_expert/2, N, K]
const int n_expert = (int)r3d_geti_or(a, "n_expert", 1);
const int top_k = (int)r3d_geti_or(a, "top_k", 1);
const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 1); // 1 (per col) or 128 (per 128)
if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128 || n_expert <= 0 || top_k <= 0)
return R3D_NO(RAD_E_SHAPE);
const int a_ld = (int)at->stride[0];
const int w_ld = (int)wt->shape[2];
const int y_ld = (int)yt->stride[0];
return r3d_moe_gemm_fp8_f32scale_v((long)(uintptr_t)r3d_p(at), (long)(uintptr_t)r3d_p(ast),
(long)(uintptr_t)r3d_p(st), (long)(uintptr_t)r3d_p(ot),
(long)(uintptr_t)r3d_p(wt), (long)(uintptr_t)r3d_p(wst),
(long)(uintptr_t)r3d_p(wot), (long)(uintptr_t)r3d_p(wost),
(long)(uintptr_t)r3d_wp(yt), (int)T, (int)N, (int)K, a_ld,
w_ld, y_ld, n_expert, top_k, grid_rows, vgpr, acc,
(long)(uintptr_t)s);
}
extern "C" int r3d_rad_moe_gemm_fp8_f32scale(const RadArgs* a, RadStream s)
{
R3dMoeCfg c; r3d_cfg_moe(a, &c); // the checker entry point's budget (128 default)
return r3d_moe_gemm_fp8_f32scale_run(a, s, c.vgpr, c.acc);
}
+224
View File
@@ -0,0 +1,224 @@
/* r3d_moe_gemm_mxfp4a8.hip -- moe_gemm_mxfp4a8: the grouped GEMM with canonical MXFP4 experts.
*
* y[i, n] = sum_k a[tok(i), k] * w_e[n, k], e = the expert of sorted row i
*
* The activation is E4M3 with one f32 scale per (row, 128 of K). The weight is canonical MXFP4:
* packed E2M1 codes (two a byte) with one E8M0 scale per 32 of K. E2M1's eight magnitudes
* {0, .5, 1, 1.5, 2, 3, 4, 6} are exactly representable in E4M3, so each weight code is decoded to
* an E4M3 byte (the v_perm_b32 unpack, the exact d=0 row) and both operands run on the f16
* wave-matrix (f32 accumulate). Each 32-wide E8M0 scale folds into the f32 accumulator per group.
*
* One block per 16 expert-sorted rows, walking the runs (contiguous rows per expert) in its tile,
* the same run-walk / gather structure as moe_gemm_q. The even experts are `w` / `w_scale`, the
* odd `w_odd` / `w_odd_scale`, at index e/2. K is a multiple of 128; N a multiple of 16.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
#include "r3d_fp8_dequant.h"
namespace {
constexpr int kThreads = 256; // eight waves
constexpr int kWaves = kThreads / kWave;
constexpr int kNBlock = 128; // a block is 16 rows x 128 cols: eight waves x 16 cols
constexpr int kGroup = 128; // a k tile: four 32-wide E8M0 groups
constexpr int kAPitch = 33; // dwords a staged activation row: 32 (128 E4M3) + 1
constexpr int kWPitch = 17; // dwords a staged weight row: 16 (128 E2M1 = 64 B) + 1
/* Eight packed E2M1 codes (four bytes, element 2j in the low nibble of byte j) -> eight E4M3 bytes
* in k order (word 0 = elements 0..3, word 1 = 4..7). The exact d=0 row of the folded-magnitude
* table (R4D_MXFP4_MAG0); E2M1's magnitudes are a subset of E4M3, so this is lossless. */
__device__ __forceinline__ void e2m1x8_to_e4m3x8(uint32_t wv, uint32_t* lo, uint32_t* hi)
{
const uint32_t t0 = 0x3c383000u, t1 = 0x4c484440u;
const uint32_t ev = wv & 0x0F0F0F0Fu; // low nibble of each byte -> even elements
const uint32_t od = (wv >> 4) & 0x0F0F0F0Fu; // high nibble -> odd elements
const uint32_t be = __builtin_amdgcn_perm(t1, t0, ev & 0x07070707u) | ((ev & 0x08080808u) << 4);
const uint32_t bo = __builtin_amdgcn_perm(t1, t0, od & 0x07070707u) | ((od & 0x08080808u) << 4);
*lo = __builtin_amdgcn_perm(bo, be, 0x05010400u);
*hi = __builtin_amdgcn_perm(bo, be, 0x07030602u);
}
/* An E8M0 byte to f32: the byte is the f32 exponent field (bias 127). Code 255 is NaN, code 0 is
* 2^-127 (a representable subnormal). */
__device__ __forceinline__ float e8m0_to_f32(uint32_t e)
{
return __uint_as_float(e == 255 ? 0x7fc00000u : e ? (e << 23) : 0x00200000u);
}
__device__ __forceinline__ _Float16 h16(uint32_t w) { return __builtin_bit_cast(_Float16, (uint16_t)w); }
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_mx_kernel(
const uint8_t* __restrict__ a, const float* __restrict__ a_scale,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
const uint8_t* __restrict__ w, const uint8_t* __restrict__ w_scale,
const uint8_t* __restrict__ w_odd, const uint8_t* __restrict__ w_odd_scale,
uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int w_ld_b, int y_ld,
int n_expert, int top_k, int grid_rows)
{
__shared__ __align__(16) uint32_t s_a[16 * kAPitch];
__shared__ __align__(16) uint32_t s_w[kNBlock * kWPitch];
__shared__ __align__(16) uint16_t s_tbl[R3D_E4M3_TBL];
__shared__ int32_t s_tok[16];
__shared__ int32_t s_nruns;
__shared__ int32_t s_rs[16], s_re[16], s_e[16];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wv = tid / kWave; // the wave index (0..7): owns cols wv*16..wv*16+16
const uint32_t r = lane & 15;
r3d_e4m3_f16_init(s_tbl, (int)tid, kThreads); // the E4M3 -> f16 table
const uint32_t r0 = (uint32_t)blockIdx.y * 16; // the block's sorted rows
const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock;
const uint32_t r1 = (r0 + 16 < (uint32_t)T) ? r0 + 16 : (uint32_t)T;
// The block's rows' source tokens (the gather). -1 marks a dropped slot.
if (tid < 16) {
const uint32_t i = r0 + tid;
const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1;
s_tok[tid] = (f < 0) ? -1 : (f / top_k);
}
// The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them.
if (tid == 0) {
int nruns = 0, i = (int)r0;
while (i < (int)r1) {
int32_t ee = -1;
for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x;
const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1);
s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee;
++nruns; i = re;
}
s_nruns = nruns;
}
group_barrier();
const int nruns = s_nruns;
const uint32_t nc = n0 + wv * 16 + r; // this wave's output column
const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1);
// One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the
// run does not own are padding (reading the run's first row) and their output is dropped.
for (int run = 0; run < nruns; ++run) {
const int rs = s_rs[run], re = s_re[run], e = s_e[run];
v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
if (e >= 0) {
const int e2 = e >> 1;
const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld_b
: w + (size_t)e2 * (size_t)N * w_ld_b;
const uint8_t* wsb = (e & 1) ? w_odd_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / 32)
: w_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / 32);
for (int b = 0; b < K / kGroup; ++b) {
const int kt = b * kGroup;
// Stage 16 rows x 128 E4M3 of the gathered activation; padding rows read the run's first.
for (int i = (int)tid; i < 16 * (kGroup / 4); i += kThreads) {
const int row = i / (kGroup / 4), d = i % (kGroup / 4);
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row]
: s_tok[rs - (int)r0];
const int rr = (src < 0) ? 0 : src;
s_a[(size_t)row * kAPitch + d] = *(const uint32_t*)(a + (size_t)rr * a_ld + kt + 4 * d);
}
// Stage 128 cols x 128 E2M1 of the expert's weight (64 bytes = 16 dwords a row).
for (int i = (int)tid; i < kNBlock * (kGroup / 8); i += kThreads) {
const int col = i / (kGroup / 8), d = i % (kGroup / 8);
const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1);
s_w[(size_t)col * kWPitch + d] =
*(const uint32_t*)(wbase + (size_t)nn * w_ld_b + kt / 2 + 4 * d);
}
group_barrier();
const uint32_t* ap = s_a + (size_t)r * kAPitch;
const uint32_t* wp = s_w + (size_t)(wv * 16 + r) * kWPitch; // this wave's 16 cols
// The weight scale for this lane's column, per 32-of-K group.
const int wn = (int)(n_real / grid_rows);
#pragma unroll
for (int g32 = 0; g32 < 4; ++g32) {
v8float blk = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
#pragma unroll
for (int k = g32 * 32; k < g32 * 32 + 32; k += 16) {
uint32_t af[8], bf[8];
// 16 E4M3 (four dwords) -> 16 f16 (eight dwords).
r3d_e4m3x8_decode<0>(s_tbl, uint2{ ap[k / 4], ap[k / 4 + 1] }, af);
r3d_e4m3x8_decode<0>(s_tbl, uint2{ ap[k / 4 + 2], ap[k / 4 + 3] }, af + 4);
// 16 E2M1 (two dwords) -> 16 E4M3 (four dwords) -> 16 f16 (eight dwords).
uint32_t e4lo, e4hi, e4lo2, e4hi2;
e2m1x8_to_e4m3x8(wp[k / 8], &e4lo, &e4hi);
e2m1x8_to_e4m3x8(wp[k / 8 + 1], &e4lo2, &e4hi2);
r3d_e4m3x8_decode<0>(s_tbl, uint2{ e4lo, e4hi }, bf);
r3d_e4m3x8_decode<0>(s_tbl, uint2{ e4lo2, e4hi2 }, bf + 4);
v16half fa, fb;
#pragma unroll
for (int q = 0; q < 8; ++q) { fa[2 * q] = h16(af[q] & 0xffffu); fa[2 * q + 1] = h16(af[q] >> 16); }
#pragma unroll
for (int q = 0; q < 8; ++q) { fb[2 * q] = h16(bf[q] & 0xffffu); fb[2 * q + 1] = h16(bf[q] >> 16); }
blk = wmma_f16(fa, fb, blk);
}
group_barrier();
// Fold the g32-group's scales: the weight E8M0 (per 32) and the activation f32 (per 128).
const float sw = e8m0_to_f32((uint32_t)wsb[(size_t)wn * (K / 32) + b * 4 + g32]);
#pragma unroll
for (int g = 0; g < 8; ++g) {
const int row = (int)(g * 2 + (lane >> 4));
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row]
: s_tok[rs - (int)r0];
const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * (K / kGroup) + b];
acc[g] += blk[g] * sa * sw;
}
}
}
}
// Store only the run's rows, as bf16.
#pragma unroll
for (int g = 0; g < 8; ++g) {
const int row = (int)(g * 2 + (lane >> 4));
const int m = (int)(r0 + row);
if (rs <= m && m < re && nc < (uint32_t)N)
y[(size_t)m * y_ld + nc] = f32_to_bf16(acc[g]);
}
}
}
} // namespace
extern "C" {
int r3d_rad_moe_gemm_mxfp4a8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL);
const RadTensor* at = r3d_opt(a, 0), *asc = r3d_opt(a, 1), *st = r3d_opt(a, 2),
*ot = r3d_opt(a, 3), *wt = r3d_opt(a, 4), *wsc = r3d_opt(a, 5),
*wot = r3d_opt(a, 6), *wosc = r3d_opt(a, 7), *yt = r3d_opt(a, 8);
if (!r3d_p(at) || !r3d_p(asc) || !r3d_p(st) || !r3d_p(ot) || !r3d_p(wt) || !r3d_p(wsc) ||
!r3d_wp(yt))
return R3D_NO(RAD_E_INVAL);
long long M = 0, K = 0;
if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
const long long T = (st->rank >= 1) ? st->shape[0] : 0;
const long long N = (wt->rank >= 3) ? wt->shape[1] : 0;
if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128) return R3D_NO(RAD_E_SHAPE); // N tail clamps
const int n_expert = (int)r3d_geti_or(a, "n_expert", 1);
const int top_k = (int)r3d_geti_or(a, "top_k", 1);
const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 128);
const int a_ld = (int)at->stride[0];
const int w_ld_b = (int)wt->shape[2]; // the weight's K in bytes (K/2 for E2M1)
const int y_ld = (int)yt->stride[0];
dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + 15) / 16)), blk(kThreads);
moe_mx_kernel<<<grid, blk, 0, (hipStream_t)s>>>(
(const uint8_t*)r3d_p(at), (const float*)r3d_p(asc), (const int32_t*)r3d_p(st),
(const int32_t*)r3d_p(ot), (const uint8_t*)r3d_p(wt), (const uint8_t*)r3d_p(wsc),
(const uint8_t*)r3d_p(wot), (const uint8_t*)r3d_p(wosc), (uint16_t*)r3d_wp(yt),
(int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld, n_expert, top_k, grid_rows);
return (int)hipGetLastError();
}
} // extern "C"
+227
View File
@@ -0,0 +1,227 @@
/* r3d_moe_gemm_q.hip -- moe_gemm_q (Phase 1: the GEMM core, dense rows, no gather).
*
* y[M,N] = a[M,K] @ w[N,K]^T, both operands E4M3, with a per-(row, g-of-K) scale fold.
*
* `a` and `w` are E4M3 (fp8) with one f32 scale per (row, g of K). RDNA3 has no fp8 matrix unit, so
* each operand is staged to LDS compactly (8-bit) and upcast to f16 in registers as the wave-matrix
* fragments load -- the FeatherOps `fp8e4m3x4_to_half2x2` bit trick (a V_PERM_B32 + shift-add, no
* table, no extra pass), then the f16 wave-matrix (`v_wmma_f32_16x16x16_f16`, f32 accumulate). Each
* g-wide block of K is accumulated raw, then folded by scale_a[m][b] * scale_w[n][b].
*
* STATUS: WIP. Phases 1-2 are verified against a CPU reference (maxrel ~1e-4, the f16 rounding
* floor):
* * Phase 1: the GEMM core (E4M3 x E4M3 -> f16 wave-matrix, the per-(row, 128-of-K) scale fold).
* * Phase 2: the gather (row i reads a[sorted[i]/top_k]), the per-expert weight tables, and the
* run structure (the block walks the runs in its 16 rows, so a block spanning several experts
* is correct).
*
* * Phase 3: the even/odd expert split (expert e's weight is in `w` for even e, `w_odd` for odd
* e, at index e/2) and the dtype-selected scale grid (`grid_rows` = 1 for w4a8's per-row scale,
* 128 for fp8a8's per-128x128 tile).
*
* Verified against a CPU reference for runs of 1, 2, 4 and 16 rows, the even/odd split, and both
* scale grids (maxrel ~1e-4, the f16 rounding floor). A row: `moe_gemm_q_e4m3` in r3d_rows.cpp, a
* selftest case in r3d_selftest.cpp.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include "r3d_fp8_dequant.h"
namespace {
constexpr int kThreads = 256; // eight waves
constexpr int kWaves = kThreads / kWave;
constexpr int kNBlock = 128; // a block is 16 rows x 128 cols: eight waves x 16 cols
constexpr int kGroup = 128; // a scale block: one k tile, eight wmma steps
constexpr int kPitch = 33; // dwords a staged row: 33 mod 32 = 1, bank-free
__device__ __forceinline__ _Float16 h16(uint32_t w) { return __builtin_bit_cast(_Float16, (uint16_t)w); }
template <int ALU>
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_q_kernel(
const uint8_t* __restrict__ a, const float* __restrict__ a_scale,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
const uint8_t* __restrict__ w, const float* __restrict__ w_scale,
const uint8_t* __restrict__ w_odd, const float* __restrict__ w_odd_scale,
float* __restrict__ y, int T, int N, int K, int a_ld, int w_ld_b, int y_ld,
int n_expert, int top_k, int grid_rows)
{
__shared__ __align__(16) uint32_t s_a[16 * kPitch];
__shared__ __align__(16) uint32_t s_w[kNBlock * kPitch];
__shared__ __align__(16) uint16_t s_tbl[R3D_E4M3_TBL];
__shared__ int32_t s_tok[16];
__shared__ int32_t s_nruns;
__shared__ int32_t s_rs[16], s_re[16], s_e[16];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wv = tid / kWave; // the wave index (0..7): owns cols wv*16..wv*16+16
const uint32_t r = lane & 15;
if (!ALU) r3d_e4m3_f16_init(s_tbl, (int)tid, kThreads); // the E4M3 -> f16 table (ALU=0)
const uint32_t r0 = (uint32_t)blockIdx.y * 16; // the block's sorted rows
const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock;
const uint32_t r1 = (r0 + 16 < (uint32_t)T) ? r0 + 16 : (uint32_t)T;
// The block's rows' source tokens (the gather). -1 marks a dropped slot.
if (tid < 16) {
const uint32_t i = r0 + tid;
const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1;
s_tok[tid] = (f < 0) ? -1 : (f / top_k);
}
// The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them.
if (tid == 0) {
int nruns = 0, i = (int)r0;
while (i < (int)r1) {
int32_t ee = -1;
for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x;
const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1);
s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee;
++nruns; i = re;
}
s_nruns = nruns;
}
group_barrier();
const int nruns = s_nruns;
const uint32_t nc = n0 + wv * 16 + r; // this wave's output column
const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1);
// One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the
// run does not own are padding (reading the run's first row) and their output is dropped. Expert
// e's weight is in `w` (even e) or `w_odd` (odd e) at index e/2.
for (int run = 0; run < nruns; ++run) {
const int rs = s_rs[run], re = s_re[run], e = s_e[run];
v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
if (e >= 0) {
const int e2 = e >> 1;
const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld_b
: w + (size_t)e2 * (size_t)N * w_ld_b;
const float* wsb = (e & 1) ? w_odd_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / kGroup)
: w_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / kGroup);
for (int b = 0; b < K / kGroup; ++b) {
const int kt = b * kGroup;
// Stage 16 rows x 128 E4M3 of the gathered activation; padding rows read the run's first.
for (int i = (int)tid; i < 16 * (kGroup / 4); i += kThreads) {
const int row = i / (kGroup / 4), d = i % (kGroup / 4);
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row]
: s_tok[rs - (int)r0];
const int rr = (src < 0) ? 0 : src;
s_a[(size_t)row * kPitch + d] = *(const uint32_t*)(a + (size_t)rr * a_ld + kt + 4 * d);
}
// Stage 128 cols x 128 E4M3 of the expert's weight (the block's columns).
for (int i = (int)tid; i < kNBlock * (kGroup / 4); i += kThreads) {
const int col = i / (kGroup / 4), d = i % (kGroup / 4);
const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1);
s_w[(size_t)col * kPitch + d] =
*(const uint32_t*)(wbase + (size_t)nn * w_ld_b + kt + 4 * d);
}
group_barrier();
const uint32_t* ap = s_a + (size_t)r * kPitch;
const uint32_t* wp = s_w + (size_t)(wv * 16 + r) * kPitch; // this wave's 16 cols
v8float blk = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
#pragma unroll
for (int k = 0; k < kGroup; k += 16) {
uint32_t ain[4], af[8], bin[4], bf[8];
#pragma unroll
for (int g = 0; g < 4; ++g) ain[g] = ap[k / 4 + g];
r3d_e4m3x16_decode<ALU>(s_tbl, ain, af);
#pragma unroll
for (int g = 0; g < 4; ++g) bin[g] = wp[k / 4 + g];
r3d_e4m3x16_decode<ALU>(s_tbl, bin, bf);
v16half fa, fb;
#pragma unroll
for (int g = 0; g < 8; ++g) { fa[2 * g] = h16(af[g] & 0xffffu); fa[2 * g + 1] = h16(af[g] >> 16); }
#pragma unroll
for (int g = 0; g < 8; ++g) { fb[2 * g] = h16(bf[g] & 0xffffu); fb[2 * g + 1] = h16(bf[g] >> 16); }
blk = wmma_f16(fa, fb, blk);
}
group_barrier();
// Fold the g-block's scales. acc[g] is at row g*2 + lane/16 (varies with g), column r.
// The weight scale is per (grid_rows columns, 128 of K).
const float sw = wsb[(size_t)(n_real / grid_rows) * (K / kGroup) + b];
#pragma unroll
for (int g = 0; g < 8; ++g) {
const int row = (int)(g * 2 + (lane >> 4));
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row]
: s_tok[rs - (int)r0];
const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * (K / kGroup) + b];
acc[g] += blk[g] * sa * sw;
}
}
}
// Store only the run's rows.
#pragma unroll
for (int g = 0; g < 8; ++g) {
const int row = (int)(g * 2 + (lane >> 4));
const int m = (int)(r0 + row);
if (rs <= m && m < re && nc < (uint32_t)N) y[(size_t)m * y_ld + nc] = acc[g];
}
}
}
} // namespace
extern "C" {
static int r3d_moe_gemm_q_dispatch(const RadArgs* a, RadStream s, int alu)
{
if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL);
const RadTensor* at = r3d_opt(a, 0), *asc = r3d_opt(a, 1), *st = r3d_opt(a, 2),
*ot = r3d_opt(a, 3), *wt = r3d_opt(a, 4), *wsc = r3d_opt(a, 5),
*wot = r3d_opt(a, 6), *wosc = r3d_opt(a, 7), *yt = r3d_opt(a, 8);
if (!r3d_p(at) || !r3d_p(asc) || !r3d_p(st) || !r3d_p(ot) || !r3d_p(wt) || !r3d_p(wsc) ||
!r3d_wp(yt))
return R3D_NO(RAD_E_INVAL);
long long M = 0, K = 0;
if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
const long long T = (st->rank >= 1) ? st->shape[0] : 0;
const long long N = (wt->rank >= 3) ? wt->shape[1] : 0;
if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128) return R3D_NO(RAD_E_SHAPE); // N tail clamps
const int n_expert = (int)r3d_geti_or(a, "n_expert", 1);
const int top_k = (int)r3d_geti_or(a, "top_k", 1);
const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 1); // 1 (w4a8) or 128 (fp8a8)
const int a_ld = (int)at->stride[0];
const int w_ld_b = (int)wt->shape[2]; // the weight's K in bytes
const int y_ld = (int)yt->stride[0];
dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + 15) / 16)), blk(kThreads);
const uint8_t* pa = (const uint8_t*)r3d_p(at);
const float* psa = (const float*)r3d_p(asc);
const int32_t* ps = (const int32_t*)r3d_p(st);
const int32_t* po = (const int32_t*)r3d_p(ot);
const uint8_t* pw = (const uint8_t*)r3d_p(wt);
const float* pws = (const float*)r3d_p(wsc);
const uint8_t* pwo = (const uint8_t*)r3d_p(wot);
const float* pwos = (const float*)r3d_p(wosc);
float* py = (float*)r3d_wp(yt);
if (alu)
moe_q_kernel<1><<<grid, blk, 0, (hipStream_t)s>>>(pa, psa, ps, po, pw, pws, pwo, pwos, py,
(int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld,
n_expert, top_k, grid_rows);
else
moe_q_kernel<0><<<grid, blk, 0, (hipStream_t)s>>>(pa, psa, ps, po, pw, pws, pwo, pwos, py,
(int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld,
n_expert, top_k, grid_rows);
return (int)hipGetLastError();
}
/* The two rows share the dispatch: the table decode (ALU=0) and the ALU decode (ALU=1). The tune
* picks the faster per geometry. */
extern "C" int r3d_rad_moe_gemm_q(const RadArgs* a, RadStream s)
{ return r3d_moe_gemm_q_dispatch(a, s, 0); }
extern "C" int r3d_rad_moe_gemm_q_alu(const RadArgs* a, RadStream s)
{ return r3d_moe_gemm_q_dispatch(a, s, 1); }
} // extern "C"
+193
View File
@@ -0,0 +1,193 @@
/* r3d_moe_gemm_w4a8.hip -- moe_gemm_w4a8 (Phase 2: the GEMM core + the gather + per-expert weights).
*
* y[T,N] = a[gather(row), :] @ w[e(row), :]^T, with a per-(row, 128-of-K) scale fold.
*
* The routed rows are in SORTED order (one row per (token, expert slot)); row i reads its
* activation from `a[sorted[i] / top_k]` and its weight from expert e(i)'s table, where e(i) is the
* expert owning sorted row i (the one whose [off, off') span contains i). `a` is int8 with one f32
* scale per (row, 128 of K); each expert's weight is a 4-bit two's-complement nibble (-8..7) packed
* two per byte, with one f32 scale per (row, 128 of K). RDNA3's native int8 wave-matrix
* (`v_wmma_i32_16x16x16_iu8`, exact i32 accumulate) takes the int4 weight widened to int8, so no f16
* rounding. Each 128-wide block of K is accumulated raw in i32, then folded by
* scale_a[src][b] * scale_w[e][n][b].
*
* STATUS: WIP. Phases 1-3 are verified bit-exact against a CPU reference (the i32 accumulate is
* exact, so the random cases are exact, not just within tolerance):
* * Phase 1: the GEMM core (int8 x widened-int4, the per-(row, 128-of-K) scale fold).
* * Phase 2: the gather (row i reads a[sorted[i]/top_k]) and the per-expert weight tables.
* * Phase 3: the run structure -- the block walks the runs in its 16 rows, so a block spanning
* several experts (short runs, decode) is correct. Verified for runs of 1, 2, 4 and 16 rows.
*
* The `w4a8` form (a two's-complement nibble, -8..7) is served. Remaining (Phase 4): the other
* weight forms (w4nl64a8h / w4nl32a8h / w5nl64a8h, whose nibbles decode through a magnitude table
* and a per-64/32 E4M3 scale), the prefill run map, and the SK/UW/RS optimisations. Not yet a row:
* no r3d_rows.cpp entry, no selftest.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
namespace {
constexpr int kThreads = 256; // eight waves
constexpr int kWaves = kThreads / kWave;
constexpr int kGroup = 128; // a scale block: one k tile, eight wmma steps
constexpr int kPitch = 33; // dwords a staged a row: 33 mod 32 = 1, bank-free
__device__ __forceinline__ int32_t nib_i8(uint32_t nib)
{
return (nib & 8u) ? (int32_t)nib - 16 : (int32_t)(nib & 7u);
}
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_w4a8_kernel(
const int8_t* __restrict__ a, const float* __restrict__ a_scale,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
const uint8_t* __restrict__ w, const float* __restrict__ w_scale,
float* __restrict__ y, int T, int N, int K, int a_ld, int w_ld_b, int y_ld,
int n_expert, int top_k)
{
__shared__ __align__(16) uint32_t s_a[16 * kPitch];
__shared__ int32_t s_tok[16];
__shared__ int32_t s_nruns;
__shared__ int32_t s_rs[16], s_re[16], s_e[16];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t r = lane & 15;
const uint32_t r0 = (uint32_t)blockIdx.y * 16; // the block's sorted rows
const uint32_t ncol = ((uint32_t)blockIdx.x * kWaves + wave) * 16; // the wave's 16 columns
const uint32_t r1 = (r0 + 16 < (uint32_t)T) ? r0 + 16 : (uint32_t)T;
// The block's rows' source tokens, resolved once (the gather). -1 marks a dropped slot.
if (tid < 16) {
const uint32_t i = r0 + tid;
const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1;
s_tok[tid] = (f < 0) ? -1 : (f / top_k);
}
// The runs in [r0, r1): each is a contiguous set of rows for one expert. The block walks them.
if (tid == 0) {
int nruns = 0, i = (int)r0;
while (i < (int)r1) {
int32_t ee = -1;
for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x;
const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1);
s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee;
++nruns; i = re;
}
s_nruns = nruns;
}
group_barrier();
const int nruns = s_nruns;
const uint32_t nc = ncol + r;
const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1);
// One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the
// run does not own are padding (they read the run's first row) and their output is dropped.
for (int run = 0; run < nruns; ++run) {
const int rs = s_rs[run], re = s_re[run], e = s_e[run];
v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
if (e >= 0) {
const uint8_t* wrow = w + (size_t)e * (size_t)N * w_ld_b + (size_t)n_real * w_ld_b;
const float* wsb = w_scale + (size_t)e * (size_t)N * (K / kGroup);
for (int b = 0; b < K / kGroup; ++b) {
const int kt = b * kGroup;
// Stage 16 rows x 128 i8 of the gathered activation; padding rows read the run's first.
for (int i = (int)tid; i < 16 * (kGroup / 4); i += kThreads) {
const int row = i / (kGroup / 4), d = i % (kGroup / 4);
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row]
: s_tok[rs - (int)r0];
const int rr = (src < 0) ? 0 : src;
s_a[(size_t)row * kPitch + d] = *(const uint32_t*)(a + (size_t)rr * a_ld + kt + 4 * d);
}
group_barrier();
const uint32_t* ap = s_a + (size_t)r * kPitch;
v8int sub = v8int{ 0, 0, 0, 0, 0, 0, 0, 0 };
#pragma unroll
for (int k = 0; k < kGroup; k += 16) {
const r3d_u32x4 aq = *(const r3d_u32x4*)(ap + k / 4);
const uint2 wp = *(const uint2*)(wrow + (kt + k) / 2); // 8 bytes = 16 nibbles
int32_t v[16];
#pragma unroll
for (int j = 0; j < 16; ++j) {
const int byt = j / 2;
const bool high = (j & 1);
const uint32_t byte = (byt < 4) ? ((wp.x >> (8 * byt)) & 0xFFu)
: ((wp.y >> (8 * (byt - 4))) & 0xFFu);
v[j] = nib_i8(high ? (byte >> 4) : (byte & 0xFu));
}
v4int bf{ (int)((uint32_t)(v[0] & 0xFF) | (uint32_t)(v[1] & 0xFF) << 8 |
(uint32_t)(v[2] & 0xFF) << 16 | (uint32_t)(v[3] & 0xFF) << 24),
(int)((uint32_t)(v[4] & 0xFF) | (uint32_t)(v[5] & 0xFF) << 8 |
(uint32_t)(v[6] & 0xFF) << 16 | (uint32_t)(v[7] & 0xFF) << 24),
(int)((uint32_t)(v[8] & 0xFF) | (uint32_t)(v[9] & 0xFF) << 8 |
(uint32_t)(v[10] & 0xFF) << 16 | (uint32_t)(v[11] & 0xFF) << 24),
(int)((uint32_t)(v[12] & 0xFF) | (uint32_t)(v[13] & 0xFF) << 8 |
(uint32_t)(v[14] & 0xFF) << 16 | (uint32_t)(v[15] & 0xFF) << 24) };
sub = wmma_i8(v4int{ (int)aq.x, (int)aq.y, (int)aq.z, (int)aq.w }, bf, sub);
}
// Fold the 128-block's scales: scale_a[src][b] * scale_w[e][n][b].
const float sw = wsb[(size_t)n_real * (K / kGroup) + b];
#pragma unroll
for (int g2 = 0; g2 < 8; ++g2) {
const int row = (int)(g2 * 2 + (lane >> 4));
const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row]
: s_tok[rs - (int)r0];
const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * (K / kGroup) + b];
acc[g2] += (float)sub[g2] * sa * sw;
}
group_barrier();
}
}
// Store only the run's rows.
#pragma unroll
for (int g2 = 0; g2 < 8; ++g2) {
const int row = (int)(g2 * 2 + (lane >> 4));
const int m = (int)(r0 + row);
if (rs <= m && m < re && nc < (uint32_t)N) y[(size_t)m * y_ld + nc] = acc[g2];
}
}
}
} // namespace
extern "C" {
int r3d_rad_moe_gemm_w4a8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 7) return R3D_NO(RAD_E_INVAL);
const RadTensor* at = r3d_opt(a, 0), *asc = r3d_opt(a, 1), *st = r3d_opt(a, 2),
*oft = r3d_opt(a, 3), *wt = r3d_opt(a, 4), *wsc = r3d_opt(a, 5),
*yt = r3d_opt(a, 6);
if (!r3d_p(at) || !r3d_p(asc) || !r3d_p(st) || !r3d_p(oft) || !r3d_p(wt) || !r3d_p(wsc) ||
!r3d_wp(yt))
return R3D_NO(RAD_E_INVAL);
const long long ne = r3d_geti_or(a, "n_expert", 0), tk = r3d_geti_or(a, "top_k", 0);
long long M = 0, K = 0, T = 0, N = 0;
if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
if (r3d_rows_of(yt, &T, &N) != 0) return R3D_NO(RAD_E_INVAL);
if (ne <= 0 || tk <= 0 || M <= 0 || N <= 0 || K <= 0 || K % 128) return R3D_NO(RAD_E_SHAPE);
const int a_ld = (int)(at->rank >= 2 ? at->shape[1] : at->stride[0]);
const int w_ld_b = (int)(wt->rank >= 3 ? wt->shape[2] : wt->stride[2]); // bytes/row = K/2
const int y_ld = (int)(yt->rank >= 2 ? yt->shape[1] : yt->stride[0]);
dim3 grid((unsigned)((N + 127) / 128), (unsigned)((T + 15) / 16)), blk(kThreads);
R3D_KLAUNCH(moe_w4a8_kernel, grid, blk, (hipStream_t)s, (const int8_t*)r3d_p(at),
(const float*)r3d_p(asc), (const int32_t*)r3d_p(st), (const int32_t*)r3d_p(oft),
(const uint8_t*)r3d_p(wt), (const float*)r3d_p(wsc), (float*)r3d_wp(yt), (int)T,
(int)N, (int)K, a_ld, w_ld_b, y_ld, (int)ne, (int)tk);
return (int)hipGetLastError();
}
} // extern "C"
+363
View File
@@ -0,0 +1,363 @@
/* r3d_moe_router_topk_bf16.hip -- router_topk: softmax over all n_expert logits, the top_k by
* value, and -- if `norm` -- the kept weights renormalised to sum to one.
*
* One wave per row (one block per row); the selection is top_k passes of a wave minimum, not a
* sort. That matches the reference exactly (largest remaining value, ties to the lower id); a sort
* with another tie rule would be a different router on tied rows, which are not rare. Selection
* runs on the logits: softmax is monotone, so the order is the same and the comparison exact.
*
* gfx1102: a wave reduction (the max, the sum, the per-round min) in a loop body miscompiles for
* a non-first wave -- wave 0 is correct, wave 1+ drop out. Two things keep this safe:
* * one wave per block (one block per row): the __syncthreads is a single-wave barrier, so there
* is no cross-wave sync whose ordering the compiler can scramble;
* * a separate LDS slot per top_k round: the loop never reuses a slot, so a read-after-write
* across iterations cannot be folded (the max and the sum use their own slots, rounds 0 and 1).
* Every wave reduction is an LDS pass, not a DPP butterfly (a DPP exchange miscompiles here).
*
* Verified: single-row (equal, distinct, random) and multi-row (M >= 2) all pick the right ids and
* weights.
*/
#include <hip/hip_runtime.h>
#include <cmath>
#include <cstdint>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_launch.h"
#include "r3d_codecs.h"
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
namespace {
constexpr int kW = 32;
/* (order-preserving value, ~id); 0 = absent or NaN. The key's high half is the logit's bits with
* the sign folded (so larger logit -> larger key) and the low half is the complemented id, so a
* tie goes to the lower id. */
__device__ __forceinline__ uint32_t topk_key(uint16_t raw, uint32_t e, bool ok) {
const bool nan = ((raw & 0x7F80u) == 0x7F80u) && (raw & 0x7Fu);
const uint16_t u = (raw == 0x8000u) ? (uint16_t)0u : raw; // -0.0 folds to +0.0
const uint16_t k = (u & 0x8000u) ? (uint16_t)~u : (uint16_t)(u | 0x8000u);
return nan ? 0u : (((uint32_t)k << 16) | (~e & 0xFFFFu));
}
__device__ __forceinline__ uint16_t topk_key_raw(uint32_t key) {
const uint32_t k = key >> 16;
return (uint16_t)((k & 0x8000u) ? (k & 0x7FFFu) : ~k);
}
/* One row, one wave (the block is a single wave). `wmin` holds 32 slots per round: round 0 the
* max, round 1 the sum, rounds 2..(1+top_k) the per-round minimums. A separate slot per round so
* the loop never reuses one (gfx1102). */
template <int MAXOWN>
__device__ __forceinline__ void r3d_router_topk_row(
const unsigned short* __restrict__ lg, int32_t* __restrict__ ids,
unsigned short* __restrict__ w, uint32_t m, uint32_t n_expert, uint32_t top_k,
uint32_t lg_ld, int norm, uint32_t lane, __shared__ uint32_t* wmin)
{
const unsigned short* row = lg + (size_t)m * lg_ld;
uint16_t raw[MAXOWN];
#pragma unroll
for (int i = 0; i < MAXOWN; ++i) {
const uint32_t e = lane + i * kW;
raw[i] = row[e < n_expert ? e : 0u];
}
float v[MAXOWN];
uint32_t key[MAXOWN];
#pragma unroll
for (int i = 0; i < MAXOWN; ++i) {
const uint32_t e = lane + i * kW;
const bool ok = e < n_expert;
v[i] = ok ? bf16_to_f32(raw[i]) : -INFINITY;
key[i] = topk_key(raw[i], e, ok) & (0u - (uint32_t)ok);
}
float mx = -INFINITY;
#pragma unroll
for (int i = 0; i < MAXOWN; ++i) mx = fmaxf(mx, v[i]);
// Wave max through LDS (round 0).
wmin[lane] = __builtin_bit_cast(uint32_t, mx);
R3D_BARRIER();
#pragma unroll
for (int i = 0; i < kW; ++i)
mx = fmaxf(mx, __builtin_bit_cast(float, wmin[i]));
float sum = 0.0f;
#pragma unroll
for (int i = 0; i < MAXOWN; ++i) sum += __expf(v[i] - mx);
// Wave sum through LDS (round 1).
wmin[kW + lane] = __builtin_bit_cast(uint32_t, sum);
R3D_BARRIER();
float s = 0.0f;
#pragma unroll
for (int i = 0; i < kW; ++i) s += __builtin_bit_cast(float, wmin[kW + i]);
sum = s;
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
uint32_t P = 0xFFFFFFFFu, mykey = 0u, nsel = 0;
for (uint32_t r = 0; r < top_k; ++r) {
uint32_t d = 0xFFFFFFFFu;
#pragma unroll
for (int i = 0; i < MAXOWN; ++i) {
const uint32_t t = P - key[i];
d = d < t ? d : t;
}
// Wave minimum through LDS, round (2 + r): a fresh slot each round.
const uint32_t base = (2 + r) * kW;
wmin[base + lane] = d;
R3D_BARRIER();
uint32_t mn = 0xFFFFFFFFu;
#pragma unroll
for (int i = 0; i < kW; ++i) mn = mn < wmin[base + i] ? mn : wmin[base + i];
const uint32_t best = P - mn;
if ((best & 0xFFFFu) == 0u) break;
if (lane == r) mykey = best;
P = best - 1u;
++nsel;
}
const float p = __expf(bf16_to_f32(topk_key_raw(mykey)) - mx) * inv;
const uint16_t pb = f32_to_bf16(p);
float wsum = 0.0f;
for (uint32_t r = 0; r < nsel; ++r)
wsum += __builtin_bit_cast(float, __builtin_amdgcn_readlane(__builtin_bit_cast(int, p),
(int)r));
if (lane < nsel) {
ids[(size_t)m * top_k + lane] = (int32_t)(~mykey & 0xFFFFu);
w[(size_t)m * top_k + lane] =
(norm && wsum > 0.0f) ? f32_to_bf16(bf16_to_f32(pb) * (1.0f / wsum)) : pb;
}
}
template <int MAXOWN>
__global__ __launch_bounds__(kW) void r3d_router_topk_kernel(
const unsigned short* __restrict__ lg, int32_t* __restrict__ ids,
unsigned short* __restrict__ w, uint32_t M, uint32_t n_expert, uint32_t top_k,
uint32_t lg_ld, int norm)
{
__shared__ uint32_t wmin[kW * (2 + kW)]; // a slot per round, top_k <= kW
const uint32_t lane = threadIdx.x;
const uint32_t m = blockIdx.x; // one block per row
r3d_router_topk_row<MAXOWN>(lg, ids, w, m, n_expert, top_k, lg_ld, norm, lane, wmin);
}
} // namespace
/* ------------------------------------------------------------------ router_sigmoid_topk
*
* The GLM-style router: scores[e] = sigmoid(logit[e]), the selection runs on
* select[e] = scores[e] + bias[e] (a per-expert correction bias), and the kept weights are the
* scores themselves, scaled by route_scale (and renormalised to sum to one if `norm`). Ties go to
* the lower id, as in router_topk.
*
* The selection key is 64-bit (the 32-bit select's monotone bits, the low 32 the complemented id),
* so a 64-bit LDS slot per round. The scores are staged in LDS so the weight is read back without a
* global reload. */
template <int MAXOWN>
__device__ __forceinline__ void r3d_router_sigmoid_topk_row(
const unsigned short* __restrict__ lg, const float* __restrict__ bias,
int32_t* __restrict__ ids, unsigned short* __restrict__ w,
uint32_t m, uint32_t n_expert, uint32_t top_k, uint32_t lg_ld,
float scale, int norm, uint32_t lane,
__shared__ uint64_t* wmin, __shared__ float* s_score)
{
const unsigned short* row = lg + (size_t)m * lg_ld;
uint64_t key[MAXOWN];
#pragma unroll
for (int i = 0; i < MAXOWN; ++i) {
const uint32_t e = lane + i * kW;
const bool ok = e < n_expert;
const float lgt = ok ? bf16_to_f32(row[e]) : -INFINITY;
const float sc = 1.0f / (1.0f + __expf(-lgt));
s_score[lane * MAXOWN + i] = sc;
const float sel = ok ? (sc + bias[e]) : -INFINITY;
const uint32_t bits = __builtin_bit_cast(uint32_t, sel);
const uint32_t u = (bits & 0x80000000u) ? ~bits : (bits | 0x80000000u);
key[i] = (((uint64_t)u) << 32) | (~e & 0xFFFFFFFFull);
}
uint64_t P = ~0ull, mykey = 0ull, nsel = 0;
for (uint32_t r = 0; r < top_k; ++r) {
uint64_t d = ~0ull; // min over (P - key[i]); P - key is smaller for the larger key
#pragma unroll
for (int i = 0; i < MAXOWN; ++i) {
const uint64_t t = P - key[i];
d = d < t ? d : t;
}
const uint64_t base = (uint64_t)(2 + r) * kW;
wmin[base + lane] = d;
R3D_BARRIER();
uint64_t mn = ~0ull;
#pragma unroll
for (int i = 0; i < kW; ++i) mn = mn < wmin[base + i] ? mn : wmin[base + i];
const uint64_t best = P - mn;
if (best == 0ull) break;
if (lane == r) mykey = best;
P = best - 1ull;
++nsel;
}
const uint32_t id = (uint32_t)(~mykey & 0xFFFFFFFFull);
const float sc = s_score[(id % kW) * MAXOWN + (id / kW)];
// Sum the kept scores over lanes 0..nsel-1 (a wave reduce).
wmin[lane] = (uint64_t)__builtin_bit_cast(uint32_t, sc);
R3D_BARRIER();
float sum = 0.0f;
#pragma unroll
for (int i = 0; i < kW; ++i) {
const uint32_t b = (uint32_t)wmin[i];
if (i < nsel) sum += __builtin_bit_cast(float, b);
}
if (lane < nsel) {
const float weight = sc * (norm ? (scale / (sum + 1e-20f)) : scale);
ids[(size_t)m * top_k + lane] = (int32_t)id;
w[(size_t)m * top_k + lane] = f32_to_bf16(weight);
}
}
template <int MAXOWN>
__global__ __launch_bounds__(kW) void r3d_router_sigmoid_topk_kernel(
const unsigned short* __restrict__ lg, const float* __restrict__ bias,
int32_t* __restrict__ ids, unsigned short* __restrict__ w,
uint32_t M, uint32_t n_expert, uint32_t top_k, uint32_t lg_ld, float scale, int norm)
{
__shared__ uint64_t wmin[kW * (2 + kW)];
__shared__ float s_score[kW * MAXOWN];
const uint32_t lane = threadIdx.x;
const uint32_t m = blockIdx.x;
r3d_router_sigmoid_topk_row<MAXOWN>(lg, bias, ids, w, m, n_expert, top_k, lg_ld, scale,
norm, lane, wmin, s_score);
}
extern "C" {
/* moe_scatter's public dispatch, reused by the fused router_topk_scatter. */
int r3d_rad_moe_scatter(const RadArgs*, RadStream);
int r3d_rad_moe_router_topk_bf16(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const long long M = r3d_geti_or(a, "M", 0), ne = r3d_geti_or(a, "n_expert", 0),
tk = r3d_geti_or(a, "top_k", 0);
const long long norm_ll = r3d_geti_or(a, "norm", 0);
const int norm = (int)norm_ll;
if (M <= 0 || ne <= 0 || tk <= 0 || tk > kW) return R3D_NO(RAD_E_SHAPE);
if (ne > (long long)16 * kW) return R3D_NO(RAD_E_SHAPE); // MAXOWN=16 for this row
const RadTensor* L = r3d_opt(a, 0), *I = r3d_opt(a, 1), *W = r3d_opt(a, 2);
if (!r3d_p(L) || !r3d_wp(I) || !r3d_wp(W)) return R3D_NO(RAD_E_INVAL);
if (L->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
const uint32_t lg_ld = (uint32_t)r3d_row_pitch(L);
if (lg_ld < ne) return R3D_NO(RAD_E_SHAPE);
dim3 grid((unsigned)M), blk(kW); // one block (one wave) per row
const unsigned short* lg = (const unsigned short*)r3d_p(L);
int32_t* ip = (int32_t*)r3d_wp(I);
unsigned short* wp = (unsigned short*)r3d_wp(W);
if (ne <= (long long)2 * kW)
R3D_KLAUNCH(r3d_router_topk_kernel<2>, grid, blk, (hipStream_t)s, lg, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm);
else if (ne <= (long long)8 * kW)
R3D_KLAUNCH(r3d_router_topk_kernel<8>, grid, blk, (hipStream_t)s, lg, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm);
else
R3D_KLAUNCH(r3d_router_topk_kernel<16>, grid, blk, (hipStream_t)s, lg, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm);
return (int)hipGetLastError();
}
/* router_topk_scatter: the pair as one op. Phase 1 is the top-k selection over the whole n_expert
* (the router_topk kernel); phase 2 is the counting sort over this rank's slice (n_local), which
* reuses moe_scatter's dispatch. Byte-identical to the two reference launches, in order. */
int r3d_rad_router_topk_scatter(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 6) return R3D_NO(RAD_E_INVAL);
const long long M = r3d_geti_or(a, "M", 0), ne = r3d_geti_or(a, "n_expert", 0),
tk = r3d_geti_or(a, "top_k", 0), nl = r3d_geti_or(a, "n_local", ne);
const int norm = (int)r3d_geti_or(a, "norm", 0);
if (M <= 0 || ne <= 0 || tk <= 0 || tk > (long long)kW || tk > ne) return R3D_NO(RAD_E_SHAPE);
if (nl <= 0 || nl > ne) return R3D_NO(RAD_E_SHAPE);
if (ne > (long long)16 * kW) return R3D_NO(RAD_E_SHAPE);
const RadTensor* L = r3d_opt(a, 0), *I = r3d_opt(a, 1), *W = r3d_opt(a, 2),
*ST = r3d_opt(a, 3), *OFF = r3d_opt(a, 4), *CNT = r3d_opt(a, 5);
if (!r3d_p(L) || !r3d_wp(I) || !r3d_wp(W) || !r3d_wp(ST) || !r3d_wp(OFF) || !r3d_wp(CNT))
return R3D_NO(RAD_E_INVAL);
if (L->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
const uint32_t lg_ld = (uint32_t)r3d_row_pitch(L);
if (lg_ld < ne) return R3D_NO(RAD_E_SHAPE);
// Phase 1: the top-k selection (the router_topk kernel, over the whole n_expert).
dim3 grid((unsigned)M), blk(kW);
const unsigned short* lg = (const unsigned short*)r3d_p(L);
int32_t* ip = (int32_t*)r3d_wp(I);
unsigned short* wp = (unsigned short*)r3d_wp(W);
if (ne <= (long long)2 * kW)
R3D_KLAUNCH(r3d_router_topk_kernel<2>, grid, blk, (hipStream_t)s, lg, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm);
else if (ne <= (long long)8 * kW)
R3D_KLAUNCH(r3d_router_topk_kernel<8>, grid, blk, (hipStream_t)s, lg, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm);
else
R3D_KLAUNCH(r3d_router_topk_kernel<16>, grid, blk, (hipStream_t)s, lg, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm);
if (hipGetLastError() != hipSuccess) return R3D_NO(RAD_E_INVAL);
// Phase 2: the counting sort over this rank's slice (n_local), via moe_scatter's dispatch.
RadTensor t2[4] = { *I, *ST, *OFF, *CNT };
RadParam sp[4] = {
{ "n_expert", RAD_P_INT, (long long)nl, 0, nullptr, 0.0 },
{ "top_k", RAD_P_INT, (long long)tk, 0, nullptr, 0.0 },
{ "expert_base", RAD_P_INT, r3d_geti_or(a, "expert_base", 0), 0, nullptr, 0.0 },
{ "protect", RAD_P_STR, 0, 0, r3d_gets(a, "protect"), 0.0 },
};
RadArgs sa;
std::memset(&sa, 0, sizeof(sa));
sa.t = t2; sa.n_t = 4; sa.p = sp; sa.n_p = 4;
sa.rank = a->rank; sa.world_size = a->world_size;
return r3d_rad_moe_scatter(&sa, s);
}
int r3d_rad_router_sigmoid_topk(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 4) return R3D_NO(RAD_E_INVAL);
const long long M = r3d_geti_or(a, "M", 0), ne = r3d_geti_or(a, "n_expert", 0),
tk = r3d_geti_or(a, "top_k", 0);
const int norm = (int)r3d_geti_or(a, "norm", 0);
const double scale_d = r3d_getf(a, "route_scale", 0.0);
const float scale = (float)scale_d;
if (M <= 0 || ne <= 0 || tk <= 0 || tk > (long long)kW || tk > ne) return R3D_NO(RAD_E_SHAPE);
if (ne > (long long)16 * kW) return R3D_NO(RAD_E_SHAPE);
if (scale <= 0.0f) return R3D_NO(RAD_E_SHAPE);
const RadTensor* L = r3d_opt(a, 0), *B = r3d_opt(a, 1), *I = r3d_opt(a, 2), *W = r3d_opt(a, 3);
if (!r3d_p(L) || !r3d_p(B) || !r3d_wp(I) || !r3d_wp(W)) return R3D_NO(RAD_E_INVAL);
if (L->dtype != RAD_BF16 || B->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE);
const uint32_t lg_ld = (uint32_t)r3d_row_pitch(L);
if (lg_ld < ne) return R3D_NO(RAD_E_SHAPE);
dim3 grid((unsigned)M), blk(kW);
const unsigned short* lg = (const unsigned short*)r3d_p(L);
const float* bp = (const float*)r3d_p(B);
int32_t* ip = (int32_t*)r3d_wp(I);
unsigned short* wp = (unsigned short*)r3d_wp(W);
if (ne <= (long long)2 * kW)
R3D_KLAUNCH(r3d_router_sigmoid_topk_kernel<2>, grid, blk, (hipStream_t)s, lg, bp, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, scale, norm);
else if (ne <= (long long)8 * kW)
R3D_KLAUNCH(r3d_router_sigmoid_topk_kernel<8>, grid, blk, (hipStream_t)s, lg, bp, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, scale, norm);
else
R3D_KLAUNCH(r3d_router_sigmoid_topk_kernel<16>, grid, blk, (hipStream_t)s, lg, bp, ip, wp,
(uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, scale, norm);
return (int)hipGetLastError();
}
} // extern "C"
+256
View File
@@ -0,0 +1,256 @@
/* r3d_moe_scatter.hip -- moe_scatter: the routed slots' stable counting sort.
*
* One workgroup does the whole sort (the "small" form, T <= 1024, which covers every decode and
* verify step): histogram in LDS, offsets an exclusive prefix over n_expert <= 512 counts, and
* each slot placed by its rank inside its expert's run. Stable and byte-identical to the
* reference: a slot's place is its position among the same expert's slots in ascending i.
*
* expert_ids [T] -> sorted_tok [T], expert_offset [n_expert+1], expert_count [n_expert]
*
* `expert_base` is this rank's first expert, subtracted from every routed id so the offsets,
* counts and (downstream) weight table are indexed locally; an id outside the slice is dropped
* (sorted to the tail as -1). `protect` is a comma list of local expert indices placed last.
*
* gfx1102 note: the prefix scan's per-wave inclusive sum goes through LDS, not the DPP row-shift
* butterfly (a DPP exchange inside the scan's tile loop miscompiles here). Each wave writes its
* lane's count to LDS, barriers, and takes the serial prefix of its 32 lanes.
*
* The general (three-pass) form for T > 1024 is not implemented here; the shim declines it.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include <cstdlib>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_launch.h"
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
namespace {
constexpr uint32_t kSortWave = 32;
constexpr uint32_t kMaxExpert = 512;
constexpr uint32_t kMaxProtect = 8;
constexpr uint32_t kScatterSmall = 1024;
constexpr uint32_t kScatWaves = 8; // 256 threads
struct Protect {
uint32_t n;
uint16_t e[kMaxProtect];
};
/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */
__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) {
int32_t below = 0;
for (uint32_t j = 0; j < p.n; ++j) {
if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j);
below += (int32_t)p.e[j] < e;
}
return e - below;
}
template <uint32_t NW>
struct ScatterLds {
static constexpr uint32_t kTiles = (kMaxExpert + NW * kSortWave - 1) / (NW * kSortWave);
int32_t e[kScatterSmall];
int32_t tk[kScatterSmall];
int32_t run[kScatterSmall];
int32_t cnt[kMaxExpert + 1];
int32_t off[kMaxExpert + 1];
int32_t wt[kTiles][NW];
int32_t scan[NW * kSortWave]; // the LDS inclusive-scan scratch (gfx1102: no DPP here)
};
/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has
* written sl.e[0,T) and zeroed sl.cnt[0,n_expert), followed by a barrier. */
template <uint32_t NW, bool INV = false>
__device__ __forceinline__ void scatter_small_place(
int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt,
uint32_t T, uint32_t n_expert, ScatterLds<NW>& sl, int32_t* __restrict__ inv) {
const uint32_t tid = threadIdx.x, lane = tid % kSortWave, wave = tid / kSortWave;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1);
}
R3D_BARRIER();
int32_t carry = 0;
for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kSortWave, ++t) {
const uint32_t e = b + tid;
const int32_t v = (e < n_expert) ? sl.cnt[e] : 0;
// Inclusive wave scan through LDS (a DPP row-shift miscompiles on gfx1102).
sl.scan[wave * kSortWave + lane] = v;
R3D_BARRIER();
int32_t x = 0;
for (int i = 0; i <= (int)lane; ++i) x += sl.scan[wave * kSortWave + i];
if (lane == kSortWave - 1) sl.wt[t][wave] = x;
R3D_BARRIER();
int32_t below = 0, tot = 0;
#pragma unroll
for (uint32_t k = 0; k < NW; ++k) {
const int32_t c = sl.wt[t][k];
below += (k < wave) ? c : 0;
tot += c;
}
if (e < n_expert) {
const int32_t o = carry + below + x - v; // inclusive -> exclusive
sl.off[e] = o;
off[e] = o;
cnt[e] = v;
}
carry += tot;
}
if (tid == 0) off[n_expert] = carry;
R3D_BARRIER();
for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i;
}
R3D_BARRIER();
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e < 0) {
if (INV) inv[i] = -1;
continue;
}
const int32_t o = sl.off[e], n = sl.cnt[e];
int32_t rank = 0;
for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i;
sorted[o + rank] = (int32_t)i;
if (INV) inv[i] = o + rank;
}
}
template <bool INV>
__global__ __launch_bounds__(kScatWaves * kSortWave) void scatter_small_kernel(
const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off,
int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot,
int32_t* __restrict__ inv) {
__shared__ ScatterLds<kScatWaves> sl;
const uint32_t tid = threadIdx.x;
for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = ids[i] - base;
sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1;
}
R3D_BARRIER();
scatter_small_place<kScatWaves, INV>(sorted, off, cnt, T, n_expert, sl, inv);
}
} // namespace
extern "C" {
int r3d_rad_moe_scatter(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 4) return R3D_NO(RAD_E_INVAL);
const RadTensor* ids = r3d_opt(a, 0), *sorted = r3d_opt(a, 1), *off = r3d_opt(a, 2),
*cnt = r3d_opt(a, 3);
if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt))
return R3D_NO(RAD_E_INVAL);
if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 ||
cnt->dtype != RAD_I32)
return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt))
return R3D_NO(RAD_E_STRIDE);
const long long n_expert = r3d_geti_or(a, "n_expert", 0);
if (n_expert <= 0 || n_expert > (long long)kMaxExpert) return R3D_NO(RAD_E_SHAPE);
const long long T = r3d_numel(ids);
if (T <= 0) return R3D_NO(RAD_E_SHAPE);
if (T > (long long)kScatterSmall) return R3D_NO(RAD_E_SHAPE); // the small form only
if (r3d_numel(sorted) < T) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(off) < n_expert + 1 || r3d_numel(cnt) < n_expert) return R3D_NO(RAD_E_SHAPE);
const long long base = r3d_geti_or(a, "expert_base", 0);
if (base < 0) return R3D_NO(RAD_E_SHAPE);
// protect: a comma list of local expert indices, strictly ascending, at most kMaxProtect.
Protect prot{};
if (const char* str = r3d_gets(a, "protect")) {
const char* p = str;
long long prev = -1;
while (*p) {
char* end = nullptr;
const long long v = std::strtoll(p, &end, 10);
if (end == p || v <= prev || v >= n_expert || prot.n >= kMaxProtect)
return R3D_NO(RAD_E_SHAPE);
prot.e[prot.n++] = (uint16_t)v;
prev = v;
p = end;
if (*p == ',') ++p;
else if (*p) return R3D_NO(RAD_E_SHAPE);
}
}
const int32_t* idp = (const int32_t*)r3d_p(ids);
int32_t* sp = (int32_t*)r3d_wp(sorted);
int32_t* op = (int32_t*)r3d_wp(off);
int32_t* cp = (int32_t*)r3d_wp(cnt);
R3D_KLAUNCH(scatter_small_kernel<false>, dim3(1), dim3(kScatWaves * kSortWave), (hipStream_t)s,
idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot,
(int32_t*)nullptr);
return (int)hipGetLastError();
}
/* moe_scatter_inv: the same sort, plus the inverse permutation (each slot's row in sorted_tok). */
int r3d_rad_moe_scatter_inv(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL);
const RadTensor* ids = r3d_opt(a, 0), *sorted = r3d_opt(a, 1), *off = r3d_opt(a, 2),
*cnt = r3d_opt(a, 3), *inv = r3d_opt(a, 4);
if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt) || !r3d_wp(inv))
return R3D_NO(RAD_E_INVAL);
if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 ||
cnt->dtype != RAD_I32 || inv->dtype != RAD_I32)
return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt) ||
!r3d_contig(inv))
return R3D_NO(RAD_E_STRIDE);
const long long n_expert = r3d_geti_or(a, "n_expert", 0);
if (n_expert <= 0 || n_expert > (long long)kMaxExpert) return R3D_NO(RAD_E_SHAPE);
const long long T = r3d_numel(ids);
if (T <= 0) return R3D_NO(RAD_E_SHAPE);
if (T > (long long)kScatterSmall) return R3D_NO(RAD_E_SHAPE); // the small form only
if (r3d_numel(sorted) < T || r3d_numel(inv) < T) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(off) < n_expert + 1 || r3d_numel(cnt) < n_expert) return R3D_NO(RAD_E_SHAPE);
const long long base = r3d_geti_or(a, "expert_base", 0);
if (base < 0) return R3D_NO(RAD_E_SHAPE);
Protect prot{};
if (const char* str = r3d_gets(a, "protect")) {
const char* p = str;
long long prev = -1;
while (*p) {
char* end = nullptr;
const long long v = std::strtoll(p, &end, 10);
if (end == p || v <= prev || v >= n_expert || prot.n >= kMaxProtect)
return R3D_NO(RAD_E_SHAPE);
prot.e[prot.n++] = (uint16_t)v;
prev = v;
p = end;
if (*p == ',') ++p;
else if (*p) return R3D_NO(RAD_E_SHAPE);
}
}
const int32_t* idp = (const int32_t*)r3d_p(ids);
int32_t* sp = (int32_t*)r3d_wp(sorted);
int32_t* op = (int32_t*)r3d_wp(off);
int32_t* cp = (int32_t*)r3d_wp(cnt);
int32_t* ip = (int32_t*)r3d_wp(inv);
R3D_KLAUNCH(scatter_small_kernel<true>, dim3(1), dim3(kScatWaves * kSortWave), (hipStream_t)s,
idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot, ip);
return (int)hipGetLastError();
}
} // extern "C"
+126 -1
View File
@@ -139,10 +139,116 @@ int r3d_rad_quant_act_i8g (const RadArgs* a, RadStream s);
int r3d_rad_gated_quant_fp8 (const RadArgs* a, RadStream s);
int r3d_rad_dequant (const RadArgs* a, RadStream s);
/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */
/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_f16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */
int r3d_rad_gemm_nt_bf16_m16 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_f16_m16 (const RadArgs* a, RadStream s);
/* --- r3d_gemm_w4a16_nt_m64.hip: the 4-bit weight against an f16 activation at M <= 64. The
* codes are read in the container's order; the layout and relayout hooks present the
* (scale, zero) pair as the rad.planes joined operand, the rule's own form. --- */
int r3d_rad_gemm_nt_q_w4a16_m64 (const RadArgs* a, RadStream s);
int r3d_layout_gemm_nt_q_w4a16 (const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* pl, int n, RadLayout* out);
int r3d_relayout_gemm_nt_q_w4a16(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* pl, int n, void* dst,
int64_t dst_bytes);
/* --- r3d_gemm_w5a16_nt_m64.hip: the 5-bit weight (ParoQuant int5) against an f16
* activation at M <= 64: the 4-bit row with the fifth-bit plane. --- */
int r3d_rad_gemm_nt_q_w5a16_m64 (const RadArgs* a, RadStream s);
int r3d_layout_gemm_nt_q_w5a16 (const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* pl, int n, RadLayout* out);
int r3d_relayout_gemm_nt_q_w5a16(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* pl, int n, void* dst,
int64_t dst_bytes);
int r3d_rad_gemm_nt_q_fp8 (const RadArgs* a, RadStream s);
/* --- r3d_gdn_kkt_solve_c64.hip: the gated-delta-net chunk preamble, the gram and the blocked
* inverse of I + the strictly lower decayed gram, one 64-chunk a workgroup. --- */
int r3d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s);
/* --- r3d_gdn_chunk_scan_k128_v128_c64.hip: the gated-delta-net chunked scan, the chunk's
* output and its closing state, the recurrent state in wave-matrix accumulators. --- */
int r3d_rad_gdn_chunk_scan(const RadArgs* a, RadStream s);
/* --- r3d_gdn_gated_rmsnorm_h128.hip: the gated RMS norm a gated-delta-net layer applies to its
* own output, one wave per (token, head) row. */
int r3d_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s);
/* --- r3d_gdn_gated_norm_had_quant_i8.hip: the GDN block's gated RMS norm, block Hadamard and
* per-row int8 quantiser in one pass. */
int r3d_rad_gdn_gated_norm_hq_i8(const RadArgs* a, RadStream s);
/* --- r3d_gdn_conv_w4_h128.hip: the GDN depthwise causal convolution (width 4, silu) and the
* work fused around it: the prefill prep and the decode update. */
int r3d_rad_gdn_conv_prep(const RadArgs* a, RadStream s);
int r3d_rad_gdn_conv_update(const RadArgs* a, RadStream s);
/* --- r3d_gdn_recurrent_update_k128_v128.hip: the gated-delta-net recurrent state update at
* decode, the per-token state step against a paged fp32 state cache. */
int r3d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s);
/* --- r3d_expert_scale_bf16.hip: each routing weight times its expert's own scale, in place. */
int r3d_rad_expert_scale_bf16(const RadArgs* a, RadStream s);
/* --- r3d_moe_router_topk_bf16.hip: softmax over the expert logits, the top_k, renormalised. */
int r3d_rad_moe_router_topk_bf16(const RadArgs* a, RadStream s);
/* --- r3d_moe_scatter.hip: the routed slots' stable counting sort (small form). */
int r3d_rad_moe_scatter(const RadArgs* a, RadStream s);
int r3d_rad_moe_scatter_inv(const RadArgs* a, RadStream s);
/* --- r3d_moe_gather.hip: fold the expert outputs back to the token. */
int r3d_rad_moe_gather(const RadArgs* a, RadStream s);
int r3d_rad_moe_gather_inv(const RadArgs* a, RadStream s);
int r3d_rad_router_topk_scatter(const RadArgs* a, RadStream s);
int r3d_rad_router_sigmoid_topk(const RadArgs* a, RadStream s);
/* --- r3d_moe_gemm_q.hip: the grouped quantised GEMM (E4M3 x E4M3, the per-(row, grid) scale fold). */
int r3d_rad_moe_gemm_q(const RadArgs* a, RadStream s);
int r3d_rad_moe_gemm_q_alu(const RadArgs* a, RadStream s);
int r3d_rad_moe_gemm_bf16(const RadArgs* a, RadStream s);
int r3d_rad_moe_gemm_fp8_f32scale(const RadArgs* a, RadStream s);
int r3d_rad_moe_gemm_mxfp4a8(const RadArgs* a, RadStream s);
/* --- r3d_moe_gemm_w4a8.hip: the grouped GEMM with int4-weights / int8-activation experts. */
int r3d_rad_moe_gemm_w4a8(const RadArgs* a, RadStream s);
/* --- r3d_had_quant_act_i8.hip: a block Hadamard along K, then per-row symmetric int8. */
int r3d_rad_had_quant_act_i8(const RadArgs* a, RadStream s);
/* --- r3d_gelu_mul_quant_i8.hip: gelu(gate) * up, then per-row symmetric int8. */
int r3d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream s);
/* --- r3d_kv_len_trim.hip: per-sequence context lengths less `trim`. */
int r3d_rad_kv_len_trim(const RadArgs* a, RadStream s);
/* --- r3d_qsa_tail_store.hip: the QSA indexer's tail, into a per-layer linear KV state. */
int r3d_rad_qsa_tail_store(const RadArgs* a, RadStream s);
/* --- r3d_gated_had_quant_i8.hip: a gated product, block Hadamard, then per-row int8. */
int r3d_rad_gated_had_quant_i8(const RadArgs* a, RadStream s);
/* --- r3d_had_quant_act_fp8.hip: a 128-wide block Hadamard, then per-group E4M3. */
int r3d_rad_had_quant_act_fp8(const RadArgs* a, RadStream s);
/* --- r3d_gated_had_quant_fp8.hip: a gated product, 128-wide Hadamard, then per-group E4M3. */
int r3d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream s);
/* --- r3d_quant_cols_fp8.hip: E4M3 codes with one scale per column over every row. */
int64_t r3d_quant_cols_fp8_scratch(const RadArgs* a);
int r3d_rad_quant_cols_fp8(const RadArgs* a, RadStream s);
/* --- r3d_had_quant_act_i8g.hip: a 128-wide block Hadamard, then per-group int8 (row-major). */
int r3d_rad_had_quant_act_i8g(const RadArgs* a, RadStream s);
/* --- r3d_gated_had_quant_i8g.hip: a gated product, 128-wide Hadamard, then per-group int8. */
int r3d_rad_gated_had_quant_i8g(const RadArgs* a, RadStream s);
/* --- r3d_rmsnorm_quant_i8.hip: the RMS norm and the per-row int8 quantiser, one pass. */
int r3d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream s);
/* --- r3d_shapes.cpp --- */
int r3d_shape_rmsnorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_layernorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
@@ -163,6 +269,17 @@ int r3d_shape_gather_rows (const RadParam* p, int n_p, int operand, RadOpdDe
int r3d_shape_scatter_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_quant_act_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_quant_act_i8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_had_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gelu_mul_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_kv_len_trim(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_qsa_tail_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gated_had_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_had_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gated_had_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_quant_cols_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_had_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gated_had_quant_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_rmsnorm_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_quant_act_i8g (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gated_quant_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_dequant (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
@@ -230,6 +347,7 @@ int r3d_rad_attn_prefill_h128 (const RadArgs* a, RadStream s);
* carries its own layout hook because the reference's gemm_nt_q hook answers nothing for this
* dtype (ref_layout_gemm_q reads zp_grid, which has no fp8a8 entry). */
int r3d_rad_gemm_nt_q_fp8_tiled (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_fp8_tiled_alu(const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_w2a8_tiled (const RadArgs* a, RadStream s);
extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, RadLayout*);
@@ -240,6 +358,8 @@ extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam*, int, int, const Rad
* E4M3 codes and block scale. */
int r3d_rad_gemm_nt_q_mxfp4a8_m16 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_mxfp4a8_m16_alu (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_mxfp4a8_tiled_alu(const RadArgs* a, RadStream s);
/* --- r3d_gemm_inta8.hip: the symmetric int4 and int8 weight grids at decode heights. The weight
* is signed codes (I4 two per byte, or I8) with a plain f16 scale per (row, 128 of K). No zero
@@ -263,6 +383,7 @@ extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadE
* (r3d_shapes.cpp) transcribes ref_logits_gemm_shape, three plain tensors with nothing joined, so
* the band the engine declares is the band kbench fills. */
int r3d_rad_logits_gemm_bf16 (const RadArgs* a, RadStream s);
int r3d_rad_logits_gemm_bf16_alu (const RadArgs* a, RadStream s);
/* The head's layout hook: `output.weight` at a llama_dense_fp8 checkpoint is E4M3 codes and a bf16
* scale per 128x128 block, stored as two container planes behind the one `lm_head` operand, and the
* mapped tier does not place a weight a loaded library cannot read in place. Transcribed from
@@ -272,6 +393,10 @@ int r3d_rad_logits_gemm_bf16 (const RadArgs* a, RadStream s);
extern "C" int r3d_layout_logits_head(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, RadLayout*);
int r3d_rad_gemm_nt_bf16_tiled (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_bf16_tiled_alu(const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_bf16_tiled_wmma(const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_bf16_m64_wmma (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_w8a8_m64 (const RadArgs* a, RadStream s);
int r3d_shape_logits_gemm_bf16 (const RadParam*, int, int, RadOpdDesc*);
/* --- r3d_model_bf16.hip: the fused MLP activation and the fused norm-quantiser --- */
+93
View File
@@ -0,0 +1,93 @@
/* r3d_qsa_tail_store.hip -- qsa_tail_store: the QSA indexer's tail, raw index keys of tokens that
* have not yet completed a block, into a per-layer linear KV state.
*
* The tail is a per-layer linear KV state owned by the sequence (allocated zeroed, kept for the
* sequence's life), not a plane indexed by the step-local batch row. `state` is one layer's cache,
* [slots, 1, ring, n]; `sidx` names the sequence's slot; position p lands at row p % ring.
*
* The ring is ratio + n_spec, not ratio: the next step restarts at the first rejected position, so
* a step may still owe positions back to p0 - ratio + 1 while writing up to p0 + n_spec. A token's
* sequence comes from cu_seqlens (a linear scan suffices for a handful of sequences). Only the last
* `ring` tokens of a sequence's chunk write: positions p and p + ring share a row, so writing all
* of a prefill chunk would race.
*
* k [T][n] bf16, pos [T] i32, cu [seqs+1] i32, state [slots,1,ring,n] bf16 (inout), sidx [seqs]
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_launch.h"
namespace {
constexpr int kThreads = 256;
__global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel(
const uint16_t* __restrict__ k, const int32_t* __restrict__ pos,
const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx,
uint16_t* __restrict__ state,
int T, int n, int ring, int seqs, int k_ld, int s_slot, int s_row, int sidx_ld) {
const int t = (int)blockIdx.x;
if (t >= T) return;
// This token's sequence, by a linear scan in every thread (cheaper than LDS plus a barrier).
int s = -1;
for (int i = 0; i < seqs; ++i)
if (t >= cu[i] && t < cu[i + 1]) { s = i; break; }
if (s < 0) return;
// Only the last `ring` tokens of this sequence's chunk.
if (t < cu[s + 1] - ring) return;
// Column 0 is the committed slot; -1 marks a sequence with no state.
const int si = sidx[(size_t)s * sidx_ld];
if (si < 0) return;
const int row = pos[t] % ring;
const size_t src = (size_t)t * k_ld;
const size_t dst = (size_t)si * s_slot + (size_t)row * s_row;
for (int d = (int)threadIdx.x; d < n; d += kThreads) state[dst + d] = k[src + d];
}
} // namespace
extern "C" {
int r3d_rad_qsa_tail_store(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL);
const RadTensor* k = r3d_opt(a, 0), *po = r3d_opt(a, 1), *cu = r3d_opt(a, 2),
*st = r3d_opt(a, 3), *sx = r3d_opt(a, 4);
if (!r3d_p(k) || !r3d_p(po) || !r3d_p(cu) || !r3d_wp(st) || !r3d_p(sx))
return R3D_NO(RAD_E_INVAL);
if (k->rank != 2) return R3D_NO(RAD_E_SHAPE);
// The state arrives as the group declared it: [slots, heads, ring, n], heads 1.
if (st->rank != 4 || st->shape[1] != 1) return R3D_NO(RAD_E_SHAPE);
if (st->stride[3] != 1) return R3D_NO(RAD_E_STRIDE);
if (k->dtype != RAD_BF16 || st->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
const long long n = r3d_geti_or(a, "n", 0);
const long long ratio = r3d_geti_or(a, "ratio", 0);
const long long ring = r3d_geti_or(a, "ring", 0);
if (n <= 0 || ratio <= 0 || ring < ratio) return R3D_NO(RAD_E_INVAL);
const long long T = k->shape[0];
if (T < 1 || k->shape[1] != n) return R3D_NO(RAD_E_SHAPE);
if (st->shape[2] < ring || st->shape[3] != n) return R3D_NO(RAD_E_SHAPE);
const long long seqs = r3d_numel(cu) - 1;
if (seqs < 1 || r3d_numel(po) < T) return R3D_NO(RAD_E_SHAPE);
const long long sidx_ld = sx->rank >= 2 ? sx->shape[1] : 1;
if (sidx_ld < 1 || (sx->rank >= 1 && sx->shape[0] < seqs)) return R3D_NO(RAD_E_SHAPE);
const long long kp = k->stride[1] ? k->stride[0] / k->stride[1] : k->shape[1];
if (kp < n) return R3D_NO(RAD_E_STRIDE);
R3D_KLAUNCH(qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), (hipStream_t)s,
(const uint16_t*)r3d_p(k), (const int32_t*)r3d_p(po), (const int32_t*)r3d_p(cu),
(const int32_t*)r3d_p(sx), (uint16_t*)r3d_wp(st), (int)T, (int)n, (int)ring,
(int)seqs, (int)kp, (int)st->stride[0], (int)st->stride[2], (int)sidx_ld);
return (int)hipGetLastError();
}
} // extern "C"
+174
View File
@@ -0,0 +1,174 @@
/* r3d_quant_cols_fp8.hip -- quant_cols_fp8: E4M3 codes with one scale per column over every row.
*
* An attention's V for its fp8 P.V: the formula is quant_act_fp8's (scale amax / 448, 1 for an
* all-zero column, codes of x / scale clamped to +-448) with the group running down a column. A
* column's scale needs every row, so two passes over the rows, split into kColChunks chunks:
* 1. column amax partials, a workgroup a block of columns and a chunk of rows, the bf16
* magnitudes compared as integers (their order is the values');
* 2. a workgroup the same block and chunk: the scales from the chunks' partials, then the codes,
* the chunk's rows walked from its end (the first pass read them last, the cache still holds
* them).
*
* A thread owns eight columns: one 16-byte load and one 8-byte store a row. RDNA3 has no fp8
* hardware, so the codes use the software E4M3 codec (r3d_codecs.h), not the cvt_pk_fp8 builtin.
*
* Scratch: kColChunks * n floats (the column amax partials).
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
namespace {
constexpr int kColChunks = 32;
constexpr int kColThreads = 128;
constexpr float kTopE4M3 = 448.0f;
// The two bf16 in a 32-bit word, sign masked off: the magnitude, ordered as the values.
__device__ __forceinline__ uint32_t col_mag(uint32_t w) { return w & 0x7fff7fffu; }
__device__ __forceinline__ float bf16w_lo(uint32_t w) { return bf16_to_f32((uint16_t)(w & 0xffffu)); }
__device__ __forceinline__ float bf16w_hi(uint32_t w) { return bf16_to_f32((uint16_t)(w >> 16)); }
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
// Two E4M3 codes packed into a 16-bit value, the software codec (RDNA3 has no fp8 builtin).
__device__ __forceinline__ uint16_t col_code2(float a, float b, float ia, float ib) {
const uint8_t lo = f32_to_e4m3(clamp_top(a * ia, kTopE4M3));
const uint8_t hi = f32_to_e4m3(clamp_top(b * ib, kTopE4M3));
return (uint16_t)(lo | (hi << 8));
}
__global__ __launch_bounds__(kColThreads) void quant_cols_amax_kernel(
const uint16_t* __restrict__ x, int M, int n, int x_ld, float* __restrict__ part) {
const int c8 = blockIdx.x * kColThreads + threadIdx.x;
if (c8 * 8 >= n) return;
const int r0 = (int)((long)M * blockIdx.y / kColChunks);
const int r1 = (int)((long)M * (blockIdx.y + 1) / kColChunks);
const uint16_t* p = x + (long)c8 * 8;
uint32_t m[4] = { 0, 0, 0, 0 };
int r = r0;
for (; r + 8 <= r1; r += 8) {
uint4 u[8];
#pragma unroll
for (int k = 0; k < 8; ++k) u[k] = *(const uint4*)(p + (long)(r + k) * x_ld);
#pragma unroll
for (int k = 0; k < 8; ++k) {
m[0] = max(m[0], col_mag(u[k].x));
m[1] = max(m[1], col_mag(u[k].y));
m[2] = max(m[2], col_mag(u[k].z));
m[3] = max(m[3], col_mag(u[k].w));
}
}
for (; r < r1; ++r) {
const uint4 u = *(const uint4*)(p + (long)r * x_ld);
m[0] = max(m[0], col_mag(u.x));
m[1] = max(m[1], col_mag(u.y));
m[2] = max(m[2], col_mag(u.z));
m[3] = max(m[3], col_mag(u.w));
}
float* d = part + (long)blockIdx.y * n + c8 * 8;
*(float4*)d = make_float4(bf16w_lo(m[0]), bf16w_hi(m[0]), bf16w_lo(m[1]), bf16w_hi(m[1]));
*(float4*)(d + 4) = make_float4(bf16w_lo(m[2]), bf16w_hi(m[2]), bf16w_lo(m[3]), bf16w_hi(m[3]));
}
__global__ __launch_bounds__(kColThreads) void quant_cols_code_kernel(
const uint16_t* __restrict__ x, int M, int n, int x_ld, const float* __restrict__ part,
uint8_t* __restrict__ y, int y_ld, float* __restrict__ scale) {
const int c8 = blockIdx.x * kColThreads + threadIdx.x;
if (c8 * 8 >= n) return;
float am[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
for (int ch = 0; ch < kColChunks; ++ch) {
const float4 a = *(const float4*)(part + (long)ch * n + c8 * 8);
const float4 b = *(const float4*)(part + (long)ch * n + c8 * 8 + 4);
am[0] = fmaxf(am[0], a.x); am[1] = fmaxf(am[1], a.y);
am[2] = fmaxf(am[2], a.z); am[3] = fmaxf(am[3], a.w);
am[4] = fmaxf(am[4], b.x); am[5] = fmaxf(am[5], b.y);
am[6] = fmaxf(am[6], b.z); am[7] = fmaxf(am[7], b.w);
}
float sc[8], inv[8];
#pragma unroll
for (int e = 0; e < 8; ++e) {
sc[e] = am[e] > 0.0f ? am[e] * (1.0f / kTopE4M3) : 1.0f;
inv[e] = 1.0f / sc[e];
}
if (blockIdx.y == 0) {
*(float4*)(scale + c8 * 8) = make_float4(sc[0], sc[1], sc[2], sc[3]);
*(float4*)(scale + c8 * 8 + 4) = make_float4(sc[4], sc[5], sc[6], sc[7]);
}
const int r0 = (int)((long)M * blockIdx.y / kColChunks);
const int r1 = (int)((long)M * (blockIdx.y + 1) / kColChunks);
const uint16_t* p = x + (long)c8 * 8;
uint8_t* q = y + (long)c8 * 8;
auto code = [&](uint4 u) -> uint2 {
uint32_t lo = col_code2(bf16w_lo(u.x), bf16w_hi(u.x), inv[0], inv[1]);
lo |= (uint32_t)col_code2(bf16w_lo(u.y), bf16w_hi(u.y), inv[2], inv[3]) << 16;
uint32_t hi = col_code2(bf16w_lo(u.z), bf16w_hi(u.z), inv[4], inv[5]);
hi |= (uint32_t)col_code2(bf16w_lo(u.w), bf16w_hi(u.w), inv[6], inv[7]) << 16;
return make_uint2(lo, hi);
};
int r = r1;
for (; r - 8 >= r0; r -= 8) {
uint4 u[8];
#pragma unroll
for (int k = 0; k < 8; ++k) u[k] = *(const uint4*)(p + (long)(r - 1 - k) * x_ld);
#pragma unroll
for (int k = 0; k < 8; ++k) *(uint2*)(q + (long)(r - 1 - k) * y_ld) = code(u[k]);
}
for (; r > r0; --r)
*(uint2*)(q + (long)(r - 1) * y_ld) = code(*(const uint4*)(p + (long)(r - 1) * x_ld));
}
} // namespace
extern "C" {
int64_t r3d_quant_cols_fp8_scratch(const RadArgs* a)
{
const long long n = r3d_geti_or(a, "n", 0);
if (n <= 0) return 0;
return (int64_t)kColChunks * n * (int64_t)sizeof(float);
}
int r3d_rad_quant_cols_fp8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, 0), *y = r3d_opt(a, 1), *sc = r3d_opt(a, 2);
if (!r3d_p(x) || !r3d_wp(y) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || y->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
const long long n = r3d_geti_or(a, "n", 0);
if (n <= 0 || n % 8) return R3D_NO(RAD_E_SHAPE);
/* The rows are the leading axes, whatever their rank; the pitches are the leading strides.
* All three are cast to int for the launch, so bound them. */
if (n > (1LL << 30)) return R3D_NO(RAD_E_SHAPE);
const long long x_ld = r3d_row_pitch(x);
const long long y_ld = r3d_row_pitch(y);
if (x_ld < n || y_ld < n || (x_ld & 7) || (y_ld & 7)) return R3D_NO(RAD_E_SHAPE);
const long long xnel = r3d_numel(x);
if (xnel % n) return R3D_NO(RAD_E_SHAPE);
const long long M = xnel / n;
if (M < 1 || M > (1LL << 30)) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(y) < M * n || r3d_numel(sc) < n) return R3D_NO(RAD_E_SHAPE);
const int64_t need = (int64_t)kColChunks * n * sizeof(float);
if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH);
float* part = (float*)a->scratch;
const dim3 grid((unsigned)((n / 8 + kColThreads - 1) / kColThreads), (unsigned)kColChunks);
const dim3 blk(kColThreads);
R3D_KLAUNCH(quant_cols_amax_kernel, grid, blk, (hipStream_t)s, (const uint16_t*)r3d_p(x),
(int)M, (int)n, (int)x_ld, part);
R3D_KLAUNCH(quant_cols_code_kernel, grid, blk, (hipStream_t)s, (const uint16_t*)r3d_p(x),
(int)M, (int)n, (int)x_ld, part, (uint8_t*)r3d_wp(y), (int)y_ld,
(float*)r3d_wp(sc));
return (int)hipGetLastError();
}
} // extern "C"
+208
View File
@@ -0,0 +1,208 @@
/* r3d_rmsnorm_quant_i8.hip -- rmsnorm_quant_i8: the RMS norm and the per-row int8 quantiser, in
* one pass over the row, optionally with the residual junction in front of it: a post-norm on the
* branch output, the residual add and a scalar on the sum.
*
* A w4a8 linear needs its activation as int8 codes in the GEMM's fragment order with one f32 scale
* per row, produced by a norm. Unfused that is two dispatches, and a sandwich-norm model issues
* four or five at every residual junction:
*
* rmsnorm(branch; w_post) -> add(residual) -> [scale] -> rmsnorm(residual; w) -> quant
*
* This is the chain as one dispatch. Byte-identical to the chain, because every intermediate the
* chain stores in bf16 is rounded to bf16 here and the next stage reads the rounded value: the
* post-norm output, the residual sum, the scaled residual and the norm output the quantiser
* reduces over. Both sums of squares use the standalone norm's partition (thread t folding columns
* t, t+THR, ... in order, then the wave sum and the waves in order through LDS).
*
* The codes are in the w4a8 GEMM's fragment order: byte j of a k step comes from source
* 8*((j&7)>>2) + 4*(j>>3) + (j&3) inside the step.
*
* THR is fixed at 256 (the re-read form): one workgroup a row, the row re-read in each pass. The
* register form (decode heights) and the fused all-reduce forms are not served here.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <cstdint>
#define R3D_BARRIER() __syncthreads(); asm volatile("" ::: "memory");
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr float kTopI8 = 127.0f;
constexpr float kFloor = 1e-8f;
__device__ __forceinline__ float bf2f(uint16_t h) { return bf16_to_f32(h); }
template <bool WF32>
__device__ __forceinline__ float gain(const void* w, uint32_t i) {
return WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]);
}
__device__ __forceinline__ float scalar_of(const void* sc, uint32_t f32) {
return f32 ? ((const float*)sc)[0] : bf16_to_f32(((const uint16_t*)sc)[0]);
}
// The row body from the junction on: `s1` is the post-norm's factor, already reduced over `xr`.
template <bool WF32, bool RES, bool POST, bool SCL>
__device__ __forceinline__ void junction_row(
const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w,
const void* __restrict__ wp, float sv, signed char* __restrict__ qr, float* __restrict__ Sr,
uint16_t* __restrict__ yr, uint32_t n, float eps, float wadd, float s1, uint16_t* ybuf,
float* l2, float* lm) {
// ---- the junction (post-norm, add, scalar), stored, and the norm's sum of squares over it
float ss2 = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
uint16_t v = xr[i];
if (RES) {
if (POST) v = f32_to_bf16(bf2f(v) * s1 * (gain<WF32>(wp, i) + wadd));
v = f32_to_bf16(bf2f(rr[i]) + bf2f(v));
if (SCL) v = f32_to_bf16(bf2f(v) * sv);
rr[i] = v;
}
const float f = bf2f(v);
ss2 += f * f;
}
ss2 = block_sum<kThreads>(ss2, l2);
const float s2 = rsqrtf(ss2 / (float)n + eps);
// ---- the norm output, rounded to bf16 as the standalone norm stores it, and its absmax
const uint16_t* __restrict__ nr = RES ? rr : xr;
float m = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const uint16_t y = f32_to_bf16(bf2f(nr[i]) * s2 * (gain<WF32>(w, i) + wadd));
ybuf[i] = y;
if (yr) yr[i] = y;
m = fmaxf(m, fabsf(bf2f(y)));
}
m = wave_max(m);
if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m;
R3D_BARRIER(); // also publishes ybuf to every thread
m = lm[0];
#pragma unroll
for (uint32_t i = 1; i < kWaves; ++i) m = fmaxf(m, lm[i]);
const float scale = fmaxf(m, kFloor) / kTopI8;
const float inv = 1.0f / scale;
if (threadIdx.x == 0) *Sr = scale;
// ---- the codes, in the w4a8 GEMM's fragment order
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const uint32_t s = i >> 4, j = i & 15;
const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
const int t = (int)lrintf(bf2f(ybuf[src]) * inv);
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
}
template <bool WF32, bool RES, bool POST, bool SCL>
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void rmsnorm_quant_i8_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, uint32_t n,
float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) {
extern __shared__ uint16_t ybuf[];
__shared__ float l1[kWaves], l2[kWaves], lm[kWaves];
const uint32_t row = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
// ---- the post-norm's sum of squares, over the branch output
float s1 = 0.0f;
if (POST) {
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const float v = bf2f(xr[i]);
ss += v * v;
}
ss = block_sum<kThreads>(ss, l1);
s1 = rsqrtf(ss / (float)n + eps);
}
junction_row<WF32, RES, POST, SCL>(
xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, SCL ? scalar_of(sc, sc_f32) : 1.0f,
q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1,
ybuf, l2, lm);
}
} // namespace
extern "C" {
int r3d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL);
const RadTensor* x = r3d_opt(a, 0), *rs = r3d_opt(a, 1), *w = r3d_opt(a, 2), *q = r3d_opt(a, 3),
*sc = r3d_opt(a, 4), *y = r3d_opt(a, 5), *wp = r3d_opt(a, 6),
*sv = r3d_opt(a, 7);
if (!r3d_p(x) || !r3d_p(w) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL);
if ((wp || sv) && !rs) return R3D_NO(RAD_E_INVAL); // a junction without a stream to add into
if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32)
return R3D_NO(RAD_E_DTYPE);
long long M = 0, n = 0;
if (r3d_rows_of(x, &M, &n) != 0) return R3D_NO(RAD_E_INVAL);
if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(w) != n) return R3D_NO(RAD_E_SHAPE);
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
if (wp && (r3d_numel(wp) != n || wp->dtype != w->dtype)) return R3D_NO(RAD_E_SHAPE);
if (sv && (r3d_numel(sv) != 1 || (sv->dtype != RAD_F32 && sv->dtype != RAD_BF16)))
return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(q) < M * n || r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE);
if (y && r3d_numel(y) < M * n) return R3D_NO(RAD_E_SHAPE);
if (rs && r3d_numel(rs) < M * n) return R3D_NO(RAD_E_SHAPE);
const long long x_ld_ = r3d_row_pitch(x);
if (x_ld_ < 0) return R3D_NO(RAD_E_STRIDE);
const uint32_t x_ld = (uint32_t)x_ld_;
uint32_t r_ld = (uint32_t)n;
if (rs) {
const long long rl = r3d_row_pitch(rs);
if (rl < n) return R3D_NO(RAD_E_STRIDE);
r_ld = (uint32_t)rl;
}
uint32_t y_ld = (uint32_t)n;
if (y) {
const long long yl = r3d_row_pitch(y);
if (yl < n) return R3D_NO(RAD_E_STRIDE);
y_ld = (uint32_t)yl;
}
const size_t lds = (size_t)n * sizeof(uint16_t);
if (lds > 60 * 1024) return R3D_NO(RAD_E_SHAPE);
const float eps = (float)r3d_getf(a, "eps", 1e-6);
const float wadd = (float)r3d_getf(a, "wadd", 0.0);
const uint32_t scf = sv ? (sv->dtype == RAD_F32) : 0u;
const bool WF = w->dtype == RAD_F32, RS = rs != nullptr, PO = wp != nullptr, SC = sv != nullptr;
dim3 grid((unsigned)M), blk(kThreads);
const uint16_t* xp = (const uint16_t*)r3d_p(x);
uint16_t* rwp = rs ? (uint16_t*)r3d_wp(rs) : nullptr;
const void* wv = r3d_p(w);
const void* wpp = r3d_p(wp);
const void* svp = r3d_p(sv);
signed char* qp = (signed char*)r3d_wp(q);
float* sp = (float*)r3d_wp(sc);
uint16_t* yp = y ? (uint16_t*)r3d_wp(y) : nullptr;
#define RQ8(WF_, RS_, PO_, SC_) \
R3D_KLAUNCH_S(R3D_KNAME(rmsnorm_quant_i8_kernel<WF_, RS_, PO_, SC_>), grid, blk, lds, \
(hipStream_t)s, xp, rwp, wv, wpp, svp, scf, qp, sp, yp, (uint32_t)n, eps, wadd,\
x_ld, r_ld, y_ld)
if (WF) {
if (!RS) RQ8(true, false, false, false);
else if (!PO && !SC) RQ8(true, true, false, false);
else if (PO && !SC) RQ8(true, true, true, false);
else if (PO && SC) RQ8(true, true, true, true);
else RQ8(true, true, false, true);
} else {
if (!RS) RQ8(false, false, false, false);
else if (!PO && !SC) RQ8(false, true, false, false);
else if (PO && !SC) RQ8(false, true, true, false);
else if (PO && SC) RQ8(false, true, true, true);
else RQ8(false, true, false, true);
}
#undef RQ8
return (int)hipGetLastError();
}
} // extern "C"
+1009 -24
View File
File diff suppressed because it is too large. Load diff
+5 -2
View File
@@ -597,7 +597,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel(
if (x0 != x0) { /* topk_next's seed, as in row_topk */
for (uint32_t r = 0; r < n_cand; ++r) {
if (r >= k) { hole(r); continue; }
ir[r] = vocab_off;
ir[r] = 0; /* cand_idx is local: the NaN logit's column */
vr[r] = x0;
if (pp) { pp[2 * r] = vocab_off; pp[2 * r + 1] = *(const int32_t*)&x0; }
}
@@ -788,8 +788,11 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel(
if (s_ev[i] * inv >= th) { cnt += 1.0f; last = (float)i; }
}
/* Count and last index are order-free (a sum of small integers and a max), so no serial
* loop is needed; candidates are re-tested below from the same `s_ev`. */
* loop is needed; candidates are re-tested below from the same `s_ev`. The two
* reductions share the `red` scratch: block_sum ends on a read of it and block_max
* begins on a write, so the barrier between them is the read/write fence. */
const float n_above = block_sum<kThreads>(cnt, red);
__syncthreads();
const float hi = block_max(last, red);
if (n_above < 2.0f) return; /* needs two to exclude all but the least likely */
const int32_t keep = (int32_t)hi;
+1328 -2
View File
File diff suppressed because it is too large. Load diff
+108
View File
@@ -346,6 +346,114 @@ int r3d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc*
}
/* The per-group int8 the i8a8 GEMM reads: the fp8 quantiser's extents with int8 codes. */
/* The Hadamard-rotated int8: the same three planes as quant_act_i8 (x, q, scale), no row sums. */
int r3d_shape_had_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, 1) };
R3D_PICK(list);
}
/* The GELU-gated product quantiser: gate_up [M, 2n], q [M, n] i8, scale [M], out_bf16 [M, n]. */
int r3d_shape_gelu_mul_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, 2 * n), opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, 1), opd(D, M, n) };
R3D_PICK(list);
}
/* The prefill-overlap length trim: seqused [max_seqs], tail [trim] (extent carries the count),
* out [max_seqs]. */
int r3d_shape_kv_len_trim(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t n = gi(p, n_p, "max_seqs", 0), trim = gi(p, n_p, "trim", 0);
const RadOpdDesc list[] = { opd((uint32_t)RAD_I32, n, 1), opd((uint32_t)RAD_I32, trim, 1),
opd((uint32_t)RAD_I32, n, 1) };
R3D_PICK(list);
}
/* The QSA tail: k [M, n], pos [M], cu [seqs+1], state [seqs, 1, ring, n] (inout), sidx [seqs]. */
int r3d_shape_qsa_tail_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ring = gi(p, n_p, "ring", 0), seqs = gi(p, n_p, "seqs", 0);
const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, n), opd((uint32_t)RAD_I32, M, 1),
opd((uint32_t)RAD_I32, seqs + 1, 1),
opd((uint32_t)RAD_BF16, seqs, 1, ring, n),
opd((uint32_t)RAD_I32, seqs, 1) };
R3D_PICK(list);
}
/* The gated Hadamard int8: a [M, n], b [M, n] (optional, fused gate_up when absent), q [M, n] i8,
* scale [M]. */
int r3d_shape_gated_had_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, 1) };
R3D_PICK(list);
}
/* The rotated fp8: x [M, n], q [M, n] E4M3, scale [M, n/group]. */
int r3d_shape_had_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
const RadOpdDesc list[] = { opd(D, M, n), opd((uint32_t)RAD_F8E4M3, M, n),
opd((uint32_t)RAD_F32, M, ng) };
R3D_PICK(list);
}
/* The gated rotated fp8: gate_up [M, 2n], q [M, n] E4M3, scale [M, n/group], out_bf16 [M, n]. */
int r3d_shape_gated_had_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
const RadOpdDesc list[] = { opd(D, M, 2 * n), opd((uint32_t)RAD_F8E4M3, M, n),
opd((uint32_t)RAD_F32, M, ng), opd(D, M, n) };
R3D_PICK(list);
}
/* The column fp8: x [M, n], y [M, n] E4M3, scale [n] (one per column). */
int r3d_shape_quant_cols_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd((uint32_t)RAD_F8E4M3, M, n),
opd((uint32_t)RAD_F32, n, 1) };
R3D_PICK(list);
}
/* The rotated grouped int8: x [M, n], q [M, n] i8 (row-major), scale [M, n/group]. */
int r3d_shape_had_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
const RadOpdDesc list[] = { opd(D, M, n), opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, ng) };
R3D_PICK(list);
}
/* The gated rotated grouped int8: gate_up [M, 2n], q [M, n] i8 (row-major), scale [M, n/group]. */
int r3d_shape_gated_had_quant_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
const RadOpdDesc list[] = { opd(D, M, 2 * n), opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, ng), opd(D, M, n) };
R3D_PICK(list);
}
/* The RMS norm + per-row int8: x [M, n], residual [M, n] (optional), w [n], q [M, n] i8,
* scale [M], out_bf16 [M, n] (optional), w_post [n] (optional), scalar [1] (optional). */
int r3d_shape_rmsnorm_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd(D, n, 1), opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, 1), opd(D, M, n), opd(D, n, 1),
opd(D, 1, 1) };
R3D_PICK(list);
}
int r3d_shape_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
+57 -28
View File
@@ -205,14 +205,15 @@ __device__ __forceinline__ uint32_t cvt_pk_f16_fp8(uint32_t b)
#endif
}
template <int ALU> /* ALU=1: the per-byte ALU decode (no table); ALU=0: the LDS table */
__device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const uint16_t* tbl,
uint32_t* w)
uint32_t* w)
{
const uint32_t d[2] = { c.x, c.y };
if (tbl && !cdt) {
/* The LDS table: eight reads for eight codes, built from the codec below, so the results
* are identical (r3d_fp8_dequant.h). A null tbl selects the codec. */
r3d_e4m3x8_ld(tbl, c, w);
if (!cdt && (ALU || tbl)) {
/* The shared E4M3 decode: ALU=1 the per-byte formula, ALU=0 the LDS table
* (r3d_fp8_dequant.h). A null tbl with ALU=0 selects the codec below. */
r3d_e4m3x8_decode<ALU>(tbl, c, w);
return;
}
if (!cdt) {
@@ -302,7 +303,7 @@ __device__ __forceinline__ uint2 loadc8(const uint8_t* p)
*
* y is f32 for logits_gemm and bf16 for gemm_nt (`YF32`). WQ reads the quantised head through h.
*/
template <bool YF32, bool WQ>
template <bool YF32, bool WQ, int ALU>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, HeadQ h,
void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld)
@@ -314,7 +315,7 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
const int tid = (int)threadIdx.x;
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; /* the E4M3 decoder, 512 bytes */
if (WQ) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* fills, then barriers */
const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr;
const uint16_t* const r3d_tbl = (WQ && !ALU) ? sTbl : (const uint16_t*)nullptr;
const int m0 = (int)blockIdx.y * kTM;
const int n0 = (int)blockIdx.x * kTN;
const int rg = tid >> 4, cg = tid & 15; /* this lane's 8x8 square */
@@ -349,7 +350,7 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
* the scale is indexed by this staged row n, not the lane's output row. */
const uint2 c = *(const uint2*)(h.codes + (long long)n * h.code_row + k);
uint32_t w[4];
codes8_to_f16x4(c, h.cdt, r3d_tbl, w);
codes8_to_f16x4<ALU>(c, h.cdt, r3d_tbl, w);
const float sc = scale_at(h, n, k);
staged = make_uint4(scale_pair(w[0], sc), scale_pair(w[1], sc),
scale_pair(w[2], sc), scale_pair(w[3], sc));
@@ -421,7 +422,7 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b
* ascending order. The activation tile is block-wide, so every thread stages it, including lanes
* whose weight row is past the vocabulary; those lanes skip the dot and the store.
*/
template <int MT, bool YF32, int NT, bool WQ>
template <int MT, bool YF32, int NT, bool WQ, int ALU>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(4)
logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, HeadQ h,
void* __restrict__ y, int M, int N, int K, int x_ld, int y_ld)
@@ -431,8 +432,8 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_
__shared__ __align__(16) uint16_t sX[MT * kChunkK]; /* f16, MT rows x chunk, swizzled */
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
if (WQ) r3d_e4m3_f16_init(sTbl, (int)threadIdx.x, kBlockThreads);
const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr;
if (WQ && !ALU) r3d_e4m3_f16_init(sTbl, (int)threadIdx.x, kBlockThreads);
const uint16_t* const r3d_tbl = (WQ && !ALU) ? sTbl : (const uint16_t*)nullptr;
const int lane = (int)threadIdx.x & (kWave - 1);
const int warp = (int)threadIdx.x / kWave;
@@ -467,7 +468,7 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_
uint32_t w0, w1, w2, w3;
if (WQ) {
uint32_t q[4];
codes8_to_f16x4(loadc8<NT>(cp + kc), h.cdt, r3d_tbl, q);
codes8_to_f16x4<ALU>(loadc8<NT>(cp + kc), h.cdt, r3d_tbl, q);
w0 = scale_pair(q[0], sc); w1 = scale_pair(q[1], sc);
w2 = scale_pair(q[2], sc); w3 = scale_pair(q[3], sc);
} else {
@@ -498,7 +499,7 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_
*/
template <bool YF32>
int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ld, int sk, int kb,
int nt, long stream, const HeadQ* hq = nullptr)
int nt, long stream, const HeadQ* hq = nullptr, int alu = 1)
{
if (!xv || !wv || !yv) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
@@ -538,18 +539,22 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_
}
if (M <= kSkinnyMax) {
#define R3D_SKINNY(MTV, NTV, WQV) \
#define R3D_SKINNY(MTV, NTV, WQV, ALUV) \
do { \
const int klw = kWave / (MTV); \
const int per = kWaves * klw; \
const dim3 grid((unsigned)((N + per - 1) / per)), block(kBlockThreads); \
R3D_KLAUNCH(R3D_KNAME((logits_skinny_kernel<MTV, YF32, NTV, WQV>)), grid, block, s, x, w, \
R3D_KLAUNCH(R3D_KNAME((logits_skinny_kernel<MTV, YF32, NTV, WQV, ALUV>)), grid, block, s, x, w, \
h, y, M, N, K, x_ld, y_ld); \
} while (0)
#define R3D_SKINNY_MT(MTV) \
do { \
if (wq) { if (nt) R3D_SKINNY(MTV, 1, 1); else R3D_SKINNY(MTV, 0, 1); } \
else { if (nt) R3D_SKINNY(MTV, 1, 0); else R3D_SKINNY(MTV, 0, 0); } \
if (wq) { \
if (alu) { if (nt) R3D_SKINNY(MTV, 1, 1, 1); else R3D_SKINNY(MTV, 0, 1, 1); } \
else { if (nt) R3D_SKINNY(MTV, 1, 1, 0); else R3D_SKINNY(MTV, 0, 1, 0); } \
} else { \
if (nt) R3D_SKINNY(MTV, 1, 0, 0); else R3D_SKINNY(MTV, 0, 0, 0); \
} \
} while (0)
if (M == 1) R3D_SKINNY_MT(1);
else if (M <= 2) R3D_SKINNY_MT(2);
@@ -561,11 +566,15 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_
} else {
const dim3 grid((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM));
const dim3 block(kBlockThreads);
if (wq)
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, true>)), grid, block, s, x, w, h, y, M,
N, K, x_ld, y_ld);
else
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, false>)), grid, block, s, x, w, h, y, M,
if (wq) {
if (alu)
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, true, 1>)), grid, block, s, x, w, h, y, M,
N, K, x_ld, y_ld);
else
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, true, 0>)), grid, block, s, x, w, h, y, M,
N, K, x_ld, y_ld);
} else
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, false, 0>)), grid, block, s, x, w, h, y, M,
N, K, x_ld, y_ld);
}
return hipGetLastError() == hipSuccess ? 0 : -4;
@@ -574,7 +583,7 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_
/* The shim body both ops share (ref_logits_gemm is gemm_nt_impl with the axes renamed).
* `y_is_f32` is the op's output dtype; nkey/kkey are libref's axis names ("n_vocab"/"n_embd" or
* "N"/"K"). */
int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const char* kkey)
int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const char* kkey, int alu)
{
if (a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data)
return R3D_NO(RAD_E_INVAL);
@@ -663,9 +672,9 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey,
const HeadQ* hp = joined ? &h : nullptr;
const int e = y_is_f32
? gemm_launch<true>(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K,
(int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp)
(int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp, alu)
: gemm_launch<false>(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K,
(int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp);
(int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp, alu);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
: e == -3 ? RAD_E_STRIDE : e == -5 ? RAD_E_ALIGN : RAD_E_DEVICE);
@@ -714,15 +723,35 @@ extern "C" int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int
return gemm_launch<false>(a, b, y, M, N, K, a_ld, y_ld, sk, kb, nt, stream);
}
static int r3d_logits_gemm_bf16_dispatch(const RadArgs* a, RadStream s, int alu)
{ return rad_gemm_run(a, s, 1, "n_vocab", "n_embd", alu); }
static int r3d_gemm_nt_bf16_tiled_dispatch(const RadArgs* a, RadStream s, int alu)
{ return rad_gemm_run(a, s, 0, "N", "K", alu); }
extern "C" int r3d_rad_gemm_nt_bf16_tiled_wmma(const RadArgs*, RadStream);
extern "C" int r3d_rad_gemm_nt_bf16_m64_wmma(const RadArgs*, RadStream);
/* The rows' impl axis picks the kernel: the table decode (0) and the ALU decode (1) share the
* dispatch, and the bf16 tiled row's two wave-matrix arms (2 = the 128x128 tile, 3 = the
* 16-column-tile kernel) run through their own shims, which stay as entry points. */
extern "C" int r3d_rad_logits_gemm_bf16(const RadArgs* a, RadStream s)
{
return rad_gemm_run(a, s, 1, "n_vocab", "n_embd");
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
return r3d_logits_gemm_bf16_dispatch(a, s, c.impl);
}
extern "C" int r3d_rad_logits_gemm_bf16_alu(const RadArgs* a, RadStream s)
{ return r3d_logits_gemm_bf16_dispatch(a, s, 1); }
extern "C" int r3d_rad_gemm_nt_bf16_tiled(const RadArgs* a, RadStream s)
{
return rad_gemm_run(a, s, 0, "N", "K");
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
if (c.impl <= 1) return r3d_gemm_nt_bf16_tiled_dispatch(a, s, c.impl);
if (c.impl == 2) return r3d_rad_gemm_nt_bf16_tiled_wmma(a, s);
return r3d_rad_gemm_nt_bf16_m64_wmma(a, s);
}
extern "C" int r3d_rad_gemm_nt_bf16_tiled_alu(const RadArgs* a, RadStream s)
{ return r3d_gemm_nt_bf16_tiled_dispatch(a, s, 1); }
/* The head's relayout writer. A layout query that answers RAD_OK promises the loader that
* relayout will produce the described form (rad_abi.h). The container stores the quantiser's
+152
View File
@@ -0,0 +1,152 @@
/* r3d_vocab_bf16_wmma.hip -- the prefill tiled GEMM on the wave-matrix: the WMMA twin of the
* ALU fdot2 kernel in r3d_vocab_bf16.hip (the `gemm_nt_bf16_tiled` row's compute-dual).
*
* y[M,N] = a[M,K] @ w[N,K]^T, bf16 in, f32 accumulate, bf16 out (one narrowing at the store).
*
* The ALU arm owns 64 f32 accumulators a lane (an 8x8 square) and runs v_fdot2; this arm runs the
* same 128x128 tile on the wave-matrix, which is the matrix core at 512 FLOPS/clk/CU against the
* ALU's ~256, so it is the faster of the pair at prefill heights. The tile is split eight ways
* across the eight waves by column: wave w owns cols [w*16, w*16+16) and all 128 rows, so it
* accumulates eight 16x16 wave-matrix tiles (one per 16-row block) -- 64 f32 accumulators a wave,
* the same count the ALU arm keeps a lane. Every wave does unique work (the 16x128 wave-filling
* retile), so no wave re-runs a tile.
*
* K is walked in 32-deep chunks (two 16-wide wave-matrix steps); the operands stage to LDS as bf16
* (16 dwords a row, +1 bank-free) and load straight into the bf16 wave-matrix fragments.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
namespace {
constexpr int kThreads = 256; // eight waves
constexpr int kWaves = kThreads / kWave;
constexpr int kTM = 128; // activation rows a block
constexpr int kTN = 128; // weight cols a block
constexpr int kKC = 32; // k codes a chunk: two 16-wide wave-matrix steps
constexpr int kDW = kKC / 2; // dwords a row: 32 bf16 are 16 dwords (two bf16 a dword)
constexpr int kPitch = kDW + 1; // dwords a staged row: +1, bank-free
__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void vocab_bf16_wmma_kernel(
const uint16_t* __restrict__ a,
const uint16_t* __restrict__ w,
uint16_t* __restrict__ y, int M, int N, int K, int a_ld, int w_ld, int y_ld)
{
__shared__ __align__(16) uint32_t sA[kTM * kPitch]; // 128 rows x 16 dwords
__shared__ __align__(16) uint32_t sB[kTN * kPitch]; // 128 cols x 16 dwords
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wv = tid / kWave; // the wave index (0..7): owns cols wv*16..wv*16+16
const uint32_t r = lane & 15;
const uint32_t m0 = (uint32_t)blockIdx.y * kTM;
const uint32_t n0 = (uint32_t)blockIdx.x * kTN;
// acc[8]: one 16x16 wave-matrix tile per 16-row block (128 rows / 16).
v8float acc[8];
#pragma unroll
for (int i = 0; i < 8; ++i) acc[i] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
for (int k0 = 0; k0 < K; k0 += kKC) {
// Stage 128 activation rows and 128 weight cols (16 dwords each), clamped at the edge.
for (int i = (int)tid; i < kTM * kDW; i += kThreads) {
const int row = i / kDW, d = i % kDW;
const int mm = (int)(m0 + row < (uint32_t)M ? m0 + row : (uint32_t)M - 1);
sA[row * kPitch + d] = *(const uint32_t*)(a + (size_t)mm * a_ld + k0 + 2 * d);
}
for (int i = (int)tid; i < kTN * kDW; i += kThreads) {
const int col = i / kDW, d = i % kDW;
const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1);
sB[col * kPitch + d] = *(const uint32_t*)(w + (size_t)nn * w_ld + k0 + 2 * d);
}
group_barrier();
// Wave wv owns cols wv*16..wv*16+16, all eight 16-row blocks.
const uint32_t* wp = sB + (size_t)(wv * 16 + r) * kPitch;
#pragma unroll
for (int rb = 0; rb < 8; ++rb) {
const uint32_t* ap = sA + (size_t)(rb * 16 + r) * kPitch;
#pragma unroll
for (int k = 0; k < kKC; k += 16) {
v16short fa, fb;
#pragma unroll
for (int g = 0; g < 8; ++g) {
const uint32_t dw = ap[k / 2 + g];
fa[2 * g] = (short)(dw & 0xffffu); fa[2 * g + 1] = (short)(dw >> 16);
const uint32_t dwb = wp[k / 2 + g];
fb[2 * g] = (short)(dwb & 0xffffu); fb[2 * g + 1] = (short)(dwb >> 16);
}
acc[rb] = wmma_bf16(fa, fb, acc[rb]);
}
}
group_barrier();
}
// Store: C-frag lane l, VGPR g -> row 2*(l>>4)+g, col l&15; offset by the row block and wave.
#pragma unroll
for (int rb = 0; rb < 8; ++rb)
#pragma unroll
for (int g = 0; g < 8; ++g) {
const int m = m0 + rb * 16 + 2 * g + (lane >> 4);
const int n = n0 + wv * 16 + r;
if (m < M && n < N) y[m * y_ld + n] = f32_to_bf16(acc[rb][g]);
}
}
int r3d_vocab_bf16_wmma(long av, long wv, long yv, int M, int N, int K, int a_ld, int w_ld,
int y_ld, long stream)
{
if (!av || !wv || !yv) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (K % kKC) return -2; // the tile's k-chunk; the M/N tails clamp and are dropped at the store
if (!a_ld) a_ld = K;
if (!w_ld) w_ld = K;
if (!y_ld) y_ld = N;
if (a_ld < K || w_ld < K || y_ld < N) return -3;
if ((av & 15) || (wv & 15) || (yv & 15)) return -5;
const uint16_t* a = (const uint16_t*)(uintptr_t)av;
const uint16_t* w = (const uint16_t*)(uintptr_t)wv;
uint16_t* y = (uint16_t*)(uintptr_t)yv;
hipStream_t s = (hipStream_t)(uintptr_t)stream;
dim3 grid((unsigned)(N + kTN - 1) / kTN, (unsigned)(M + kTM - 1) / kTM), blk(kThreads);
vocab_bf16_wmma_kernel<<<grid, blk, 0, s>>>(a, w, y, M, N, K, a_ld, w_ld, y_ld);
return (int)hipGetLastError();
}
} // namespace
extern "C" {
int r3d_gemm_nt_bf16_tiled_wmma(long a, long b, long y, int M, int N, int K, int a_ld, int w_ld,
int y_ld, long stream)
{ return r3d_vocab_bf16_wmma(a, b, y, M, N, K, a_ld, w_ld, y_ld, stream); }
int r3d_rad_gemm_nt_bf16_tiled_wmma(const RadArgs* a, RadStream s)
{
if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL);
const RadTensor* at = &a->t[0], *wt = &a->t[1], *yt = &a->t[2];
if (!r3d_p(at) || !r3d_p(wt) || !r3d_wp(yt)) return R3D_NO(RAD_E_INVAL);
if (at->dtype != RAD_BF16 || wt->dtype != RAD_BF16 || yt->dtype != RAD_BF16)
return R3D_NO(RAD_E_DTYPE); // the plain bf16 head; the quantised form is the ALU arm's
long long M = 0, K = 0;
if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL);
const long long N = (wt->rank >= 2) ? wt->shape[0] : 0;
if (M <= 0 || N <= 0 || K <= 0 || (K & 31))
return R3D_NO(RAD_E_SHAPE); // the 128x128 tile, 32-deep k chunks; the M/N tails clamp
const int a_ld = (int)at->stride[0];
const int w_ld = (int)wt->stride[0];
const int y_ld = (int)yt->stride[0];
return r3d_vocab_bf16_wmma((long)(uintptr_t)r3d_p(at), (long)(uintptr_t)r3d_p(wt),
(long)(uintptr_t)r3d_wp(yt), (int)M, (int)N, (int)K, a_ld, w_ld,
y_ld, (long)(uintptr_t)s);
}
} // extern "C"