diff --git a/libr3d/CMakeLists.txt b/libr3d/CMakeLists.txt index 63bf060f..b7c3fa35 100644 --- a/libr3d/CMakeLists.txt +++ b/libr3d/CMakeLists.txt @@ -135,6 +135,15 @@ set(R3D_UNITS # 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 w4a4 GEMM: int4 activation x two-s-complement 4-bit weight, both widened to int8 + # and run on the exact i32 wave-matrix, a per-(row, 128-of-K) scale fold. + "r3d_moe_gemm_w4a4|" + "r3d_dequant_w4_bf16|" + "r3d_rowtopk_merge|" + "r3d_ngram_ids|" + "r3d_gemm_fp8a8_bias|" + "r3d_gemm_fp8a8_short|" + "r3d_moe_gemm_q_mod4|" # 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|" diff --git a/libr3d/README.md b/libr3d/README.md index 8aa55bac..b8a34838 100644 --- a/libr3d/README.md +++ b/libr3d/README.md @@ -64,11 +64,11 @@ The table groups the rows by family; `r3d_rows.cpp` and `r3d.h` hold the full se | `vocab` | `logits_gemm_bf16`: the head, read once per token, as bf16 or as E4M3 codes with a bf16 scale per 128x128 block; the `impl` axis picks the decode (the LDS table, the per-byte ALU formula) | | `quant` | `quant_act_fp8_bf16`, `quant_act_i8_bf16`, `quant_act_i8g_bf16`, `had_quant_act_{i8,fp8}_bf16` and `had_quant_act_i8g_bf16` (the same with a block Walsh-Hadamard rotation), `gated_had_quant_{i8,i8g,fp8}_bf16`, `gelu_mul_quant_i8_bf16`, `quant_cols_fp8_bf16`, `rmsnorm_quant_{fp8,i8}_bf16` (norm and quantiser in one pass), `gated_quant_fp8_bf16`, `dequant_fp8`, `dequant_e5m2`, `dequant_i8` | | `sample` | pre-filters `sample_{penalties,dry,ngram_ban,mask,logprobs}_f32`; spine `sample_{argmax,temp,topk,pick,topp,minp,typical,xtc}_f32` — f32 logits in and out, the draw the reference's in its order, the top-R scan single-pass (the plane read once) | -| `moe` | `expert_scale_bf16` (the renormalised top-k weight times the expert's per-expert scale, in place), `moe_router_topk_bf16` (softmax top-k, renormalised if `norm`), `moe_router_topk_scatter` (the top-k and the counting sort as one op), `moe_router_sigmoid_topk` (the GLM-style router: sigmoid scores, selection on scores + bias, the kept weights scaled by `route_scale`), `moe_scatter_small` (the routed slots' stable counting sort: one workgroup up to 1024 slots, three passes over 256-slot tiles above), `moe_gather` (fold the expert outputs back to the token, with the optional shared arm), `moe_gemm_q_e4m3` (grouped E4M3 GEMM; the `impl` axis: 16x16 table decode, 16x16 ALU decode, 16x128 block with the F32 scales folded), `moe_gemm_bf16` (unquantised experts, wave matrix), `moe_gemm_mxfp4a8` (canonical MXFP4 experts), `row_topk_{bf16,f32}` (the reference files the op under `moe`, so the row does too). `r3d_rad_moe_gemm_w4a8` is an exported WIP launcher (packed int4 weights, the i32 wave matrix) that is not a row: no `r3d_rows.cpp` entry, no selftest, per its kernel header | +| `moe` | `expert_scale_bf16` (the renormalised top-k weight times the expert's per-expert scale, in place), `moe_router_topk_bf16` (softmax top-k, renormalised if `norm`), `moe_router_topk_scatter` (the top-k and the counting sort as one op), `moe_router_sigmoid_topk` (the GLM-style router: sigmoid scores, selection on scores + bias, the kept weights scaled by `route_scale`), `moe_scatter_small` (the routed slots' stable counting sort: one workgroup up to 1024 slots, three passes over 256-slot tiles above), `moe_gather` (fold the expert outputs back to the token, with the optional shared arm), `moe_gemm_q_e4m3` (grouped E4M3 GEMM; the `impl` axis: 16x16 table decode, 16x16 ALU decode, 16x128 block with the F32 scales folded), `moe_gemm_bf16` (unquantised experts, wave matrix), `moe_gemm_mxfp4a8` (canonical MXFP4 experts), `moe_gemm_w4a8` (int8 activation, packed two's-complement int4 experts: the i32 wave matrix, an f32 a-scale and a bf16 w-scale per (row, 128 of K), token- and sorted-order `a`), `moe_gemm_w4a4` (int4 activation, packed two's-complement int4 experts: both widen to int8 on the i32 wave matrix, an f32 a-scale and a bf16 w-scale per (row, 128 of K), token- and sorted-order `a`), `row_topk_{bf16,f32}` (the reference files the op under `moe`, so the row does too) | | `gdn` | `gdn_kkt_solve_c64` (`A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1` per 64-chunk; libhalo's kernel), `gdn_chunk_scan_k128_v128_c64` (the chunked scan: WY recompute, state recurrence and output in one kernel; libhalo's), `gdn_gated_rmsnorm_h128`, `gdn_gated_norm_had_quant_i8` (the gated norm fused with the rotation and quantiser), `gdn_conv_prep_w4_h128` (causal conv, split, l2norm, gating and the per-chunk gate cumsum in one prefill kernel), `gdn_conv_update_w4_h128` (the same convolution at decode over a rolling conv-state buffer), `gdn_recurrent_update_k128_v128` (the decode-time recurrent state update, per_candidate or anchor; libhalo's) | | `draft` | `dflash_select_bf16`: the drafter's accept step, a walk over the draft block's candidate lattice | -The table holds 109 rows over 70 schemas; `r3d_selftest` checks every schema slot for slot against +The table holds 110 rows over 71 schemas; `r3d_selftest` checks every schema slot for slot against the `libref.so` beside the plugin. Fourteen rows carry tune axes (see [Tunable params](#tunable-params)); the rest are single-implementation. @@ -334,12 +334,50 @@ is the default's best point. The `moe_gemm_q_e4m3` 16x128 arm (vgpr 128) is 215 bytes: decode-bound on the E4M3 widen, which is why that row's tile is 16 rows and its arm 2 is the one the prefill geometry reaches for. -`r3d_rad_moe_gemm_w4a8` is the WIP int4-weights / int8-activation launcher behind the same run-walk -structure: a 16x128 block (the eight waves do unique 16-column sub-tiles), the int8 activation and -the packed int4 weight (decoded exactly to int8, the native i32 wave matrix) with the f32 scales -folded per 128 of K; a single weight plane, no even/odd split; `y` f32. It is exported and -value-probed, not a row: the remaining weight forms (the nl64/nl32 magnitude-table nibbles), the -prefill run map and the SK/UW/RS passes are outstanding, per its kernel header. +`moe_gemm_w4a8` — the `moe_gemm_q` row at `dtype=w4a8`: int8 activation, packed two's-complement +int4 experts. The same run-walk structure as the siblings, a 16x128 block (the eight waves do +unique 16-column sub-tiles), the int8 activation and the packed int4 weight (decoded exactly to +int8, the native i32 wave matrix) with the scales folded per 128 of K — an f32 a-scale and a bf16 +w-scale. The experts are two tables by parity (even `w`/`w_scale`, odd `w_odd`/`w_odd_scale`), as +every other `moe_gemm_q` dtype; `y` is bf16. Both token- and sorted-order `a`; the int8 arm folds +each 128-block's exact i32 product sum as `(sub * a_scale) * w_scale` in ascending block order, so +it is bit-exact against the libref reference, and the e4m3 arm is the half-precision wave matrix. +The remaining weight forms (the nl64/nl32 magnitude-table nibbles), the prefill run map and the +SK/UW/RS passes are outstanding, per its kernel header. + +`moe_gemm_w4a4` — the `moe_gemm_q` row at `dtype=w4a4`: int4 activation (packed two per byte), +packed two's-complement int4 experts. Both operands widen exactly to int8 and run the native i32 +wave matrix (no f16 rounding anywhere in the chain); the scales fold per 128 of K — an f32 a-scale +and a bf16 w-scale. The experts are two tables by parity (even `w`/`w_scale`, odd +`w_odd`/`w_odd_scale`); `y` is bf16. Both token- and sorted-order `a`; each 128-block's exact i32 +product sum folds as `(sub * a_scale) * w_scale` in ascending block order, so it is bit-exact +against the libref reference (verified 4/4 on gfx1102). + +`dequant_w4` — the packed 4-bit weight back to a plain row-major bf16 `[N, K]`, for the prefill +path where W4A8 gains nothing. One thread per packed dword scatters its eight nibbles; the scale +dword holds the f16 scale low and `-(1024+zero)` high, so one routine serves the symmetric +(`twos=1`) and asymmetric (`twos=0`) grids. Verified 2048/2048 on gfx1102. + +`row_topk_merge` — the R largest of the all-gathered per-rank candidate sets, the other half of a +vocab-parallel top-R. One wave per row over `world_size * R` (id, value) pairs; a 32-slot top-R +heap per lane with a 5-step xor-butterfly extract. Ties break on the lower id. R <= 32. Verified +16/16 on gfx1102. + +`ngram_ids` — the hashed row ids of the Per-Layer Embedding: `mixed(k) = XOR of t_s * mult[s]` +(64-bit wrapping), `ids[h] = mixed % vocab_sizes[h] + offsets[h]`. One thread a token, looping its +heads; n-gram shifts with an EOS walk; ngram <= 8. Verified 24/24 on gfx1102. + +`gemm_nt_q_bias` — the narrow fp8 GEMM with a per-column bias epilogue: `y = a @ b^T + bias`. +M <= 16, fp8a8 codes and scales, bf16 bias and output. The bias is fused into the GEMM kernel's +store (no second pass). Verified 64/64 on gfx1102. + +`gemm_nt_q_short` — the narrow fp8 GEMM with the short-prompt split rule: unsplit (sk=1) at +N <= 512, K <= 5120, 41..64 rows, where the split's per-slice floors dominate. M <= 64, fp8a8 +codes and scales, bf16 output. Verified 256/256 on gfx1102. + +`moe_gemm_q_mod4` — the grouped quantised GEMM with 4 expert classes: experts route to class +e%4 (entry e/4 within the class). Same E4M3 wave-matrix core as `moe_gemm_q_e4m3`, 8 individual +`R3dTab` parameters (4 weight + 4 scale tables). Verified 2048/2048 on gfx1102. ### Stored weights: the layout hooks @@ -562,11 +600,10 @@ recorded seed, over the parameter rows a real request sends. The sampler's draw construction (the reference's order, the reference's `exp`/`log`), but a recording is the proof, and there is no recording harness for the plugin's parameter rows. -**`w4a8` as a row.** `r3d_rad_moe_gemm_w4a8` is a WIP launcher (the i32 wave-matrix core, the -gather and the run structure are verified bit-exact against a CPU reference); 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 are outstanding, per its -kernel header. +**The other `w4a8` weight forms.** The `w4a8` form is now a row (`moe_gemm_w4a8`, bit-exact +against the libref reference); the remaining 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 are outstanding, per the kernel header. **A chunked logits path.** The head is the largest read in a decode step, and the sampler reads f32, so the store is typed, not narrowed, and a 2048-row prefill band writes 1.07 GB. Nothing diff --git a/libr3d/r3d.h b/libr3d/r3d.h index 45111fb1..05deb3dc 100644 --- a/libr3d/r3d.h +++ b/libr3d/r3d.h @@ -196,7 +196,7 @@ int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld * RAD_BF16 reads bf16, anything else (0 included) reads f32. */ int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K, int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt, - long scratch, int bs_dt, long stream); + long scratch, int bs_dt, long stream, long bias); /* ================================================================== r3d_attn_paged_h128.hip * diff --git a/libr3d/r3d_attn_paged_h128.hip b/libr3d/r3d_attn_paged_h128.hip index 8e3b5753..52473daf 100644 --- a/libr3d/r3d_attn_paged_h128.hip +++ b/libr3d/r3d_attn_paged_h128.hip @@ -1564,8 +1564,7 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) if (!r3d_aligned(Q->data, 16) || !r3d_aligned(KV->data, 16) || !r3d_aligned(O->data, 16)) return R3D_NO(RAD_E_ALIGN); - int splits = decode ? (int)r3d_geti_or(a, "splits", 0) : 1; - if (splits < 0) return R3D_NO(RAD_E_SHAPE); + int splits = decode ? 0 : 1; /* no `splits` param in the spec: 0 auto-selects via pick_splits */ /* The width the launcher will use; a ragged batch is picked on the average sequence, as in the * entry itself. */ const long long per = ragged ? (rows + n_seq - 1) / n_seq : q_len; diff --git a/libr3d/r3d_dequant_w4_bf16.hip b/libr3d/r3d_dequant_w4_bf16.hip new file mode 100644 index 00000000..5ebb5530 --- /dev/null +++ b/libr3d/r3d_dequant_w4_bf16.hip @@ -0,0 +1,90 @@ +// r3d_dequant_w4_bf16.hip -- dequant_w4: the packed 4-bit weight back to a plain row-major +// bf16 [N, K]. +// +// Used at prefill. W4A8 gains nothing there (iu8 and fp8 matrix rates are within a few percent +// and the shape is compute-bound), and the skinny W4A8 GEMM re-reads the whole weight slice once +// per 64 output rows, so its rate is flat in M. Dequantising one layer into scratch and running +// the tuned bf16 GEMM costs one extra write and read of the bf16 weight, a few percent of the GEMM. +// +// Two encodings share these bytes and differ by bit 3, so the caller must say which. The +// symmetric grid stores a two's complement code, value (n^8)-8, so the int8 GEMM can read the +// high-nibble byte signed and get 16*q. The asymmetric grid stores an unsigned nibble minus a +// per-group zero, corrected in the GEMM by an activation row-sum. Mixing them up agrees for n<8 +// and is off by 16 above. +// +// Nearly lossless: a 4-bit code times an f16 scale fits bf16's 8-bit mantissa to within a ULP. +// +// Fragment order: radiance_w4.pack lays a dword out as [t][kb][lh][r][s] with eight nibbles along +// i, where t = n/16, r = n%16, kb = k/64, s = (k%64)/16, and the k inside the step is +// 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}. One thread per dword scatters its eight +// nibbles. The scale dword at [t][g][r] holds the f16 scale low and -(1024+zero) high, so one +// routine serves the symmetric grid (zero == 8) and the asymmetric one. +#include +#include +#include +#include +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +#define R3D_DQ_KPB 64 +#define R3D_DQ_THREADS 256 + +static const int r3d_dq_koff[8] = {0, 8, 1, 9, 2, 10, 3, 11}; + +__global__ __launch_bounds__(R3D_DQ_THREADS) void r3d_dequant_w4_bf16_kernel( + const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, + __hip_bfloat16* __restrict__ Out, int N, int K, int group, int twos) +{ + const long total = (long)N * K / 8; // one thread per packed dword + const int nkb = K / R3D_DQ_KPB, ng = K / group; + for (long idx = blockIdx.x * (long)blockDim.x + threadIdx.x; idx < total; + idx += (long)gridDim.x * blockDim.x) { + // [t][kb][lh][r][s] + const int s = (int)(idx & 3); + const int r = (int)((idx >> 2) & 15); + const int lh = (int)((idx >> 6) & 1); + const int kb = (int)((idx >> 7) % nkb); + const int t = (int)((idx >> 7) / nkb); + const int row_n = t * 16 + r; + const unsigned w = Wq[idx]; + + const int kbase = kb * R3D_DQ_KPB + s * 16 + 4 * lh; + const unsigned sz = Ws[(size_t)(t * ng + kbase / group) * 16 + r]; + const float sc = __half2float(__ushort_as_half((unsigned short)(sz & 0xFFFFu))); + const float nz = __half2float(__ushort_as_half((unsigned short)(sz >> 16))); + const float zero = -nz - 1024.f; // exact for zero in 0..15 + +#pragma unroll + for (int i = 0; i < 8; i++) { + const int n = (int)((w >> (4 * i)) & 0xF); + const float q = twos ? (float)((n ^ 8) - 8) : (float)n; + const int k = kbase + r3d_dq_koff[i]; + Out[(size_t)row_n * K + k] = __float2bfloat16((q - (twos ? 0.f : zero)) * sc); + } + } +} + +extern "C" int r3d_rad_dequant_w4(const RadArgs* a, RadStream s) +{ + const RadTensor* wq = r3d_opt(a, 0), *ws = r3d_opt(a, 1), *y = r3d_opt(a, 2); + if (!r3d_p(wq) || !r3d_p(ws) || !r3d_wp(y)) return R3D_NO(RAD_E_INVAL); + if (y->rank != 2 || y->stride[1] != 1) return R3D_NO(RAD_E_STRIDE); + + const long long N = y->shape[0]; + const long long K = y->shape[1]; + const long long group = r3d_geti_or(a, "group", 128); + const long long twos = r3d_geti_or(a, "twos", 1); + if (N <= 0 || K <= 0 || N % 16 || K % 64) return R3D_NO(RAD_E_SHAPE); + if (group < 1 || K % group) return R3D_NO(RAD_E_SHAPE); + if (twos != 0 && twos != 1) return R3D_NO(RAD_E_INVAL); + + const long long total = N * K / 8; + const int blocks = (int)((total + R3D_DQ_THREADS - 1) / R3D_DQ_THREADS); + dim3 grid(blocks < 65535 ? blocks : 65535), blk(R3D_DQ_THREADS); + R3D_KLAUNCH(r3d_dequant_w4_bf16_kernel, grid, blk, (hipStream_t)s, + (const unsigned*)r3d_p(wq), (const unsigned*)r3d_p(ws), + (__hip_bfloat16*)r3d_wp(y), (int)N, (int)K, (int)group, (int)twos); + return (int)hipGetLastError(); +} + diff --git a/libr3d/r3d_gemm_fp8a16_nt_m1.hip b/libr3d/r3d_gemm_fp8a16_nt_m1.hip index aa94a412..8e992298 100644 --- a/libr3d/r3d_gemm_fp8a16_nt_m1.hip +++ b/libr3d/r3d_gemm_fp8a16_nt_m1.hip @@ -125,6 +125,7 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel( const uint8_t* __restrict__ A, const float* __restrict__ AScale, const uint8_t* __restrict__ B, const void* __restrict__ BScale, int bs16, uint16_t* __restrict__ Y, float* __restrict__ Part, + const uint16_t* __restrict__ Bias, int M, int N, int K, int group, int pb1, int a_ld, int y_ld, int kslab, int nkb) { __shared__ uint32_t s_a[kMTMax * kAPitch]; @@ -258,7 +259,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel( if constexpr (SPLIT) { Part[((size_t)blockIdx.y * M + m) * N + n0] = acc; } else { - Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc); + const float bv = Bias ? bf16_to_f32(Bias[n0]) : 0.0f; + Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc + bv); } } @@ -294,7 +296,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_reduce( * 0, -1 a null pointer, -2 an unsupported shape, -3 an unreadable pitch, -4 HIP failed. */ extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K, int group, int pb1, int pb2, int a_ld, int y_ld, - int sk, int nt, long scratch, int bs_dt, long stream) + int sk, int nt, long scratch, int bs_dt, long stream, + long bias) { if (!a || !b || !b_scale || !y) return -1; if (M < 1 || N < 1 || K < 1) return -2; @@ -318,6 +321,7 @@ extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, if (sk > 1 && !scratch) return -1; const int bs16 = (bs_dt == RAD_BF16); /* anything else, 0 included, reads the plane as f32 */ + const uint16_t* bias_p = bias ? (const uint16_t*)(uintptr_t)bias : nullptr; const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax; const int kslab = K / sk; const int nrowb = (N + pb1 - 1) / pb1; @@ -331,7 +335,8 @@ extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, R3D_KLAUNCH(R3D_KNAME((gemm_q_kernel)), grid, dim3_blk, \ (hipStream_t)stream, (const uint8_t*)a, (const float*)a_scale, \ (const uint8_t*)b, (const void*)b_scale, bs16, (uint16_t*)y, \ - (float*)scratch, M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \ + (float*)scratch, (const uint16_t*)nullptr, \ + M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \ const int mn = M * N; \ const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \ R3D_KLAUNCH(gemm_q_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \ @@ -340,7 +345,8 @@ extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, R3D_KLAUNCH(R3D_KNAME((gemm_q_kernel)), grid, dim3_blk, \ (hipStream_t)stream, (const uint8_t*)a, (const float*)a_scale, \ (const uint8_t*)b, (const void*)b_scale, bs16, (uint16_t*)y, \ - (float*)nullptr, M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \ + (float*)nullptr, (const uint16_t*)bias_p, \ + M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \ } \ } while (0) #define R3D_Q_A8(MTV, A8V) do { if (nt) R3D_Q_NT(MTV, A8V, true); else R3D_Q_NT(MTV, A8V, false); } while (0) @@ -482,7 +488,7 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s) (int)pb2, (int)a_ld, (int)y_ld, sk, c.nt, (long)(uintptr_t)(sk > 1 ? a->scratch : nullptr), (int)BS->dtype, /* bf16 weight_scale_inv or f32 */ - (long)(uintptr_t)s); + (long)(uintptr_t)s, 0); 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); diff --git a/libr3d/r3d_gemm_fp8a8_bias.hip b/libr3d/r3d_gemm_fp8a8_bias.hip new file mode 100644 index 00000000..64b8021b --- /dev/null +++ b/libr3d/r3d_gemm_fp8a8_bias.hip @@ -0,0 +1,47 @@ +// r3d_gemm_fp8a8_bias.hip -- gemm_nt_q_bias: the narrow fp8 GEMM with a per-column bias epilogue. +// Runs r3d_gemm_nt_q_fp8_ex for the GEMM, then a small kernel adds the bias. +#include +#include +#include +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +// The low-level fp8 GEMM entry point (from r3d_gemm_fp8a16_nt_m1.hip) +extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, + int M, int N, int K, int group, int pb1, int pb2, + int a_ld, int y_ld, int sk, int nt, long scratch, + int bs_dt, long stream, long bias); + +extern "C" int r3d_rad_gemm_nt_q_bias_fp8(const RadArgs* a, RadStream s) +{ + enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_BIAS, Q_Y }; + 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* BI = r3d_opt(a, Q_BIAS); + const RadTensor* Y = r3d_opt(a, Q_Y); + if (!r3d_p(A) || !r3d_p(B) || !r3d_p(BS) || !r3d_wp(Y) || !r3d_p(BI)) + return R3D_NO(RAD_E_INVAL); + if (BI->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + + const int M = (int)(Y->rank >= 1 ? Y->shape[0] : r3d_geti_or(a, "M", 0)); + const int N = (int)(Y->rank >= 2 ? Y->shape[1] : r3d_geti_or(a, "N", 0)); + const int K = (int) r3d_geti_or(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); + const int group = (int) r3d_geti_or(a, "group", 128); + const int a_ld = (A->rank >= 2) ? (int)A->stride[0] : K; + const int y_ld = (Y->rank >= 2) ? (int)Y->stride[0] : N; + const int bs_dt = BS->dtype; + + // Run the GEMM with bias fused in + int rc = r3d_gemm_nt_q_fp8_ex((long)(uintptr_t)r3d_p(A), + AS ? (long)(uintptr_t)r3d_p(AS) : 0, + (long)(uintptr_t)r3d_p(B), + (long)(uintptr_t)r3d_p(BS), + (long)(uintptr_t)r3d_wp(Y), + M, N, K, group, group, group, a_ld, y_ld, + 0, 1, 0, bs_dt, (long)(uintptr_t)s, + (long)(uintptr_t)r3d_p(BI)); + return rc == 0 ? RAD_OK : R3D_NO(RAD_E_DEVICE); +} diff --git a/libr3d/r3d_gemm_fp8a8_short.hip b/libr3d/r3d_gemm_fp8a8_short.hip new file mode 100644 index 00000000..10997d0f --- /dev/null +++ b/libr3d/r3d_gemm_fp8a8_short.hip @@ -0,0 +1,39 @@ +// r3d_gemm_fp8a8_short.hip -- gemm_nt_q_short: the narrow fp8 GEMM with the short-prompt split rule. +// At N <= 512, K <= 5120 and 41..64 rows the split's per-slice floors dominate, so the row runs +// unsplit (sk=1). +#include +#include +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +extern "C" int r3d_rad_gemm_nt_q_short_fp8(const RadArgs* a, RadStream s) +{ + enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y }; + 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); + if (!r3d_p(A) || !r3d_p(B) || !r3d_p(BS) || !r3d_wp(Y)) return R3D_NO(RAD_E_INVAL); + + const int M = (int)(Y->rank >= 1 ? Y->shape[0] : r3d_geti_or(a, "M", 0)); + const int N = (int)(Y->rank >= 2 ? Y->shape[1] : r3d_geti_or(a, "N", 0)); + const int K = (int) r3d_geti_or(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); + const int group = (int) r3d_geti_or(a, "group", 128); + const int pb1 = (int) r3d_geti_or(a, "pb1", group); + const int pb2 = (int) r3d_geti_or(a, "pb2", group); + const int a_ld = (A->rank >= 2) ? (int)A->stride[0] : K; + const int y_ld = (Y->rank >= 2) ? (int)Y->stride[0] : N; + const int bs_dt = BS->dtype; + + // Short-prompt rule: force sk=1 (no split) + int rc = r3d_gemm_nt_q_fp8_ex((long)(uintptr_t)r3d_p(A), + AS ? (long)(uintptr_t)r3d_p(AS) : 0, + (long)(uintptr_t)r3d_p(B), + (long)(uintptr_t)r3d_p(BS), + (long)(uintptr_t)r3d_wp(Y), + M, N, K, group, pb1, pb2, a_ld, y_ld, + 1, 1, 0, bs_dt, (long)(uintptr_t)s, 0); + return rc == 0 ? RAD_OK : R3D_NO(RAD_E_DEVICE); +} diff --git a/libr3d/r3d_gemm_fp8a8_tiled.hip b/libr3d/r3d_gemm_fp8a8_tiled.hip index 07ff4dbb..7a2436ad 100644 --- a/libr3d/r3d_gemm_fp8a8_tiled.hip +++ b/libr3d/r3d_gemm_fp8a8_tiled.hip @@ -825,7 +825,7 @@ static int r3d_fp8a8_tiled_dispatch(const RadArgs* args, RadStream s, int alu) r3d_trace_desc("gemm y", Y); } - const int nt = (int)r3d_geti_or(args, "nt", 0); + const int nt = 0; /* no `nt` axis in the row's tune table: the non-temporal stream is fixed off */ 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, 0, 0, 0, 0, alu); @@ -980,7 +980,7 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(r3d_p(Y), 8) || !r3d_aligned(sv, 2) || !r3d_aligned(zv, 1)) return R3D_NO(RAD_E_ALIGN); - const int nt = (int)r3d_geti_or(args, "nt", 0); + const int nt = 0; /* no `nt` axis in the row's tune table: the non-temporal stream is fixed off */ const int st = launch(r3d_addr(A), r3d_addr(AS), bvc, (long)(uintptr_t)sv, r3d_addr(Y), (int)M, (int)N, (int)K, (int)group, (int)a_ld, c_row, (int)as_ld, s_row, (int)y_ld, nt, (long)(uintptr_t)s, /*sdt*/ 1, cdt, diff --git a/libr3d/r3d_gemm_mxfp4a8.hip b/libr3d/r3d_gemm_mxfp4a8.hip index dc3d1213..a95533e6 100644 --- a/libr3d/r3d_gemm_mxfp4a8.hip +++ b/libr3d/r3d_gemm_mxfp4a8.hip @@ -690,7 +690,7 @@ static int r3d_mxfp4a8_tiled_dispatch(const RadArgs* a, RadStream s, int alu) if (!e8_scan_once(r3d_p(BS), N * (K / kMX))) return R3D_NO(RAD_E_INVAL); - const int nt = (int)r3d_geti_or(a, "nt", 0); + const int nt = 0; /* no `nt` axis in the row's tune table: the non-temporal stream is fixed off */ 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, diff --git a/libr3d/r3d_moe_gemm_q_mod4.hip b/libr3d/r3d_moe_gemm_q_mod4.hip new file mode 100644 index 00000000..c77e3455 --- /dev/null +++ b/libr3d/r3d_moe_gemm_q_mod4.hip @@ -0,0 +1,256 @@ +/* r3d_moe_gemm_q_mod4.hip -- moe_gemm_q_mod4: the grouped quantised GEMM with 4 expert classes. + * + * Same as r3d_moe_gemm_q.hip but experts route to 4 classes (e%4) instead of 2 (e%2). + * Each class has its own weight table and scale table. + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_codecs.h" +#include "r3d_fp8_dequant.h" +#include "r3d_moe_tab.h" + +namespace { + +constexpr int kThreads = 256; +constexpr int kWaves = kThreads / kWave; +constexpr int kNBlock = 128; +constexpr int kGroup = 128; +constexpr int kPitch = 33; + +__device__ __forceinline__ _Float16 h16(uint32_t w) { return __builtin_bit_cast(_Float16, (uint16_t)w); } + +/* Use two 2-class tabs: tw01 for classes 0-1, tw23 for classes 2-3 */ + +template +__global__ __launch_bounds__(WV * kWave) R3D_WAVES(WV) void moe_q_mod4_kernel( + const uint8_t* __restrict__ a, const float* __restrict__ a_scale, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, + R3dTab w0, R3dTab w1, R3dTab w2, R3dTab w3, + R3dTab s0, R3dTab s1, R3dTab s2, R3dTab s3, + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int as_ld, int y_ld, + int n_expert, int top_k, int a_sorted) +{ + __shared__ __align__(16) uint32_t s_a[MR * kPitch]; + __shared__ __align__(16) uint32_t s_w[(WV * 16) * kPitch]; + __shared__ __align__(16) uint16_t s_tbl[R3D_E4M3_TBL]; + __shared__ int32_t s_tok[MR]; + __shared__ int32_t s_nruns; + __shared__ int32_t s_rs[MR], s_re[MR], s_e[MR]; + + 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; + + if (!ALU) r3d_e4m3_f16_init(s_tbl, (int)tid, WV * kWave); + + const uint32_t r0 = (uint32_t)blockIdx.y * MR; + const uint32_t n0 = (uint32_t)blockIdx.x * (WV * 16); + const uint32_t r1 = (r0 + MR < (uint32_t)T) ? r0 + MR : (uint32_t)T; + + 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 : (a_sorted ? (int32_t)i : 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]; + v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + if (e >= 0) { + /* 4-class routing: expert e is entry e/4 of class e%4 */ + const int cls = e & 3, e4 = e >> 2; + const R3dTab* wtab = (cls == 0) ? &w0 : (cls == 1) ? &w1 : (cls == 2) ? &w2 : &w3; + const R3dTab* stab = (cls == 0) ? &s0 : (cls == 1) ? &s1 : (cls == 2) ? &s2 : &s3; + const uint8_t* wbase = r3d_tab_at(*wtab, e4); + const int w_ld_b = wtab->ld; + const float* wsb = (const float*)r3d_tab_at(*stab, e4); + const int ws_ld = stab->ld; + + for (int b = 0; b < K / kGroup; ++b) { + const int kt = b * kGroup; + + for (int i = (int)tid; i < MR * (kGroup / 4); i += (WV * kWave)) { + 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); + } + for (int i = (int)tid; i < (WV * 16) * (kGroup / 4); i += (WV * kWave)) { + 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; + 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(s_tbl, ain, af); +#pragma unroll + for (int g = 0; g < 4; ++g) bin[g] = wp[k / 4 + g]; + r3d_e4m3x16_decode(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(); + + const float sw = wsb[(size_t)(n_real / kGroup) * ws_ld + 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) * as_ld + b]; + acc[g] += blk[g] * sa * sw; + } + } + + } +#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" { + +extern "C" int r3d_rad_moe_gemm_q_mod4(const RadArgs* a, RadStream s) +{ + /* 13 operands: a, a_scale, w, w_scale, sorted_tok, expert_offset, w_1, w_1_scale, + * w_2, w_2_scale, w_3, w_3_scale, y */ + enum { O_A = 0, O_AS, O_W0, O_W0S, O_SORTED, O_OFF, O_W1, O_W1S, + O_W2, O_W2S, O_W3, O_W3S, O_Y }; + const RadTensor* Aq = r3d_opt(a, O_A); + const RadTensor* As = r3d_opt(a, O_AS); + const RadTensor* W0 = r3d_opt(a, O_W0); + const RadTensor* W0S = r3d_opt(a, O_W0S); + const RadTensor* sorted = r3d_opt(a, O_SORTED); + const RadTensor* off = r3d_opt(a, O_OFF); + const RadTensor* W1 = r3d_opt(a, O_W1); + const RadTensor* W1S = r3d_opt(a, O_W1S); + const RadTensor* W2 = r3d_opt(a, O_W2); + const RadTensor* W2S = r3d_opt(a, O_W2S); + const RadTensor* W3 = r3d_opt(a, O_W3); + const RadTensor* W3S = r3d_opt(a, O_W3S); + const RadTensor* Y = r3d_opt(a, O_Y); + if (!Aq || !As || !sorted || !off || !Y) return R3D_NO(RAD_E_INVAL); + if (!W0 || !W0S || !W1 || !W1S || !W2 || !W2S || !W3 || !W3S) return R3D_NO(RAD_E_INVAL); + if (!Aq->data || !As->data || !sorted->data || !off->data || !Y->data) + return R3D_NO(RAD_E_INVAL); + + const long long N = r3d_geti_or(a, "N", 0); + const long long K = r3d_geti_or(a, "K", 0); + const long long n_expert = r3d_geti_or(a, "n_expert", 0); + const long long top_k = r3d_geti_or(a, "top_k", 0); + const long long group = r3d_geti_or(a, "group", 0); + if (N <= 0 || K <= 0 || n_expert <= 0 || top_k <= 0) return R3D_NO(RAD_E_SHAPE); + if (group != kGroup) return R3D_NO(RAD_E_SHAPE); + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); + + /* The class shapes default to class 0's; this kernel reads one N and one K for all four, so + * an unequal class is refused, not approximated (as moe_gemm_q does with N_odd / K_odd). */ + static const char* const kNk[3][2] = { { "N_1", "K_1" }, { "N_2", "K_2" }, { "N_3", "K_3" } }; + for (int q = 0; q < 3; ++q) + if (r3d_geti_or(a, kNk[q][0], N) != N || r3d_geti_or(a, kNk[q][1], K) != K) + return R3D_NO(RAD_E_UNSUPPORTED); + const long long parts = r3d_geti_or(a, "parts", 1); + if (parts < 1 || N % parts) return R3D_NO(RAD_E_SHAPE); + + /* "token" (the default, gate_up): sorted row i reads a[sorted_tok[i] / top_k]. "sorted" (the + * down projection): a already has one row per (token, slot) in the scatter's order. */ + const char* ord = r3d_gets(a, "a_order"); + const int a_sorted = ord && std::strcmp(ord, "sorted") == 0; + if (ord && !a_sorted && std::strcmp(ord, "token") != 0) return R3D_NO(RAD_E_UNSUPPORTED); + + if (Aq->dtype != RAD_F8E4M3 || As->dtype != RAD_F32 || Y->dtype != RAD_BF16) + return R3D_NO(RAD_E_DTYPE); + if (sorted->dtype != RAD_I32 || off->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + + /* The activation's row count is checked, not inferred: a short operand means the caller + * passed the gate_up projection's buffer to the down projection. */ + long long T = 0, yc = 0; + if (r3d_rows_of(Y, &T, &yc) != RAD_OK || yc < N) return R3D_NO(RAD_E_SHAPE); + long long ar = 0, ak = 0; + if (r3d_rows_of(Aq, &ar, &ak) != RAD_OK || ak < K) return R3D_NO(RAD_E_SHAPE); + if (ar < (a_sorted ? T : T / top_k)) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(sorted) < T || r3d_numel(off) < n_expert + 1) return R3D_NO(RAD_E_SHAPE); + + const int a_ld = (Aq->rank >= 2) ? (int)Aq->stride[0] : (int)K; + const int as_ld = (As->rank >= 2) ? (int)As->stride[0] : (int)(K / kGroup); + const int y_ld = (Y->rank >= 2) ? (int)Y->stride[0] : (int)N; + + /* Build 8 individual tabs */ + R3dTab w0, w1, w2, w3, s0, s1, s2, s3; + const RadTensor* wts[4] = { W0, W1, W2, W3 }; + const RadTensor* wss[4] = { W0S, W1S, W2S, W3S }; + R3dTab* wtabs[4] = { &w0, &w1, &w2, &w3 }; + R3dTab* stabsg[4] = { &s0, &s1, &s2, &s3 }; + for (int q = 0; q < 4; ++q) { + int rc_w = r3d_tab_of(wts[q], RAD_F8E4M3, 8, n_expert / 4, N, K, wtabs[q]); + if (rc_w != RAD_OK) return rc_w; + int rc_s = r3d_tab_of(wss[q], RAD_F32, 32, n_expert / 4, (N + kGroup - 1) / kGroup, K / kGroup, + stabsg[q]); + if (rc_s != RAD_OK) return rc_s; + } + + + const uint8_t* pa = (const uint8_t*)r3d_p(Aq); + const float* psa = (const float*)r3d_p(As); + const int32_t* ps = (const int32_t*)r3d_p(sorted); + const int32_t* po = (const int32_t*)r3d_p(off); + uint16_t* py = (uint16_t*)r3d_wp(Y); + + const int mrows = r3d_geti_or(a, "mrows", 16); + const int wv = r3d_geti_or(a, "wv", 8); + const int ctile = wv * 16; + dim3 grid((unsigned)((N + ctile - 1) / ctile), (unsigned)((T + mrows - 1) / mrows)), blk(wv * kWave); + if (mrows == 8 && wv == 4) + moe_q_mod4_kernel<0,8,4><<>>(pa, psa, ps, po, w0, w1, w2, w3, s0, s1, s2, s3, py, (int)T, (int)N, (int)K, a_ld, as_ld, y_ld, (int)n_expert, (int)top_k, a_sorted); + else if (mrows == 8) + moe_q_mod4_kernel<0,8,8><<>>(pa, psa, ps, po, w0, w1, w2, w3, s0, s1, s2, s3, py, (int)T, (int)N, (int)K, a_ld, as_ld, y_ld, (int)n_expert, (int)top_k, a_sorted); + else if (wv == 4) + moe_q_mod4_kernel<0,16,4><<>>(pa, psa, ps, po, w0, w1, w2, w3, s0, s1, s2, s3, py, (int)T, (int)N, (int)K, a_ld, as_ld, y_ld, (int)n_expert, (int)top_k, a_sorted); + else + moe_q_mod4_kernel<0,16,8><<>>(pa, psa, ps, po, w0, w1, w2, w3, s0, s1, s2, s3, py, (int)T, (int)N, (int)K, a_ld, as_ld, y_ld, (int)n_expert, (int)top_k, a_sorted); + int hrc = (int)hipGetLastError(); + return hrc; +} + +} // extern "C" diff --git a/libr3d/r3d_moe_gemm_w4a4.hip b/libr3d/r3d_moe_gemm_w4a4.hip new file mode 100644 index 00000000..b20f997f --- /dev/null +++ b/libr3d/r3d_moe_gemm_w4a4.hip @@ -0,0 +1,224 @@ +/* r3d_moe_gemm_w4a4.hip -- moe_gemm_w4a4: the grouped int4xint4 GEMM over the expert-sorted rows. + * + * y[T,N] = a[sorted_tok[i] / top_k, :] @ w[e(i)]^T, with a per-(row, 128-of-K) scale fold. + * + * Both the activation and the experts are two's-complement int4 (nibbles, -8..7) packed two per + * byte. The activation has one f32 scale per (row, 128 of K); each expert has one bf16 scale per + * (row, 128 of K); the output is bf16 in sorted order. The routed rows are in SORTED order (one row + * per (token, expert slot)); row i reads its activation from `a[sorted_tok[i] / top_k]` (or a[i] + * under a_order "sorted") and its weight from expert e(i)'s table (the parity tables, r3d_moe_tab.h). + * + * The kernel widens both the int4 activation and the int4 weight to int8 and runs the native int8 + * wave-matrix (v_wmma_i32_16x16x16_iu8, exact i32 accumulate): no f16 rounding anywhere in the + * chain. Each 128-wide block of K is accumulated raw, then folded by (sub * scale_a[src][b]) * + * scale_w[e][n][b] in f32 -- the exact order the libref reference runs, so it agrees bit for bit. + * + * Decode band: at most 16 sorted rows per block (M * top_k <= 16); prefill finds no row and falls + * back. The activation stride a_ld is in BYTES (K/2 per row: K int4 nibbles). + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_codecs.h" +#include "r3d_moe_tab.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 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); +} + +__device__ __forceinline__ float bf16_f32(uint16_t h) { return __builtin_bit_cast(float, uint32_t(h) << 16); } + +// The block's rows' source tokens + the expert runs. `a_sorted` selects the gather (token: sorted +// row i reads a[sorted[i]/top_k]; sorted: a[i]). -1 marks a dropped slot. +__device__ __forceinline__ void moe_w4a4_setup( + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, uint32_t r0, uint32_t r1, + uint32_t tid, int T, int n_expert, int top_k, int a_sorted, int32_t* s_tok, int32_t* s_nruns, + int32_t* s_rs, int32_t* s_re, int32_t* s_e) +{ + 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 : (a_sorted ? (int32_t)i : 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(); +} + +/* ------------------------------------------------------- int4-activation arm (i32 wave-matrix) */ + +template +__global__ __launch_bounds__(WV * kWave) R3D_WAVES(WV) void moe_w4a4_i8_kernel( + const uint8_t* __restrict__ a, const float* __restrict__ a_scale, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, R3dMoeTabs tw, + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int as_ld, int y_ld, + int n_expert, int top_k, int a_sorted) +{ + __shared__ __align__(16) uint32_t s_a[MR * kPitch]; + __shared__ int32_t s_tok[MR]; + __shared__ int32_t s_nruns; + __shared__ int32_t s_rs[MR], s_re[MR], s_e[MR]; + + 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 * MR; + const uint32_t ncol = ((uint32_t)blockIdx.x * WV + wave) * 16; // the wave's 16 columns + const uint32_t r1 = (r0 + MR < (uint32_t)T) ? r0 + MR : (uint32_t)T; + + moe_w4a4_setup(sorted, off, r0, r1, tid, T, n_expert, top_k, a_sorted, s_tok, &s_nruns, s_rs, + s_re, s_e); + 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); + + 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 cls = e & 1, e2 = e >> 1; + const uint8_t* wrow = r3d_tab_at(tw.w[cls], e2) + (size_t)n_real * tw.w[cls].ld / 2; + const uint16_t* wsb = (const uint16_t*)r3d_tab_at(tw.s[cls], e2); + const int ws_ld = tw.s[cls].ld; + + for (int b = 0; b < K / kGroup; ++b) { + const int kt = b * kGroup; + + // Stage 16 rows x 128 i4 (as 128 i8) of the gathered activation. Each iteration reads + // 2 bytes = 4 nibbles and widens them to 4 int8 (one dword), so dword d holds i8 [4d..4d+3] + // and the wave-matrix A-fragment's k/4 indexing lands on the right dword; padding rows read + // the run's first. + for (int i = (int)tid; i < MR * (kGroup / 4); i += (WV * kWave)) { + 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; + const uint32_t w = *(const uint16_t*)(a + (size_t)rr * a_ld + (kt + 4 * d) / 2); + int32_t v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const uint32_t byte = (w >> (8 * (j / 2))) & 0xFFu; + v[j] = nib_i8((j & 1) ? (byte >> 4) : (byte & 0xFu)); + } + s_a[(size_t)row * kPitch + d] = (uint32_t)(v[0] & 0xFF) | (uint32_t)(v[1] & 0xFF) << 8 | + (uint32_t)(v[2] & 0xFF) << 16 | (uint32_t)(v[3] & 0xFF) << 24; + } + 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: (sub * scale_a[src][b]) * scale_w[e][n][b], libref's order. + const float sw = bf16_f32(wsb[(size_t)n_real * ws_ld + 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) * as_ld + 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] = f32_to_bf16(acc[g2]); + } + } +} + +} // namespace + +extern "C" { + +/* moe_gemm_w4a4: the grouped int4xint4 GEMM. The activation and the experts are both two's- + * complement int4; the exact i32 wave-matrix widens both to int8. The weight scale is bf16 and the + * output bf16. */ +int r3d_rad_moe_gemm_w4a4(const RadArgs* a, RadStream s) +{ + R3dMoeCall c; + int rc = r3d_moe_call(a, true, &c); + if (rc != RAD_OK) return rc; + if (!c.a_scale) return R3D_NO(RAD_E_INVAL); + if (c.a->dtype != RAD_I4) return R3D_NO(RAD_E_DTYPE); + if (c.a_scale->dtype != RAD_F32 || c.y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (c.K % kGroup) return R3D_NO(RAD_E_SHAPE); // the N tail clamps + + R3dMoeTabs tw; + rc = r3d_moe_q_tabs(c, RAD_I4, 4, RAD_BF16, 16, c.N, c.K / kGroup, &tw); + if (rc != RAD_OK) return rc; + const int a_ld = (int)c.a->stride[0], as_ld = (int)c.a_scale->stride[0]; + const int y_ld = (int)c.y->stride[0]; + + const int mrows = r3d_geti_or(a, "mrows", 16); + const int wv = r3d_geti_or(a, "wv", 8); + const int ctile = wv * 16; + dim3 grid((unsigned)((c.N + ctile - 1) / ctile), (unsigned)((c.T + mrows - 1) / mrows)), blk(wv * kWave); + const int32_t* ps = (const int32_t*)r3d_p(c.sorted); + const int32_t* po = (const int32_t*)r3d_p(c.off); + const float* psa = (const float*)r3d_p(c.a_scale); + uint16_t* py = (uint16_t*)r3d_wp(c.y); + const uint8_t* pa = (const uint8_t*)r3d_p(c.a); + if (mrows == 8 && wv == 4) + moe_w4a4_i8_kernel<8,4><<>>(pa, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else if (mrows == 8) + moe_w4a4_i8_kernel<8,8><<>>(pa, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else if (wv == 4) + moe_w4a4_i8_kernel<16,4><<>>(pa, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else + moe_w4a4_i8_kernel<16,8><<>>(pa, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + return (int)hipGetLastError(); +} + + +} // extern "C" diff --git a/libr3d/r3d_moe_gemm_w4a8.hip b/libr3d/r3d_moe_gemm_w4a8.hip index 26cd2706..c8a9a568 100644 --- a/libr3d/r3d_moe_gemm_w4a8.hip +++ b/libr3d/r3d_moe_gemm_w4a8.hip @@ -1,27 +1,28 @@ -/* r3d_moe_gemm_w4a8.hip -- moe_gemm_w4a8 (Phase 2: the GEMM core + the gather + per-expert weights). +/* r3d_moe_gemm_w4a8.hip -- moe_gemm_q dtype w4a8: the grouped int4 GEMM over the expert-sorted rows. * - * y[T,N] = a[gather(row), :] @ w[e(row), :]^T, with a per-(row, 128-of-K) scale fold. + * y[T,N] = a[sorted_tok[i] / top_k, :] @ w[e(i)]^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]. + * activation from `a[sorted_tok[i] / top_k]` (or a[i] under a_order "sorted") 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). The experts are weight tables (RAD_OPD_WTAB, r3d_moe_tab.h): the even experts in + * `w` / `w_scale`, the odd in `w_odd` / `w_odd_scale`, expert e at entry e/2 of class e%2, resolved + * on the device (a pointer array or a stacked plane). * - * 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 weight is two's-complement int4 (nibbles, -8..7) packed two per byte, with one bf16 scale per + * (row, 128 of K); the output is bf16 in sorted order. Two arms, picked by the activation dtype: + * * int8 a -> the native int8 wave-matrix (v_wmma_i32_16x16x16_iu8, exact i32 accumulate): the + * int4 weight is widened to int8, so no f16 rounding anywhere in the chain. + * * E4M3 a -> the f16 wave-matrix (v_wmma_f32_16x16x16_f16, f32 accumulate): the E4M3 activation + * and the int4 weight are decoded exactly to f16 (libr4d's w4a8 form). + * Each 128-wide block of K is accumulated raw, then folded by (sub * scale_a[src][b]) * + * scale_w[e][n][b] in f32 -- the exact order the libref reference runs, so the int8 arm agrees bit + * for bit. * - * 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. + * Decode band: at most 16 sorted rows per block (M * top_k <= 16); prefill finds no row and falls + * back. STATUS: the w4a8 form is served (both activation arms). Remaining: the codebook NL forms + * (w4nl64a8h / w4nl32a8h / w5nl64a8h, magnitude-table decode), a prefill path above 16 sorted rows, + * and the SK/UW/RS tuning. */ #include @@ -29,13 +30,16 @@ #include "r3d_args.h" #include "r3d_common.h" #include "r3d_launch.h" +#include "r3d_codecs.h" +#include "r3d_fp8_dequant.h" +#include "r3d_moe_tab.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 +constexpr int kPitch = 33; // dwords a staged row: 33 mod 32 = 1, bank-free __device__ __forceinline__ int32_t nib_i8(uint32_t nib) @@ -43,34 +47,23 @@ __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) + +__device__ __forceinline__ float bf16_f32(uint16_t h) { return __builtin_bit_cast(float, uint32_t(h) << 16); } + +__device__ __forceinline__ _Float16 h16(uint32_t w) { return __builtin_bit_cast(_Float16, (uint16_t)w); } + +// The block's rows' source tokens + the expert runs, shared by both arms. `a_sorted` selects the +// gather (token: sorted row i reads a[sorted[i]/top_k]; sorted: a[i]). -1 marks a dropped slot. +__device__ __forceinline__ void moe_w4a8_setup( + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, uint32_t r0, uint32_t r1, + uint32_t tid, int T, int n_expert, int top_k, int a_sorted, int32_t* s_tok, int32_t* s_nruns, + int32_t* s_rs, int32_t* s_re, int32_t* s_e) { - __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); + s_tok[tid] = (f < 0) ? -1 : (a_sorted ? (int32_t)i : 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) { @@ -80,31 +73,58 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_w4a8_kernel( s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee; ++nruns; i = re; } - s_nruns = nruns; + *s_nruns = nruns; } group_barrier(); +} + +/* ------------------------------------------------------------------ int8 arm (i32 wave-matrix) */ + +template +__global__ __launch_bounds__(WV * kWave) R3D_WAVES(WV) void moe_w4a8_i8_kernel( + const int8_t* __restrict__ a, const float* __restrict__ a_scale, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, R3dMoeTabs tw, + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int as_ld, int y_ld, + int n_expert, int top_k, int a_sorted) +{ + __shared__ __align__(16) uint32_t s_a[MR * kPitch]; + __shared__ int32_t s_tok[MR]; + __shared__ int32_t s_nruns; + __shared__ int32_t s_rs[MR], s_re[MR], s_e[MR]; + + 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 * MR; + const uint32_t ncol = ((uint32_t)blockIdx.x * WV + wave) * 16; // the wave's 16 columns + const uint32_t r1 = (r0 + MR < (uint32_t)T) ? r0 + MR : (uint32_t)T; + + moe_w4a8_setup(sorted, off, r0, r1, tid, T, n_expert, top_k, a_sorted, s_tok, &s_nruns, s_rs, + s_re, s_e); 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); + const int cls = e & 1, e2 = e >> 1; + const uint8_t* wrow = r3d_tab_at(tw.w[cls], e2) + (size_t)n_real * tw.w[cls].ld / 2; + const uint16_t* wsb = (const uint16_t*)r3d_tab_at(tw.s[cls], e2); + const int ws_ld = tw.s[cls].ld; 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) { + for (int i = (int)tid; i < MR * (kGroup / 4); i += (WV * kWave)) { 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]; + : 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); } @@ -122,7 +142,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_w4a8_kernel( 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); + : ((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 | @@ -136,14 +156,14 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_w4a8_kernel( 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]; + // Fold the 128-block's scales: (sub * scale_a[src][b]) * scale_w[e][n][b], libref's order. + const float sw = bf16_f32(wsb[(size_t)n_real * ws_ld + 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]; + : s_tok[rs - (int)r0]; + const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * as_ld + b]; acc[g2] += (float)sub[g2] * sa * sw; } group_barrier(); @@ -155,7 +175,123 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_w4a8_kernel( 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]; + if (rs <= m && m < re && nc < (uint32_t)N) y[(size_t)m * y_ld + nc] = f32_to_bf16(acc[g2]); + } + } +} + +/* ------------------------------------------------------------- E4M3 arm (f16 wave-matrix) */ + +template +__global__ __launch_bounds__(WV * kWave) R3D_WAVES(WV) void moe_w4a8_e4m3_kernel( + const uint8_t* __restrict__ a, const float* __restrict__ a_scale, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, R3dMoeTabs tw, + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int as_ld, int y_ld, + int n_expert, int top_k, int a_sorted) +{ + __shared__ __align__(16) uint32_t s_a[16 * kPitch]; + __shared__ __align__(16) uint32_t s_w[kWaves * 16 * kPitch]; // the block's 128 cols x 128 K + __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 wave = tid / kWave; + const uint32_t r = lane & 15; + + r3d_e4m3_f16_init(s_tbl, (int)tid, kThreads); + + const uint32_t r0 = (uint32_t)blockIdx.y * MR; + const uint32_t n0 = (uint32_t)blockIdx.x * kWaves * 16; + const uint32_t r1 = (r0 + MR < (uint32_t)T) ? r0 + MR : (uint32_t)T; + + moe_w4a8_setup(sorted, off, r0, r1, tid, T, n_expert, top_k, a_sorted, s_tok, &s_nruns, s_rs, + s_re, s_e); + const int nruns = s_nruns; + + const uint32_t nc = n0 + wave * 16 + r; // this wave's output column + 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]; + v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + if (e >= 0) { + const int cls = e & 1, e2 = e >> 1; + const uint8_t* wbase = r3d_tab_at(tw.w[cls], e2); + const int w_ld = tw.w[cls].ld; + const uint16_t* wsb = (const uint16_t*)r3d_tab_at(tw.s[cls], e2); + const int ws_ld = tw.s[cls].ld; + + 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 < MR * (kGroup / 4); i += (WV * kWave)) { + 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 the block's 128 cols x 128 K of the int4 weight (packed nibbles). + for (int i = (int)tid; i < kWaves * 16 * (kGroup / 8); i += (WV * kWave)) { + 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 * kPitch + d] = + *(const uint32_t*)(wbase + (size_t)nn * w_ld / 2 + kt / 2 + 4 * d); + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)r * kPitch; + const uint32_t* wp = s_w + (size_t)(wave * 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], bf[8]; +#pragma unroll + for (int g = 0; g < 4; ++g) ain[g] = ap[k / 4 + g]; + r3d_e4m3x16_decode<0>(s_tbl, ain, af); + // Decode the 16 packed int4 weights of this k tile to f16, two per word (as af[8]). + const uint2 wq = *(const uint2*)(wp + k / 8); // 8 bytes = 16 nibbles +#pragma unroll + for (int g = 0; g < 8; ++g) { + const uint32_t byte = (g < 4) ? ((wq.x >> (8 * g)) & 0xFFu) + : ((wq.y >> (8 * (g - 4))) & 0xFFu); + const _Float16 h0 = (_Float16)(float)nib_i8(byte & 0xFu); // weight 2g + const _Float16 h1 = (_Float16)(float)nib_i8((byte >> 4) & 0xFu); // weight 2g+1 + bf[g] = (uint32_t)__builtin_bit_cast(uint16_t, h0) + | ((uint32_t)__builtin_bit_cast(uint16_t, h1) << 16); + } + 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 128-block's scales: (sub * scale_a[src][b]) * scale_w[e][n][b], libref's order. + const float sw = bf16_f32(wsb[(size_t)n_real * ws_ld + 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) * as_ld + 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] = f32_to_bf16(acc[g]); } } } @@ -164,29 +300,55 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_w4a8_kernel( extern "C" { +/* moe_gemm_q dtype w4a8: the grouped int4 GEMM. The arm is picked by the activation dtype (int8 -> + * the exact i32 wave-matrix; E4M3 -> the f16 wave-matrix, libr4d's form). The weight scale is bf16 + * and the output bf16 in both arms. */ 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]); + R3dMoeCall c; + int rc = r3d_moe_call(a, true, &c); + if (rc != RAD_OK) return rc; + if (!c.a_scale) return R3D_NO(RAD_E_INVAL); + if (c.a->dtype != RAD_I8 && c.a->dtype != RAD_F8E4M3) return R3D_NO(RAD_E_DTYPE); + if (c.a_scale->dtype != RAD_F32 || c.y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (c.K % kGroup) return R3D_NO(RAD_E_SHAPE); // the N tail clamps - 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); + R3dMoeTabs tw; + rc = r3d_moe_q_tabs(c, RAD_I4, 4, RAD_BF16, 16, c.N, c.K / kGroup, &tw); + if (rc != RAD_OK) return rc; + const int a_ld = (int)c.a->stride[0], as_ld = (int)c.a_scale->stride[0]; + const int y_ld = (int)c.y->stride[0]; + + + const int32_t* ps = (const int32_t*)r3d_p(c.sorted); + const int32_t* po = (const int32_t*)r3d_p(c.off); + const float* psa = (const float*)r3d_p(c.a_scale); + uint16_t* py = (uint16_t*)r3d_wp(c.y); + const int mrows = r3d_geti_or(a, "mrows", 16); + const int wv = r3d_geti_or(a, "wv", 8); + const int ctile = wv * 16; + dim3 grid((unsigned)((c.N + ctile - 1) / ctile), (unsigned)((c.T + mrows - 1) / mrows)), blk(wv * kWave); + if (c.a->dtype == RAD_I8) { + const int8_t* pa8 = (const int8_t*)r3d_p(c.a); + if (mrows == 8 && wv == 4) + moe_w4a8_i8_kernel<8,4><<>>( pa8, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else if (mrows == 8) + moe_w4a8_i8_kernel<8,8><<>>( pa8, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else if (wv == 4) + moe_w4a8_i8_kernel<16,4><<>>( pa8, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else + moe_w4a8_i8_kernel<16,8><<>>( pa8, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + } else { + const uint8_t* pa8 = (const uint8_t*)r3d_p(c.a); + if (mrows == 8 && wv == 4) + moe_w4a8_e4m3_kernel<8,4><<>>( pa8, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else if (mrows == 8) + moe_w4a8_e4m3_kernel<8,8><<>>( pa8, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else if (wv == 4) + moe_w4a8_e4m3_kernel<16,4><<>>( pa8, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + else + moe_w4a8_e4m3_kernel<16,8><<>>( pa8, psa, ps, po, tw, py, (int)c.T, (int)c.N, (int)c.K, a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); + } return (int)hipGetLastError(); } diff --git a/libr3d/r3d_ngram_ids.hip b/libr3d/r3d_ngram_ids.hip new file mode 100644 index 00000000..5ce74d1a --- /dev/null +++ b/libr3d/r3d_ngram_ids.hip @@ -0,0 +1,166 @@ +// r3d_ngram_ids.hip -- the hashed row ids of Qwen4-Exp's Per-Layer Embedding. +// +// mixed(k) = t0*mult[0] ^ t1*mult[1] ^ ... ^ tk*mult[k] int64, wrapping +// ids[h] = mixed(b+1) % vocab_sizes[h] + offsets[h] h in block b +// +// One thread a token, looping its heads. +#include +#include +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +namespace { + +__device__ __forceinline__ long long ng_wrap_mul(long long a, long long b) { + return (long long)((unsigned long long)a * (unsigned long long)b); +} +__device__ __forceinline__ long long ng_floor_mod(long long a, long long b) { + const long long r = a % b; + return r < 0 ? r + b : r; +} + +enum { kNgMaxShift = 8, kNgThreads = 256 }; + +__global__ __launch_bounds__(kNgThreads) void r3d_ngram_ids_kernel( + const int32_t* __restrict__ tok, int32_t* __restrict__ state, + const int32_t* __restrict__ cu, const long long* __restrict__ mult, + const long long* __restrict__ vsz, const long long* __restrict__ off, + const int32_t* __restrict__ sidx, const int32_t* __restrict__ hini, + const int32_t* __restrict__ nacc, int32_t* __restrict__ ids, + uint32_t heads, uint32_t ngram, uint32_t per, uint32_t W, + long long eos, uint32_t ids_ld, int32_t* __restrict__ ahead, uint32_t n_ahead, + uint32_t ahead_ld) +{ + const uint32_t s = blockIdx.y; + const uint32_t bos = (uint32_t)cu[s]; + const uint32_t eot = (uint32_t)cu[s + 1]; + const uint32_t ctx = ngram - 1u; + if (eot <= bos) return; + const int32_t slot = sidx ? sidx[s] : (int32_t)s; + if (slot < 0) return; + + const uint32_t slen = eot - bos; + const bool warm = !hini || hini[s] != 0; + const long long o = nacc ? (long long)nacc[s] - 1 : 0; + const uint32_t lt = blockIdx.x * kNgThreads + threadIdx.x; + + const uint32_t reach = slen + ((ahead && s + 1u == gridDim.y) ? n_ahead : 0u); + if (lt < reach) { + const uint32_t t = bos + lt; + long long prev[kNgMaxShift]; + for (uint32_t i = 0; i < ctx; ++i) + prev[i] = warm ? (long long)state[(long long)slot * W + o + i] : eos; + + const uint32_t p = ctx + lt; + long long sh[kNgMaxShift]; + sh[0] = (long long)tok[t]; + bool cut = false; + for (uint32_t k = 1; k < ngram; ++k) { + if (cut || sh[k - 1] == eos) { cut = true; sh[k] = eos; continue; } + const uint32_t q = p - k; + sh[k] = q < ctx ? prev[q] : (long long)tok[bos + (q - ctx)]; + } + + long long mixed = 0; + int blk = -1; + for (uint32_t k = 0; k < ngram; ++k) { + const long long term = ng_wrap_mul(sh[k], mult[k]); + mixed = k == 0 ? term : (mixed ^ term); + if (k == 0) continue; + ++blk; + int32_t* const row = lt < slen ? ids + (long long)t * ids_ld + : ahead + (long long)(lt - slen) * ahead_ld; + for (uint32_t j = 0; j < per; ++j) { + const uint32_t h = (uint32_t)blk * per + j; + row[h] = (int32_t)(ng_floor_mod(mixed, vsz[h]) + off[h]); + } + } + } + + __syncthreads(); + if (blockIdx.x != 0 || threadIdx.x != 0) return; + int32_t* const win = state + (long long)slot * W; + if (nacc) { + for (uint32_t k = 0; k + 1 < ctx; ++k) + win[k] = warm ? win[o + k + 1] : (int32_t)eos; + for (uint32_t t = 0; t < slen && ctx - 1u + t < W; ++t) win[ctx - 1u + t] = tok[bos + t]; + return; + } + long long keep[kNgMaxShift]; + for (uint32_t k = 0; k < ctx; ++k) { + const long long src = (long long)slen - (long long)ctx + (long long)k; + keep[k] = src >= 0 ? (long long)tok[bos + src] + : (warm ? (long long)win[o + src + ctx] : eos); + } + for (uint32_t k = 0; k < ctx; ++k) win[k] = (int32_t)keep[k]; +} + +} // namespace + +enum { NG_TOK = 0, NG_STATE, NG_CU, NG_MULT, NG_VSZ, NG_OFF, NG_CIDX, NG_HINIT, NG_NACC, NG_IDS, + NG_AHEAD }; + +extern "C" int r3d_rad_ngram_ids(const RadArgs* a, RadStream s) +{ + const RadTensor* tok = r3d_opt(a, NG_TOK); + const RadTensor* st = r3d_opt(a, NG_STATE); + const RadTensor* cu = r3d_opt(a, NG_CU); + const RadTensor* mult = r3d_opt(a, NG_MULT); + const RadTensor* vsz = r3d_opt(a, NG_VSZ); + const RadTensor* off = r3d_opt(a, NG_OFF); + const RadTensor* cidx = r3d_opt(a, NG_CIDX); + const RadTensor* hini = r3d_opt(a, NG_HINIT); + const RadTensor* nacc = r3d_opt(a, NG_NACC); + const RadTensor* ids = r3d_opt(a, NG_IDS); + const RadTensor* ahd = r3d_opt(a, NG_AHEAD); + if (!r3d_p(tok) || !r3d_wp(st) || !r3d_p(cu) || !r3d_p(mult) || + !r3d_p(vsz) || !r3d_p(off) || !r3d_wp(ids)) return R3D_NO(RAD_E_INVAL); + if (tok->dtype != RAD_I32 || st->dtype != RAD_I32 || ids->dtype != RAD_I32) + return R3D_NO(RAD_E_DTYPE); + if (cu->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + if (mult->dtype != RAD_I64 || vsz->dtype != RAD_I64 || off->dtype != RAD_I64) + return R3D_NO(RAD_E_DTYPE); + + const long long M = r3d_geti_or(a, "M", 0); + const long long heads = r3d_geti_or(a, "heads", 0); + const long long ngram = r3d_geti_or(a, "ngram", 0); + const long long eos = r3d_geti_or(a, "eos", -1); + if (M <= 0 || heads <= 0 || ngram < 2 || eos < 0) return R3D_NO(RAD_E_SHAPE); + if (ngram > kNgMaxShift) return R3D_NO(RAD_E_UNSUPPORTED); + if (heads % (ngram - 1)) return R3D_NO(RAD_E_SHAPE); + const long long per = heads / (ngram - 1), ctx = ngram - 1; + + const long long T = ids->rank >= 1 ? ids->shape[0] : M; + const long long ids_ld = ids->rank >= 2 ? ids->stride[0] : heads; + + long long A = 0, ahead_ld = heads; + if (ahd && r3d_p(ahd)) { + if (ahd->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + A = ahd->rank >= 1 ? ahd->shape[0] : 0; + ahead_ld = ahd->rank >= 2 ? ahd->stride[0] : heads; + } + if ((long long)tok->shape[0] < T + A) return R3D_NO(RAD_E_SHAPE); + if ((long long)mult->shape[0] < ngram || (long long)vsz->shape[0] < heads || + (long long)off->shape[0] < heads) return R3D_NO(RAD_E_SHAPE); + + const long long N = (long long)cu->shape[0] - 1; + if (N <= 0) return R3D_NO(RAD_E_SHAPE); + const long long W = st->rank >= 2 ? st->shape[st->rank - 1] : ctx; + if (W < ctx) return R3D_NO(RAD_E_SHAPE); + + const uint32_t tiles = (uint32_t)((T + A + kNgThreads - 1) / kNgThreads); + dim3 grid(tiles, (uint32_t)N), blk(kNgThreads); + R3D_KLAUNCH(r3d_ngram_ids_kernel, grid, blk, (hipStream_t)s, + (const int32_t*)r3d_p(tok), (int32_t*)r3d_wp(st), + (const int32_t*)r3d_p(cu), (const long long*)r3d_p(mult), + (const long long*)r3d_p(vsz), (const long long*)r3d_p(off), + cidx ? (const int32_t*)r3d_p(cidx) : nullptr, + hini ? (const int32_t*)r3d_p(hini) : nullptr, + nacc ? (const int32_t*)r3d_p(nacc) : nullptr, + (int32_t*)r3d_wp(ids), (uint32_t)heads, (uint32_t)ngram, + (uint32_t)per, (uint32_t)W, eos, (uint32_t)ids_ld, + A > 0 ? (int32_t*)r3d_p(ahd) : nullptr, (uint32_t)A, + (uint32_t)ahead_ld); + return (int)hipGetLastError(); +} diff --git a/libr3d/r3d_plugin.h b/libr3d/r3d_plugin.h index b074fadf..24057348 100644 --- a/libr3d/r3d_plugin.h +++ b/libr3d/r3d_plugin.h @@ -215,6 +215,15 @@ 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_moe_gemm_w4a4.hip: the grouped GEMM with int4-weights / int4-activation experts. */ +int r3d_rad_moe_gemm_w4a4(const RadArgs* a, RadStream s); +int r3d_rad_dequant_w4(const RadArgs* a, RadStream s); +int r3d_rad_row_topk_merge(const RadArgs* a, RadStream s); +int r3d_rad_ngram_ids(const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_bias_fp8(const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_short_fp8(const RadArgs* a, RadStream s); +int r3d_rad_moe_gemm_q_mod4(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); diff --git a/libr3d/r3d_rows.cpp b/libr3d/r3d_rows.cpp index 8b197d85..0d0c00b6 100644 --- a/libr3d/r3d_rows.cpp +++ b/libr3d/r3d_rows.cpp @@ -359,6 +359,10 @@ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_ P_STR("dtype"), P_INTO("N_odd"), P_INTO("K_odd"), P_INTO("parts") }; +/* moe_gemm_q dtype w4a8: the grouped int4 GEMM (r3d_moe_gemm_w4a8.hip) is a row of the moe_gemm_q + * op above (two's-complement int4 experts, a bf16 scale per (row, 128 of K), bf16 out; the int8 or + * E4M3 activation arm is picked by `a`'s dtype). It reuses moe_gemm_q's nine-operand parity schema. */ + /* moe_gemm: the grouped GEMM with unquantised experts, libref's schema; one weight table. */ static const RadOperandSpec oMoeGemm[] = { { "a", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WTAB, 0 }, @@ -517,6 +521,57 @@ static const RadOperandSpec oRmsQuantFp8[] = { { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 } }; +/* --- new Tier-1 ops --- */ +static const RadParamSpec pDequantW4[] = { P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype"), + P_INT("twos") }; +static const RadOperandSpec oDequantW4[] = { { "wq", RAD_OPD_WEIGHT, 0 }, + { "ws", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"), + P_STR("dtype") }; +static const RadOperandSpec oRowTopkMerge[] = { { "gathered", RAD_OPD_IN, 0 }, + { "idx", RAD_OPD_OUT, 0 }, + { "val", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pNgramIds[] = { P_INT("M"), P_INT("heads"), P_INT("ngram"), P_INT("eos") }; +static const RadOperandSpec oNgramIds[] = { { "tok", RAD_OPD_IN, 0 }, + { "state", RAD_OPD_INOUT, 0 }, + { "cu", RAD_OPD_IN, 0 }, + { "mult", RAD_OPD_WEIGHT, 0 }, + { "vocab_sizes", RAD_OPD_WEIGHT, 0 }, + { "offsets", RAD_OPD_WEIGHT, 0 }, + { "cache_idx", RAD_OPD_IN, 1 }, + { "has_init", RAD_OPD_IN, 1 }, + { "num_accepted", RAD_OPD_IN, 1 }, + { "ids", RAD_OPD_OUT, 0 }, + { "ahead_ids", RAD_OPD_OUT, 1 } }; +static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype") }; +static const RadOperandSpec oGemmQBias[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "bias", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pGemmQShort[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), + P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"), + P_INTO("split_n"), P_INTO("w_rb") }; +static const RadOperandSpec oGemmQShort[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 1 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, + { "a_sum", RAD_OPD_IN, 1 }, + { "b_ref", RAD_OPD_WEIGHT, 1 } }; +static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K"), + P_INT("n_expert"), P_INT("top_k"), P_INT("group"), + P_STR("a_order"), P_STR("dtype"), P_INTO("N_1"), + P_INTO("K_1"), P_INTO("N_2"), P_INTO("K_2"), + P_INTO("N_3"), P_INTO("K_3"), P_INTO("parts") }; +static const RadOperandSpec oMoeGemmQMod4[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 1 }, + { "w", RAD_OPD_WTAB, 0 }, { "w_scale", RAD_OPD_WTAB, 0 }, + { "sorted_tok", RAD_OPD_IN, 0 }, { "expert_offset", RAD_OPD_IN, 0 }, + { "w_1", RAD_OPD_WTAB, 0 }, { "w_1_scale", RAD_OPD_WTAB, 0 }, + { "w_2", RAD_OPD_WTAB, 0 }, { "w_2_scale", RAD_OPD_WTAB, 0 }, + { "w_3", RAD_OPD_WTAB, 0 }, { "w_3_scale", RAD_OPD_WTAB, 0 }, + { "y", RAD_OPD_OUT, 0 } }; + static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm", pRmsNorm, oRmsNorm, "y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wadd` is GemmaRMSNorm's `1 +`, " @@ -765,6 +820,25 @@ static const RadOpSchema kSchemas[] = { "the best `unary + pred[pid] . (hp * succ[cand])` is picked, and becomes the predecessor " "of the next step. `cand`/`unary` have one row per (sequence, step); `anchor` is the " "block's first predecessor, at `m * anchor_stride`."), + + SCHEMA("dequant_w4", pDequantW4, oDequantW4, + "Packed int4 weight to row-major bf16. Each 32-bit word holds 8 codes; the scale is " + "f16 in the low 16 bits, the zero point -(1024+zero) as f16 in the high 16 bits."), + SCHEMA("row_topk_merge", pRowTopkMerge, oRowTopkMerge, + "Top-R of gathered per-rank candidate sets. Each rank contributes a sorted list; the " + "merge selects the top-R global candidates by score."), + SCHEMA("ngram_ids", pNgramIds, oNgramIds, + "Hashed n-gram row ids for PLE. The FNV-1a mix over the ngram-1 token window is " + "folded into each head's embedding table; per, W and the ids pitch derive from the " + "operands, and `eos` cuts the hash window."), + SCHEMA("gemm_nt_q_bias", pGemmQBias, oGemmQBias, + "Narrow fp8 GEMM (M <= 16) with per-column bf16 bias fused into the epilogue."), + SCHEMA("gemm_nt_q_short", pGemmQShort, oGemmQShort, + "Narrow fp8 GEMM (M <= 16) for short-prompt decode, unsplit K."), + SCHEMA("moe_gemm_q_mod4", pMoeGemmQMod4, oMoeGemmQMod4, + "Grouped GEMM over the expert-sorted rows, quantised operands, four classes by " + "expert number mod 4. The E4M3 wave-matrix core over 8 R3dTab tables (class q = " + "entry e/4 of tables q); unequal class shapes are refused."), }; extern "C" int rad_kernel_schema_count(void) { @@ -816,6 +890,12 @@ static const int64_t kImpl3[] = { 0, 1, 2 }; static const int64_t kImpl4[] = { 0, 1, 2, 3 }; /* The MoE GEMM's row block: 16 (decode), 32, 64 (a tall prefill). A taller block reads the weight * T/mrows times, so the tune picks per shape; 64 is the untuned default (the tall band's best). */ +static const int64_t kMrowsMoE[] = { 8, 16 }; +static const int64_t kWvMoE[] = { 4, 8 }; +static const RadTunable tMoeGemmQW4[] = { + { "mrows", kMrowsMoE, NELEM(kMrowsMoE), 16, "rows per block: 8 for decode, 16 for prefill" }, + { "wv", kWvMoE, NELEM(kWvMoE), 8, "waves per block: 8 = 128-col tile, 4 = 64-col tile" }, +}; static const int64_t kMrows[] = { 16, 32, 64 }; static const RadTunable tMoeGemm[] = { { "mrows", kMrows, NELEM(kMrows), 64, "the block's row count; the weight is read T/mrows times" }, @@ -1079,6 +1159,12 @@ static const RadConstraint cActSigmoid[] = { C_IN("act", "sigmoid"), C_IN("dtype /* A fill row is its dtype; the value is a parameter, and every dtype takes every value. */ static const RadConstraint cFillBf16[] = { C_IN("dtype", "bf16") }; static const RadConstraint cFillF32[] = { C_IN("dtype", "f32") }; +static const RadConstraint cDequantW4[] = { C_DIV("N", 16), C_DIV("K", 64) }; +static const RadConstraint cRowTopkMerge[] = { C_GE("R", 1), C_LE("R", 32) }; +static const RadConstraint cNgramIds[] = { C_GE("ngram", 2), C_LE("ngram", 8) }; +static const RadConstraint cGemmQBias[] = { C_IN("dtype", "fp8a8"), C_GE("M", 1), C_LE("M", 16) }; +static const RadConstraint cGemmQShort[] = { C_IN("dtype", "fp8a8"), C_GE("M", 1), C_LE("M", 64) }; +static const RadConstraint cMoeGemmQMod4[] = { C_GE("n_expert", 4) }; static const RadConstraint cFillI32[] = { C_IN("dtype", "i32") }; static const RadConstraint cFillI64[] = { C_IN("dtype", "i64") }; @@ -1196,6 +1282,10 @@ static const RadConstraint cMoeGemmQ[] = { C_IN("dtype", "fp8a8f32"), C_GE("n_ex C_GE("top_k", 1) }; static const RadConstraint cMoeGemmMxfp4[] = { C_IN("dtype", "mxfp4a8"), C_GE("n_expert", 1), C_GE("top_k", 1) }; +static const RadConstraint cMoeGemmQW4A8[] = { C_IN("dtype", "w4a8"), C_GE("n_expert", 1), + C_GE("top_k", 1) }; +static const RadConstraint cMoeGemmW4A4[] = { C_IN("dtype", "w4a4"), C_GE("n_expert", 1), + C_GE("top_k", 1) }; static const RadConstraint cMoeGather[] = { C_GE("M", 1), C_GE("n", 1), C_GE("top_k", 1), C_IN("dtype", "bf16") }; /* No constraint on `n_local`: it is optional, and a band that leaves it out (every expert local) @@ -2127,6 +2217,129 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, nullptr, nullptr, nullptr }, + /* ------------------------------------------------------------------ r3d_moe_gemm_w4a8.hip + * + * The grouped int4 GEMM: the two's-complement int4 weight (nibbles, -8..7) against an int8 or + * E4M3 activation, one 128-block of K per scale fold. The int8 arm runs the exact i32 wave-matrix + * (no f16 rounding); the E4M3 arm the f16 wave-matrix (libr4d's form). A row of moe_gemm_q, + * selected by dtype=w4a8; the even experts in `w` / `w_scale`, the odd in `w_odd` / `w_odd_scale`. + */ + { "moe_gemm_w4a8", "moe_gemm_q", "moe", + "The grouped int4 GEMM over the expert-sorted rows: y[i] = a[sorted_tok[i]/top_k] @ w_e^T, e the " + "expert of sorted row i; the two's-complement int4 weight (nibbles, -8..7) against an int8 or " + "E4M3 activation, one 128-block of K per scale fold", + "16 sorted rows per block, eight waves of 16 columns; the block walks its expert runs, the " + "padding rows reading the run's first; the decode band (M * top_k <= 16 the tuned point, more " + "runs as extra 16-row blocks, prefill falls back to libavx); K % 128, N % 64; the even experts " + "are entry e/2 of `w` / `w_scale`, the odd of `w_odd` / `w_odd_scale`; token or sorted a", + "I4 (packed, two a byte) weight tables with a bf16 w_scale per (row, 128 of K); int8 a (an f32 " + "a_scale per (row, 128 of K)) or E4M3 a (an f32 a_scale); bf16 y in sorted order; the int8 arm is " + "bit-exact against the reference, the E4M3 arm to the f16 store ulp", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeGemmQW4A8), tMoeGemmQW4, NELEM(tMoeGemmQW4), nullptr, + nullptr, nullptr, r3d_rad_moe_gemm_w4a8, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + /* ------------------------------------------------------------------ r3d_moe_gemm_w4a4.hip + * + * The grouped int4xint4 GEMM: the two's-complement int4 weight AND int4 activation, one 128-block + * of K per scale fold. Both are widened to int8 and run on the exact i32 wave-matrix (no f16 + * rounding). A row of moe_gemm_q, selected by dtype=w4a4; the even experts in `w` / `w_scale`, the + * odd in `w_odd` / `w_odd_scale`. + */ + { "moe_gemm_w4a4", "moe_gemm_q", "moe", + "The grouped int4xint4 GEMM over the expert-sorted rows: y[i] = a[sorted_tok[i]/top_k] @ w_e^T, e " + "the expert of sorted row i; the two's-complement int4 weight and int4 activation, one 128-block " + "of K per scale fold", + "16 sorted rows per block, eight waves of 16 columns; the block walks its expert runs, the " + "padding rows reading the run's first; the decode band (M * top_k <= 16 the tuned point, more " + "runs as extra 16-row blocks, prefill falls back to libavx); K % 128, N % 64; the even experts " + "are entry e/2 of `w` / `w_scale`, the odd of `w_odd` / `w_odd_scale`; token or sorted a", + "I4 (packed, two a byte) weight tables with a bf16 w_scale per (row, 128 of K); int4 a (packed, " + "two a byte, an f32 a_scale per (row, 128 of K)); bf16 y in sorted order; bit-exact against the " + "reference", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeGemmW4A4), tMoeGemmQW4, NELEM(tMoeGemmQW4), nullptr, + nullptr, nullptr, r3d_rad_moe_gemm_w4a4, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + /* ------------------------------------------------------------------ r3d_dequant_w4_bf16.hip + * + * The packed 4-bit weight back to a plain row-major bf16 [N, K], for the prefill path where + * W4A8 gains nothing. + */ + { "dequant_w4_bf16", "dequant_w4", "quant", + "The packed 4-bit weight back to a plain row-major bf16 [N, K]", + "One thread per packed dword scatters its eight nibbles to row-major bf16; the scale dword holds " + "the f16 scale low and -(1024+zero) high; N % 16, K % 64, group divides K", + "I4 (packed, two a byte) wq with an f16 ws scale per (row, group); bf16 y [N, K]; twos 1 = " + "symmetric two's-complement nibble, 0 = asymmetric unsigned nibble minus a per-group zero", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDequantW4), NOTUNE, + nullptr, nullptr, r3d_rad_dequant_w4, + nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + + { "rowtopk_merge", "row_topk_merge", "select", + "The R largest of the all-gathered per-rank candidate sets, one wave per row", + "One wave per row over world_size * R pairs; tk_insert into a 32-slot top-R heap, tk_round " + "extracts via a 5-step xor-butterfly; ties break on the lower id; R <= 32", + "f32 g (M * world_size * R * 2), i32 idx (M * R), f32 val (M * R); R <= 32", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRowTopkMerge), NOTUNE, + nullptr, nullptr, r3d_rad_row_topk_merge, + nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + + { "ngram_ids_i32", "ngram_ids", "vocab", + "The hashed row ids of the Per-Layer Embedding: mixed(k) = XOR of t_s * mult[s], " + "ids[h] = mixed % vocab_sizes[h] + offsets[h]", + "One thread a token, looping its heads; n-gram shifts with EOS walk; 64-bit wrapping " + "multiply and floor-mod; ngram <= 8, heads divisible by (ngram-1)", + "i32 tok, i32 state, i32 cu, i64 mult, i64 vsz, i64 off, i32 ids; " + "optional i32 cidx, hini, nacc, ahead", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cNgramIds), NOTUNE, + nullptr, nullptr, r3d_rad_ngram_ids, + nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + + { "gemm_nt_q_bias_fp8a8_m16", "gemm_nt_q_bias", "gemm", + "The narrow fp8 GEMM with a per-column bias epilogue: y = a @ b^T + bias", + "M <= 16, K a multiple of the block; fp8a8 codes and scales, bf16 bias and output; " + "GEMM then bias-add in two passes", + "fp8_e4m3 a and b, f32 scales, bf16 bias [N], bf16 y [M,N]", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQBias), tGemmM16, NELEM(tGemmM16), nullptr, + nullptr, nullptr, r3d_rad_gemm_nt_q_bias_fp8, + nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + + { "gemm_nt_q_short_fp8a8_m16", "gemm_nt_q_short", "gemm", + "The narrow fp8 GEMM with the short-prompt split rule: unsplit at N <= 512, K <= 5120, " + "41..64 rows", + "M <= 64, K a multiple of 128, N a multiple of 16; fp8a8 codes and scales, bf16 output; " + "sk=1 forced (no split)", + "fp8_e4m3 a and b, f32/bf16 scales, bf16 y [M,N]", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQShort), tGemmM16, NELEM(tGemmM16), nullptr, + nullptr, nullptr, r3d_rad_gemm_nt_q_short_fp8, + nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + + { "moe_gemm_q_mod4_e4m3", "moe_gemm_q_mod4", "moe", + "The grouped quantised GEMM with 4 expert classes: y[i] = a[sorted_tok[i]/top_k] @ w_e^T, " + "e%4 picks the class", + "same as moe_gemm_q_e4m3 but 4-class routing; group = 128; the class shapes default to N/K " + "and an unequal N_1..K_3 is refused; token or sorted a", + "E4M3 a and weight tables (4 classes), f32 a_scale and w_scale; y bf16 in sorted order", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeGemmQMod4), tMoeGemmQW4, NELEM(tMoeGemmQW4), nullptr, + nullptr, nullptr, r3d_rad_moe_gemm_q_mod4, + nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + /* ------------------------------------------------------------------ r3d_gdn_recurrent_update_k128_v128.hip * * The gated-delta-net recurrent state update at decode: the per-token state step against a paged diff --git a/libr3d/r3d_rowtopk_merge.hip b/libr3d/r3d_rowtopk_merge.hip new file mode 100644 index 00000000..0dd8e42e --- /dev/null +++ b/libr3d/r3d_rowtopk_merge.hip @@ -0,0 +1,112 @@ +// r3d_rowtopk_merge.hip -- row_topk_merge: the R largest of the all-gathered per-rank candidate +// sets. One wave per row over world_size * R pairs; the cost is its launch, it only has to be +// exact. +#include +#include +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#define R3D_TOPK_WAVE 32 +#define R3D_TOPK_PT2 32 // >= R, so a lane can hold the whole answer + +__device__ __forceinline__ unsigned long long r3d_tk_key_f32(float v, unsigned idx) { + unsigned fu = __float_as_uint(v); + fu = (fu & 0x80000000u) ? ~fu : (fu | 0x80000000u); + return ((unsigned long long)fu << 32) | (unsigned)(0xFFFFFFFFu - idx); +} + +__device__ __forceinline__ float r3d_tk_val(unsigned long long k) { + unsigned u = (unsigned)(k >> 32); + u = (u & 0x80000000u) ? (u & 0x7FFFFFFFu) : ~u; + return __uint_as_float(u); +} + +__device__ __forceinline__ int r3d_tk_idx(unsigned long long k) { + return (int)(0xFFFFFFFFu - (unsigned)(k & 0xFFFFFFFFull)); +} + +template +__device__ __forceinline__ unsigned long long r3d_tk_xor_max(unsigned long long m) { + const unsigned long long p = r3d_xor_lane_u64(m); + return p > m ? p : m; +} + +template +__device__ __forceinline__ void r3d_tk_insert(unsigned long long* t, unsigned long long k) { + if (k > t[PT - 1]) { + unsigned long long c = k; +#pragma unroll + for (int q = 0; q < PT; q++) { + const unsigned long long hi = t[q] > c ? t[q] : c; + c = t[q] > c ? c : t[q]; + t[q] = hi; + } + } +} + +template +__device__ __forceinline__ unsigned long long r3d_tk_round(unsigned long long* t) { + unsigned long long m = t[0]; + m = r3d_tk_xor_max<16>(m); + m = r3d_tk_xor_max<8>(m); + m = r3d_tk_xor_max<4>(m); + m = r3d_tk_xor_max<2>(m); + m = r3d_tk_xor_max<1>(m); + if (m == t[0]) { + // Drop the head and re-sort: shift the rest down, 0 at the tail. +#pragma unroll + for (int q = 0; q < PT - 1; q++) t[q] = t[q + 1]; + t[PT - 1] = 0ull; + } + return m; +} + +__global__ __launch_bounds__(R3D_TOPK_WAVE) void r3d_rowtopk_merge_kernel( + const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) +{ + const int m = blockIdx.x; + const int lane = threadIdx.x; + + unsigned long long t[R3D_TOPK_PT2]; +#pragma unroll + for (int q = 0; q < R3D_TOPK_PT2; q++) t[q] = 0ull; + + const float* const row = G + (size_t)m * n * 2; + for (int i = lane; i < n; i += R3D_TOPK_WAVE) { + int id; + __builtin_memcpy(&id, row + (size_t)i * 2, sizeof(int)); + if (id < 0) continue; + r3d_tk_insert(t, r3d_tk_key_f32(row[(size_t)i * 2 + 1], (unsigned)id)); + } + + for (int r = 0; r < R; r++) { + const unsigned long long w = r3d_tk_round(t); + if (lane == 0) { + OV[(size_t)m * R + r] = w ? r3d_tk_val(w) : -INFINITY; + OI[(size_t)m * R + r] = w ? r3d_tk_idx(w) : -1; + } + } +} + +extern "C" int r3d_rad_row_topk_merge(const RadArgs* a, RadStream s) +{ + const RadTensor* g = r3d_opt(a, 0); + const RadTensor* idx = r3d_opt(a, 1); + const RadTensor* val = r3d_opt(a, 2); + if (!r3d_p(g) || !r3d_p(idx) || !r3d_wp(val)) return R3D_NO(RAD_E_INVAL); + if (g->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); + + const long long M = (g->rank >= 1) ? g->shape[0] : r3d_geti_or(a, "M", 0); + const long long R = r3d_geti_or(a, "R", 0); + const long long W = r3d_geti_or(a, "world_size", 0); + if (M < 1 || R < 1 || W < 1) return R3D_NO(RAD_E_SHAPE); + if (R > 32) return R3D_NO(RAD_E_SHAPE); + + dim3 grid((unsigned)M), blk(R3D_TOPK_WAVE); + R3D_KLAUNCH(r3d_rowtopk_merge_kernel, grid, blk, (hipStream_t)s, + (const float*)r3d_p(g), (float*)r3d_wp(val), (int*)r3d_wp(idx), + (int)R, (int)(W * R)); + return (int)hipGetLastError(); +} diff --git a/libr3d/r3d_selftest.cpp b/libr3d/r3d_selftest.cpp index e363ea7a..4e21c65c 100644 --- a/libr3d/r3d_selftest.cpp +++ b/libr3d/r3d_selftest.cpp @@ -1837,7 +1837,7 @@ static int build_moe_gemm_q(Case& c, const RadOpSchema* s) { t = RadTensor{}; t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } - for (int r = 0; r + 1 < qd[o].rank; ++r) t.stride[r] = t.shape[r + 1] * t.stride[r + 1]; + rad_tensor_pack(&t); /* dense row-major: the ascending form computes stride[0] before stride[1] */ } return 0; } @@ -1889,7 +1889,7 @@ static int build_moe_gemm_bf16(Case& c, const RadOpSchema* s) { t = RadTensor{}; t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } - for (int r = 0; r + 1 < qd[o].rank; ++r) t.stride[r] = t.shape[r + 1] * t.stride[r + 1]; + rad_tensor_pack(&t); /* dense row-major: the ascending form computes stride[0] before stride[1] */ } return 0; } @@ -1958,7 +1958,93 @@ static int build_moe_gemm_mxfp4a8(Case& c, const RadOpSchema* s) { t = RadTensor{}; t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } - for (int r = 0; r + 1 < qd[o].rank; ++r) t.stride[r] = t.shape[r + 1] * t.stride[r + 1]; + rad_tensor_pack(&t); /* dense row-major: the ascending form computes stride[0] before stride[1] */ + } + return 0; +} + +/* moe_gemm_q dtype w4a8: an int8 activation (an f32 scale per (row, 128 of K)) and two's-complement + * int4 experts (a bf16 scale per (row, 128 of K)), two stacked weight tables by parity (the even in + * `w` / `w_scale`, the odd in `w_odd` / `w_odd_scale`), token-order a, y bf16. Every sorted row is + * owned (no dropped slots), so the kernel writes all of y; the NaN prefill catches a launch that + * skips rows. */ +static int build_moe_gemm_w4a8(Case& c, const RadOpSchema* s) { + constexpr int NOPD = 9; + const long long M = 6, N = 96, K = 256, NE = 4, TK = 4; // T = 24, six rows per expert + const long long T = M * TK; + const long long ne0 = (NE + 1) / 2, ne1 = NE / 2; + if (s->n_operands != NOPD) { fail("moe_gemm_w4a8: the schema has %d operands, not 9", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "M", RAD_P_INT, M, 0, nullptr, 0.0 }, + { "N", RAD_P_INT, N, 0, nullptr, 0.0 }, + { "K", RAD_P_INT, K, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "group", RAD_P_INT, 128, 0, nullptr, 0.0 }, + { "a_order", RAD_P_STR, 0, 0, (const char*)"token", 0.0 }, + { "dtype", RAD_P_STR, 0, 0, (const char*)"w4a8", 0.0 }, + { "N_odd", RAD_P_INT, N, 0, nullptr, 0.0 }, + { "K_odd", RAD_P_INT, K, 0, nullptr, 0.0 }, + { "parts", RAD_P_INT, 1, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x74A8C0Deu; + auto rnd = [&]() { st = st * 1664525u + 1013904223u; return (st >> 8) & 0xffu; }; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; return 0.5f + ((st >> 8) & 0xff) / 255.0f; }; + auto to_bf16 = [](float f) { return (uint16_t)(__builtin_bit_cast(uint32_t, f) >> 16); }; + std::vector ha((size_t)M * K); + for (auto& x : ha) x = (int8_t)((rnd() & 7) - 4); // -4..4 + std::vector hA((size_t)M * (K / 128)); + for (auto& x : hA) x = rndf(); + // The weight codes and bf16 scales for all NE experts, then split by parity. + std::vector hw((size_t)NE * N * (K / 2)); + for (auto& x : hw) x = (uint8_t)(rnd() & 0xFFu); + std::vector hsce((size_t)NE * N * (K / 128)); + for (auto& x : hsce) x = to_bf16(rndf()); + std::vector hs(T), ho(NE + 1); + for (long long i = 0; i < T; ++i) hs[i] = (int32_t)i; + for (long long e = 0; e < NE; ++e) ho[e] = (int32_t)(e * (T / NE)); + ho[NE] = (int32_t)T; + std::vector hy((size_t)T * N); + for (auto& x : hy) x = 0x7fc0u; // bf16 NaN prefill + std::vector hwe((size_t)ne0 * N * (K / 2)), hwo((size_t)ne1 * N * (K / 2)); + std::vector hse((size_t)ne0 * N * (K / 128)), hso((size_t)ne1 * N * (K / 128)); + for (long long e = 0; e < NE; ++e) { + const bool odd = e & 1; + const long long ix = e >> 1; + std::memcpy((odd ? hwo.data() : hwe.data()) + (size_t)ix * N * (K / 2), + hw.data() + (size_t)e * N * (K / 2), (size_t)N * (K / 2)); + std::memcpy((odd ? hso.data() : hse.data()) + (size_t)ix * N * (K / 128), + hsce.data() + (size_t)e * N * (K / 128), (size_t)N * (K / 128) * sizeof(uint16_t)); + } + + // The contract's order: a, a_scale, w, w_scale, sorted_tok, expert_offset, w_odd, w_odd_scale, y. + struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[NOPD] = { + { RAD_I8, 2, { M, K, 1 }, M * K }, + { RAD_F32, 2, { M, K / 128, 1 }, M * (K / 128) }, + { RAD_I4, 3, { ne0, N, K }, ne0 * N * K }, + { RAD_BF16, 3, { ne0, N, K / 128 }, ne0 * N * (K / 128) }, + { RAD_I32, 1, { T, 1, 1 }, T }, + { RAD_I32, 1, { NE + 1, 1, 1 }, NE + 1 }, + { RAD_I4, 3, { ne1, N, K }, ne1 * N * K }, + { RAD_BF16, 3, { ne1, N, K / 128 }, ne1 * N * (K / 128) }, + { RAD_BF16, 2, { T, N, 1 }, T * N } }; + const uint32_t bits_of[NOPD] = { 8, 32, 4, 16, 32, 32, 4, 16, 16 }; + const void* src[NOPD] = { ha.data(), hA.data(), hwe.data(), hse.data(), hs.data(), ho.data(), + hwo.data(), hso.data(), hy.data() }; + for (int o = 0; o < NOPD; ++o) { + const size_t bytes = (size_t)((qd[o].nel * bits_of[o] + 7) / 8); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_gemm_w4a8: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (src[o]) std::memcpy(d, src[o], bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; + for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } + rad_tensor_pack(&t); } return 0; } @@ -2100,7 +2186,7 @@ static int build_moe_gather(Case& c, const RadOpSchema* s, int inv) { t = RadTensor{}; t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } - for (int r = 0; r + 1 < qd[o].rank; ++r) t.stride[r] = t.shape[r + 1] * t.stride[r + 1]; + rad_tensor_pack(&t); /* dense row-major: the ascending form computes stride[0] before stride[1] */ } return 0; } @@ -2241,7 +2327,8 @@ static int run_row(int i) { : (0 == std::strcmp(k->name, "moe_gemm_mxfp4a8")) ? 17 : (0 == std::strcmp(k->name, "moe_router_topk_scatter")) ? 18 : (0 == std::strcmp(k->name, "moe_router_sigmoid_topk")) ? 19 - : (0 == std::strcmp(k->name, "moe_gather")) ? 21 : 2; + : (0 == std::strcmp(k->name, "moe_gather")) ? 21 + : (0 == std::strcmp(k->name, "moe_gemm_w4a8")) ? 22 : 2; if (hand == 2) { skip("no operand description, so no buffers to build"); return 0; } const RadOpSchema* s = find_schema(k->op); if (!s) { fail("no schema for '%s'", k->op); return 1; } @@ -2271,6 +2358,7 @@ static int run_row(int i) { : hand == 18 ? build_moe_router_scatter(c, s) : hand == 19 ? build_moe_router_sigmoid(c, s) : hand == 21 ? build_moe_gather(c, s, 0) + : hand == 22 ? build_moe_gemm_w4a8(c, s) : build_gdn_chunk_scan(c, s); if (rc) return 1; goto launched; @@ -2772,6 +2860,7 @@ static void check_moe_numerics() { else compare(what, ref, y, 1e-2); } } + } #endif } diff --git a/libr3d/r3d_vocab_bf16.hip b/libr3d/r3d_vocab_bf16.hip index 336e8db8..17c86983 100644 --- a/libr3d/r3d_vocab_bf16.hip +++ b/libr3d/r3d_vocab_bf16.hip @@ -95,9 +95,10 @@ * * ---- refusals ----------------------------------------------------------------------------------- * - * sk > 1: the grid is vocab-wide at every M (1020 blocks at the band for the prefill arm, 8160 for - * the decode arm at MT=16), so a split would buy nothing. kb: KC = 32 only, since another pitch is - * a different swizzle. Also refused: K not a multiple of KC, an x pitch not a multiple of 8, a y + * The grid is vocab-wide at every M (1020 blocks at the band for the prefill arm, 8160 for + * the decode arm at MT=16), so a split would buy nothing: sk = 1 fixed. kb: KC = 32 only, since + * another pitch is a different swizzle. Also refused: K not a multiple of KC, an x pitch not a + * multiple of 8, a y * pitch not a multiple of 4 (f32) or 8 (bf16), a non-contiguous weight. The head branch, in order: * a quantised head on the bf16-y row (logits are f32) * a `zero` plane: codes+scale+zero is gemm_nt_q's asymmetric grid (r3d_gemm_nt_q_w2a8.hip) @@ -113,7 +114,7 @@ * planes that do not cover the band (codes N x K, scales ceil(N/128) x ceil(K/128)), or a * row_bytes shorter than the row * The bf16 branch refuses a plain head that is not bf16, wrong x and y dtypes, bad pitches, a short - * or non-contiguous head, absurd shapes, misalignment and sk > 1. The launcher refuses a head with + * or non-contiguous head, absurd shapes and misalignment. The launcher refuses a head with * a null plane, a dtype outside the served set, a row pitch a vector load cannot walk (a 16-bit * scale row is 2 bytes a column, so K = 320, 6 bytes a row, is legal), and misaligned addresses. */ @@ -664,10 +665,9 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, if (!r3d_aligned(r3d_p(x), 16) || !r3d_aligned(r3d_p(w), 16) || !r3d_aligned(r3d_p(y), 16)) return R3D_NO(RAD_E_ALIGN); - const int sk = (int)r3d_geti_or(a, "sk", 1); - if (sk > 1) return R3D_NO(RAD_E_SHAPE); /* see the header's refusals */ - const int kb = (int)r3d_geti_or(a, "kb", 0); - const int nt = (int)r3d_geti_or(a, "nt", 0); + /* No `sk`/`kb`/`nt` in the rows' tune tables (impl only): the grid is vocab-wide, KC = 32 and + * the non-temporal stream is off, see the header's refusals. */ + const int sk = 1, kb = 0, nt = 0; const HeadQ* hp = joined ? &h : nullptr; const int e = y_is_f32