From dab34da373fc310375ccb6fd03a99b51abf64d1f Mon Sep 17 00:00:00 2001 From: hugypufy Date: Sun, 25 Oct 2026 12:24:02 +0000 Subject: [PATCH] libr4d: gemm_m2xfp4a8_decode and gemm_m2xfp4a8_tiled -- the MXFP4 x fp8 GEMMs with the m2xfp4 meta plane folded into the e4m3 staging table Two gemm_nt_q rows at dtype m2xfp4: a split-K decode kernel that stages the weight through LDS, and a tiled prefill kernel after the mxfp4a8 one. The relayout appends the [K/32][N] meta plane to the fragment-order codes and r4d_m2xfp4.h's e4m3 staging table takes the subgroup multiplier as a second index, so the WMMAs and the epilogue are the mxfp4 kernels'. The decode row keeps its own per-output arrival counters, as mxd_out_ctr does. r4d_emu_m2xfp4 runs both kernels on the host, and r4d_selftest and kbench (a 4e-2 tolerance for the k = 3 rounding) cover the rows. The raw entry points are declared in r4d_m2xfp4.h, beside the table. Co-Authored-By: Claude Opus 5.5 --- libr4d/CMakeLists.txt | 4 + libr4d/r4d_args.h | 5 +- libr4d/r4d_gemm_m2xfp4a8_decode.hip | 647 ++++++++++++++++++++++++++++ libr4d/r4d_gemm_m2xfp4a8_tiled.hip | 362 ++++++++++++++++ libr4d/r4d_layout.cpp | 110 +++++ libr4d/r4d_m2xfp4.h | 129 ++++++ libr4d/r4d_plugin.h | 10 + libr4d/r4d_rows.cpp | 46 ++ libr4d/r4d_selftest.cpp | 147 +++++++ tests/CMakeLists.txt | 22 +- tests/r4d_emu/cfg_stub.cpp | 17 + tests/r4d_emu/emu/hip/hip_runtime.h | 2 + tests/r4d_emu/test_m2xfp4.cpp | 405 +++++++++++++++++ tools/kbench_core.cpp | 4 + 14 files changed, 1901 insertions(+), 9 deletions(-) create mode 100644 libr4d/r4d_gemm_m2xfp4a8_decode.hip create mode 100644 libr4d/r4d_gemm_m2xfp4a8_tiled.hip create mode 100644 libr4d/r4d_m2xfp4.h create mode 100644 tests/r4d_emu/cfg_stub.cpp create mode 100644 tests/r4d_emu/test_m2xfp4.cpp diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index f9d305af..e8084729 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -149,6 +149,10 @@ set(R4D_UNITS "r4d_gemm_mxfp4a8_tiled|" "r4d_gemm_mxfp4a8_decode|" "r4d_gemm_mxfp4a8_gemv|" + # M2XFP4 (arXiv 2601.19213 §4.4.2): the decode and tiled rows at the m2xfp4 encoding, one meta + # plane more. Same bands and fold as the OCP rows; the meta multipliers ride r4d_m2xfp4.h's table. + "r4d_gemm_m2xfp4a8_tiled|" + "r4d_gemm_m2xfp4a8_decode|" # Block-scaled FP8 (the format Qwen3.8-27B-FP8 ships in). The 128x128 block is fixed by the # checkpoint, and the entry points reject a mismatch. "r4d_gemm_fp8a16_nt_m1|" diff --git a/libr4d/r4d_args.h b/libr4d/r4d_args.h index 26118345..d6e004c5 100644 --- a/libr4d/r4d_args.h +++ b/libr4d/r4d_args.h @@ -257,7 +257,10 @@ enum { /* The same GEMM's 5-bit expert weight: per row, R4D_DT_MOEW4's nibble plane of the codes' low * four bits (the magnitude), then the sign bits, one dword per 32 elements in the order the * kernel merges them (r4d_layout.cpp, moew5_row). A row is 5K/8 bytes. */ - R4D_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8 + R4D_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8, + /* The M2XFP4 GEMMs' stored weight: R4D_DT_MXFP4_FRAG's fragment-order e2m1 codes, then the + * [K/32][N] meta plane the kernel reads beside the E8M0 exponents (r4d_layout.cpp, m2xfp4). */ + R4D_DT_M2XFP4_FRAG = RAD_DT_PLUGIN_BASE + 9 }; /* The grouped MoE GEMM's code tables, as the four dwords w4_e4m3's byte permutes read diff --git a/libr4d/r4d_gemm_m2xfp4a8_decode.hip b/libr4d/r4d_gemm_m2xfp4a8_decode.hip new file mode 100644 index 00000000..16dc9214 --- /dev/null +++ b/libr4d/r4d_gemm_m2xfp4a8_decode.hip @@ -0,0 +1,647 @@ +// r4d_gemm_m2xfp4a8_decode.hip - r4d_gemm_m2xfp4a8_decode: the M2XFP4 x fp8 GEMM for the decode +// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout, +// fold and split-K of r4d_gemm_mxfp4a8_decode, and the paper's weight-side Sg-EM (arXiv 2601.19213 +// §4.4.2) on top: per group of 32 K the weight carries, beside its E8M0 exponent (whose adaptive +// bias is already folded in), one meta byte of four two-bit subgroup multipliers k_s. The exact +// weight is e2m1mag[c&7] * sign(c) * 2^(scale-127) * (1 + k_s/4); r4d_m2xfp4.h folds the +// (1 + k_s/4) * 2^-d into the e4m3 byte through a second table index, so the WMMA sees the same +// bytes it would for MXFP4, and the Wref epilogue, the activation scale grids and the split-K +// reduction (fp32 partials, last arriver) are the mxfp4 kernel's; the split and slab rule is +// m2d_plan's own. +// +// The meta byte is staged beside the exponent byte: one byte per (row, 32 of K), in the scale +// plane's [K/32][N] order and row pitch, in the tail of the same stored weight (the relayout +// appends it after the fragment-order codes, r4d_layout.cpp), so the staging reads it with the +// codes' and exponents' own geometry and the weight stream grows by one byte per sixteen. +// +// The fold's bound: Wref[n] is the row's largest exponent byte as for MXFP4, so d >= 0 holds for +// every block, and the largest element any table cell then holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d +// -- an e4m3 normal at every d >= 0 (r4d_m2xfp4.h). +// +// Tile: DWN = 8 waves over 128 output columns and DTM 16-row M fragments; each K slab stages A and +// the 128 weight rows, unpacked to e4m3, in LDS. DKS blocks split the K slabs, each writing an fp32 +// partial [DKS][M][N] to the op's scratch, and the last to arrive on a column block sums them. The +// arrival counters are this row's own, one block per output buffer (m2d_out_ctr), zero at entry +// and reset by the reducer, as mxd_out_ctr is for the mxfp4 row; so the row is concurrent +// (rad_kernel_concurrent) on the same terms. A scratch shorter than the split needs is refused. +#include "r4d.h" +#include "r4d_gemm_args.h" +#include "r4d_common.h" +#include "r4d_m2xfp4.h" + +// bf16 output as uint16 pairs, the emulator-compatible spelling the MoE units use: the OCP rows +// read __hip_bfloat16 from hip_bf16.h, which the emulator's shim does not carry, and the bytes are +// the same -- bf16x2_rne_nan and f32_to_bf16 round as it does (r4d_common.h). +#include +#include +#include +#include + +#define R4D_M2D_DWN 8 // waves per block; the N tile is DWN*16 = 128 wide +#define R4D_M2D_MTILE 16 +#define R4D_M2D_MAX_TM 8 // M <= 128 +#define R4D_M2D_PAD 8 +#define R4D_M2D_MAX_KS 16 +#define R4D_M2D_MAX_N 36864 // the counter block's width; a 27B gate_up at TP=1 is 34816 + +typedef int m2d_v2i __attribute__((ext_vector_type(2))); +typedef unsigned m2d_u2 __attribute__((ext_vector_type(2))); +typedef unsigned m2d_u4 __attribute__((ext_vector_type(4))); +typedef float m2d_f4 __attribute__((ext_vector_type(4))); + +template +static __device__ __forceinline__ T m2d_ld(const T* p) { + if constexpr (NT) return __builtin_nontemporal_load(p); + else return *p; +} + +// ---- shared by both kernels: the scale grid at a 128 boundary, and the epilogue. +// +// The accumulator is C transposed: the WMMA takes the weight fragment as A and the activation as B +// (same register layout), so a lane's accumulator for M fragment i holds one row, m = 16i + col, +// and eight consecutive columns n0 + 16*wave + kb8 + e. A lane needs one activation scale per row, +// and writes its eight outputs as one 16-byte store (one 32-byte store of partials). + +// The (row, 128) scale grid: thread t < ROWS owns row t, loads the next boundary's two scales a +// boundary early and writes s_prev / s_next to LDS at the boundary (published by the staging +// barrier). A zero next block keeps the carried scale; after a zero block the carried scale is +// looked up from the grid. +static __device__ __forceinline__ float m2d_ratio(float ns, float np, const float* __restrict__ row, + int kb) { + return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f; +} + +template +static __device__ __forceinline__ void m2d_rescale(v8f (&acc)[DTM], const float* sR, int col) { +#pragma unroll + for (int i = 0; i < DTM; ++i) { + const float r = sR[i * 16 + col]; +#pragma unroll + for (int e = 0; e < 8; ++e) acc[i][e] *= r; + } +} + +// The split's result: written to C when the accumulator covers all of K, else as an fp32 partial +// that the last block to arrive on this column block sums. `kb_end` is the block the split's last +// slab ends in (ABLK: the scale the accumulators are carried in). +template +static __device__ __forceinline__ void m2d_epilogue( + const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs, + const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt, + uint16_t* __restrict__ C, int M, int N, int ldc, int n0, int wave, int col, int kb8, + int ks, int kb_end, unsigned* s_last, float* sR) { + constexpr int NTHR = R4D_M2D_DWN * 32, BND = R4D_M2D_DWN * 16; + constexpr int ROWS = R4D_M2D_MTILE * DTM; + const int tid = threadIdx.x; + const int nb = n0 + wave * 16 + kb8; // this lane's eight columns; N % 16 == 0 keeps all or none + // Each row's final scale: the one the split's accumulators end in (ABLK), or the row's own. The + // K loop's closing barrier retired the last ratio reads. + if (tid < ROWS) { + const int m = tid < M ? tid : M - 1; + sR[tid] = ABLK ? r4d_mxfp4_carried(As + (size_t)m * as_rs, kb_end) : As[(size_t)m * as_rs]; + } + __syncthreads(); + float sc[DTM]; +#pragma unroll + for (int i = 0; i < DTM; ++i) sc[i] = sR[i * 16 + col]; + if constexpr (DKS == 1) { + if (nb < N) { + const m2d_u2 rb = *(const m2d_u2*)(Wref + nb); + float rf[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) rf[e] = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23); +#pragma unroll + for (int i = 0; i < DTM; ++i) { + const int m = i * 16 + col; + if (m < M) { + // rounded as the bf16 store rounds, packed in whole registers (see bf16x2_rne_nan) + float v[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) + v[e] = ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i]; + m2d_u4 o; + o.x = bf16x2_rne_nan(v[0], v[1]); + o.y = bf16x2_rne_nan(v[2], v[3]); + o.z = bf16x2_rne_nan(v[4], v[5]); + o.w = bf16x2_rne_nan(v[6], v[7]); + *(m2d_u4*)(C + (size_t)m * ldc + nb) = o; + } + } + } + return; + } + if (nb < N) { +#pragma unroll + for (int i = 0; i < DTM; ++i) { + const int m = i * 16 + col; + if (m < M) { + m2d_f4 lo, hi; +#pragma unroll + for (int e = 0; e < 4; ++e) { + lo[e] = ABLK ? acc[i][e] * sc[i] : acc[i][e]; + hi[e] = ABLK ? acc[i][e + 4] * sc[i] : acc[i][e + 4]; + } + m2d_f4* dst = (m2d_f4*)(P + ((size_t)ks * M + m) * N + nb); + dst[0] = lo; + dst[1] = hi; + } + } + } + // Every thread's partial stores are ordered before the counter; then the last arriver reduces. + __threadfence(); + __syncthreads(); + if (tid == 0) + *s_last = __hip_atomic_fetch_add(&cnt[blockIdx.x], 1u, __ATOMIC_ACQ_REL, + __HIP_MEMORY_SCOPE_AGENT); + __syncthreads(); + if (*s_last != (unsigned)(DKS - 1)) return; + if (tid == 0) cnt[blockIdx.x] = 0u; // reset for the next launch + __threadfence(); // acquire, before reading the other partials + const int nhi = min(n0 + BND, N); + for (int nn = n0 + tid; nn < nhi; nn += NTHR) { + const float rf = __int_as_float((int)Wref[nn] << 23); + for (int m = 0; m < M; ++m) { + float sum = 0.f; +#pragma unroll + for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn]; + C[(size_t)m * ldc + nn] = f32_to_bf16(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs])); + } + } +} + +/* Waves per SIMD for each tile shape (R4D_WAVES), by K block, M fragments and scale form: pins + * the register budget the tile was tuned at so a compiler release cannot change occupancy (LLVM 24 + * would drop the DBK 64, three-fragment form from 16 waves to 12). Where a shape spilled at 256 + * VGPRs, the budget is the one it reaches without spilling. The meta adds one global byte per + * staged pair to the fold's inputs and no register to the WMMA chain, so the budgets are the + * mxfp4 decode kernel's; the fold is a second table index, not a multiply. */ +constexpr int m2d_waves(int dbk, int dtm, bool ablk) { + if (dbk == 64) + return dtm <= 3 ? 16 : dtm == 4 ? 12 : dtm == 5 ? 10 : dtm == 6 ? (ablk ? 9 : 10) + : dtm == 7 ? 9 : (ablk ? 8 : 9); + return dtm <= 3 ? 10 : dtm == 4 ? 8 : dtm == 5 ? (ablk ? 8 : 7) : dtm == 6 ? (ablk ? 8 : 6) + : 6; +} + +template +__global__ __launch_bounds__(R4D_M2D_DWN * 32) R4D_WAVES(m2d_waves(DBK, DTM, ABLK)) +void r4d_gemm_m2xfp4a8_decode_kernel( + const unsigned char* __restrict__ A, const float* __restrict__ As, + const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, + const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref, + float* __restrict__ P, unsigned* __restrict__ cnt, uint16_t* __restrict__ C, + int M, int K, int N, int as_rs, int lda, int ldws, int ldc) { + constexpr int DWN = R4D_M2D_DWN, BND = DWN * 16, NTHR = DWN * 32; + constexpr int ROWS = R4D_M2D_MTILE * DTM; + constexpr int STR = DBK + R4D_M2D_PAD; + __shared__ unsigned char sA[ROWS * STR]; + __shared__ unsigned char sW[BND * STR]; + __shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale + __shared__ unsigned s_last; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int col = lane & 15, kb8 = (lane >> 4) * 8; + const int n0 = blockIdx.x * BND; + const int ks = blockIdx.z; + + const int slabs = (K + DBK - 1) / DBK; + const int spb = (slabs + DKS - 1) / DKS; + const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb); + const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K); + + v8f acc[DTM]; +#pragma unroll + for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f); + const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs; + float ns = 0.f, np = 0.f; + if constexpr (ABLK) { + // a split that starts mid-block meets its first boundary one slab in + const int kb = ((s_lo * DBK) >> 7) + 1; + if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; } + } + + const unsigned int* __restrict__ Wp = (const unsigned int*)W; + const int ksteps_g = K / 16; + + for (int s = s_lo; s < s_hi; ++s) { + const int k0 = s * DBK; + const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0; + if constexpr (ABLK) { + if (bnd && tid < ROWS) sR[tid] = m2d_ratio(ns, np, asrow, k0 >> 7); + } + // ---- A: ROWS x DBK bytes, clamped rows, 16 B a thread +#pragma unroll + for (int off = 0; off < ROWS * DBK; off += NTHR * 16) { + const int idx = off + tid * 16; + if (idx < ROWS * DBK) { + const int r = idx / DBK, c = idx % DBK; + const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate + *(m2d_u4*)(&sA[r * STR + c]) = *(const m2d_u4*)(A + (size_t)rc * lda + k0 + c); + } + } + // ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3. + // The k offset of the eight elements a lane stages is a multiple of 8 and DBK of 32, so one + // meta byte's two-bit field per row covers it whole (r4d_m2xfp4.h). + { + constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16; + const int kstep0 = k0 / 16; +#pragma unroll + for (int off = 0; off < NTILES_T * KSTEPS_T * 32; off += NTHR * 2) { + const int sl = off + tid * 2; + const int lane_ = sl & 31, rest = sl >> 5; + const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T; + const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8; + const int ksh = r4d_m2xfp4_kshift(kloc); + const int gn = n0 + r; + // gn is even and N % 16 == 0, so clamping to N - 2 keeps the 8 B read aligned and gc + 1 in + // bounds; the slot address is recomputed from the clamped row. + const int gc = gn < N - 2 ? gn : N - 2; + const int lanec = (lane_ & 16) | (gc & 15); + const m2d_u2 wv = + m2d_ld((const m2d_u2*)&Wp[((size_t)(gc >> 4) * ksteps_g + kstep0 + kst) * 32 + + lanec]); + const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP; +#pragma unroll + for (int q = 0; q < 2; ++q) { + const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * ldws + gc + q]); + const int k = (Wm[(size_t)blk * ldws + gc + q] >> ksh) & 3; + unsigned int lo, hi; + r4d_m2xfp4_unpack8(q ? wv[1] : wv[0], d, k, &lo, &hi); + *(m2d_u2*)(&sW[(r + q) * STR + kloc]) = m2d_u2{lo, hi}; + } + } + } + __syncthreads(); + if constexpr (ABLK) { + if (bnd) m2d_rescale(acc, sR, col); + if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) { + ns = asrow[(k0 >> 7) + 1]; + np = asrow[k0 >> 7]; + } + } +#pragma unroll + for (int step = 0; step < DBK / 16; ++step) { + const int kk = step * 16 + kb8; + m2d_v2i af[DTM], wf; +#pragma unroll + for (int i = 0; i < DTM; ++i) { + const unsigned char* pa = &sA[(i * 16 + col) * STR + kk]; + af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4); + } + const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk]; + wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4); +#pragma unroll + for (int i = 0; i < DTM; ++i) + acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]); + } + __syncthreads(); + } + const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0; + m2d_epilogue(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks, + kb_end, &s_last, sR); +} + +// The one-fragment form (M <= 16), every single-sequence verify step. Same tile, fold and split as +// above, plus: the next slab's A, codes, exponents and meta bytes are loaded into registers while +// this slab computes, keeping loads in flight across barriers; a thread takes four adjacent slots +// (one 16 B load); and each row's reference exponent is read once. Bit-identical to the kernel +// above. +template +__global__ __launch_bounds__(R4D_M2D_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12) +void r4d_gemm_m2xfp4a8_decode1_kernel( + const unsigned char* __restrict__ A, const float* __restrict__ As, + const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, + const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref, + float* __restrict__ P, unsigned* __restrict__ cnt, uint16_t* __restrict__ C, + int M, int K, int N, int as_rs, int lda, int ldws, int ldc) { + constexpr int DTM = 1, VEC = 4; + constexpr int DWN = R4D_M2D_DWN, BND = DWN * 16, NTHR = DWN * 32; + constexpr int ROWS = R4D_M2D_MTILE * DTM; + constexpr int STR = DBK + R4D_M2D_PAD; + constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16; + constexpr int W_IT = NTILES_T * KSTEPS_T * 32 / (NTHR * VEC); + constexpr int A_IT = (ROWS * DBK + NTHR * 16 - 1) / (NTHR * 16); + __shared__ unsigned char sA[ROWS * STR]; + __shared__ unsigned char sW[BND * STR]; + __shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale + __shared__ unsigned s_last; + + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int col = lane & 15, kb8 = (lane >> 4) * 8; + const int n0 = blockIdx.x * BND; + const int ks = blockIdx.z; + const int slabs = (K + DBK - 1) / DBK; + const int spb = (slabs + DKS - 1) / DKS; + const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb); + const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K); + + v8f acc[DTM]; +#pragma unroll + for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f); + const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs; + float ns = 0.f, np = 0.f; + if constexpr (ABLK) { + const int kb = ((s_lo * DBK) >> 7) + 1; + if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; } + } + const unsigned int* __restrict__ Wp = (const unsigned int*)W; + const int ksteps_g = K / 16; + + // per-thread slot geometry, fixed across slabs; the meta shift with it, since an eight-element + // slot's offset inside its 32-column group does not move + int s_r[W_IT], s_kst[W_IT], s_kloc[W_IT], s_gc[W_IT], s_lanec[W_IT], s_ksh[W_IT][VEC]; + int s_ref[W_IT][VEC]; +#pragma unroll + for (int it = 0; it < W_IT; ++it) { + const int sl = it * NTHR * VEC + tid * VEC; + const int lane_ = sl & 31, rest = sl >> 5; + const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T; + const int r = ntl * 16 + (lane_ & 15); + const int gn = n0 + r; + const int gc = gn < N - VEC ? gn : N - VEC; + s_r[it] = r; s_kst[it] = kst; s_kloc[it] = kst * 16 + (lane_ >> 4) * 8; + s_gc[it] = gc; s_lanec[it] = (lane_ & 16) | (gc & 15); +#pragma unroll + for (int q = 0; q < VEC; ++q) { + s_ref[it][q] = (int)Wref[gc + q]; + s_ksh[it][q] = r4d_m2xfp4_kshift(s_kloc[it]); + } + } + typedef unsigned wv_t __attribute__((ext_vector_type(VEC))); + wv_t rw[W_IT]; + int rd[W_IT][VEC], rk[W_IT][VEC]; + m2d_u4 ra[A_IT]; + + auto load = [&](int s) { + const int k0 = s * DBK; +#pragma unroll + for (int j = 0; j < A_IT; ++j) { + const int idx = j * NTHR * 16 + tid * 16; + if (idx < ROWS * DBK) { + const int r = idx / DBK, c = idx % DBK; + const int rc = r < M - 1 ? r : M - 1; + ra[j] = *(const m2d_u4*)(A + (size_t)rc * lda + k0 + c); + } + } + const int kstep0 = k0 / 16; +#pragma unroll + for (int it = 0; it < W_IT; ++it) { + const size_t slot = + ((size_t)(s_gc[it] >> 4) * ksteps_g + kstep0 + s_kst[it]) * 32 + s_lanec[it]; + rw[it] = m2d_ld((const wv_t*)&Wp[slot]); + const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP; +#pragma unroll + for (int q = 0; q < VEC; ++q) { + rd[it][q] = (int)Ws[(size_t)blk * ldws + s_gc[it] + q]; + rk[it][q] = (int)Wm[(size_t)blk * ldws + s_gc[it] + q]; + } + } + }; + auto store = [&]() { +#pragma unroll + for (int j = 0; j < A_IT; ++j) { + const int idx = j * NTHR * 16 + tid * 16; + if (idx < ROWS * DBK) { + const int r = idx / DBK, c = idx % DBK; + *(m2d_u4*)(&sA[r * STR + c]) = ra[j]; + } + } +#pragma unroll + for (int it = 0; it < W_IT; ++it) { +#pragma unroll + for (int q = 0; q < VEC; ++q) { + unsigned int lo, hi; + r4d_m2xfp4_unpack8(rw[it][q], r4d_mxfp4_fold_d(s_ref[it][q], rd[it][q]), + (rk[it][q] >> s_ksh[it][q]) & 3, &lo, &hi); + *(m2d_u2*)(&sW[(s_r[it] + q) * STR + s_kloc[it]]) = m2d_u2{lo, hi}; + } + } + }; + + if (s_lo < s_hi) load(s_lo); + for (int s = s_lo; s < s_hi; ++s) { + const int k0 = s * DBK; + const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0; + if constexpr (ABLK) { + if (bnd && tid < ROWS) sR[tid] = m2d_ratio(ns, np, asrow, k0 >> 7); + } + store(); + __syncthreads(); + if (s + 1 < s_hi) load(s + 1); // the next slab's loads fly across this slab's WMMAs + if constexpr (ABLK) { + if (bnd) m2d_rescale(acc, sR, col); + if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) { + ns = asrow[(k0 >> 7) + 1]; + np = asrow[k0 >> 7]; + } + } +#pragma unroll + for (int step = 0; step < DBK / 16; ++step) { + const int kk = step * 16 + kb8; + m2d_v2i af[DTM], wf; +#pragma unroll + for (int i = 0; i < DTM; ++i) { + const unsigned char* pa = &sA[(i * 16 + col) * STR + kk]; + af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4); + } + const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk]; + wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4); +#pragma unroll + for (int i = 0; i < DTM; ++i) + acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]); + } + __syncthreads(); + } + const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0; + m2d_epilogue(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks, + kb_end, &s_last, sR); +} + +namespace { +// The arrival counters, one block per output buffer (see the header). They cannot live in the +// scratch, which other ops overwrite, because they must be zero at entry. One allocation per +// (device, output), kept zero by the reducer and never freed (a recorded pass replays the +// pointer), as gemm_mxfp4a8_decode's mxd_out_ctr. +unsigned* m2d_out_ctr(const void* out) { + static std::mutex mu; + static std::map, unsigned*> blocks; + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess) return nullptr; + std::lock_guard lk(mu); + const auto key = std::make_pair(dev, out); + if (auto it = blocks.find(key); it != blocks.end()) return it->second; + const size_t n = R4D_M2D_MAX_N / (R4D_M2D_DWN * 16); + unsigned* p = nullptr; + if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr; + // Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished + // when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it runs on the + // null stream, which a non-blocking stream does not wait for, so wait here. + if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) { + (void)hipFree(p); + return nullptr; + } + blocks.emplace(key, p); + return p; +} + +// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule). +// The rule doubles the split while the grid has fewer than 48 blocks (M <= 16), 56 (M <= 96) or 40 +// (above) and the doubled split keeps KS * M <= 512; at K >= 8192 it doubles on, under the same +// bound, while each split still waits on 24 or more 128-wide slabs. The slab is 64 wide at the +// cases below, and wherever a 128-wide one would run past K. Shared by the launch and the scratch +// hook so the sized partial is the one written. +struct M2dPlan { int ks, bk; bool nt; }; +M2dPlan m2d_plan(int M, int K, int N, int KS, int BK, int NT) { + const int nblk = (N + R4D_M2D_DWN * 16 - 1) / (R4D_M2D_DWN * 16); + const int tm = (M + R4D_M2D_MTILE - 1) / R4D_M2D_MTILE; + M2dPlan p; + int ks = 1; + const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40); + while (ks < R4D_M2D_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1; + if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them + while (ks < R4D_M2D_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1; + p.ks = KS > 0 ? KS : ks; + // 64-wide slabs where LDS per block would cost resident blocks: DTM 4 unsplit on 110+ column + // blocks, and DTM 8 on those or at a split of 4 or more. + const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4)); + p.bk = BK > 0 ? BK : (slab64 ? 64 : 128); + p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20)); + if (K % p.bk) { // a slab may not run past K + p.bk = 64; + if (p.ks == 2) p.ks = 4; + } + return p; +} + +long m2d_partial_bytes(int M, int N, int ks) { + return ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0; +} + +void m2d_launch(long a, long ascale, long wq, long ws, long wm, long wref, long c, int M, int K, + int N, int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch, + long scratch_bytes, int lda, int ldws, int ldc) { + // A caller reading windows of larger planes passes their row pitches; 0 means the plane's own + // width, as r4d_gemm_mxfp4a8_nt_m64's launcher spells it. + if (!lda) lda = K; + if (!ldws) ldws = N; + if (!ldc) ldc = N; + if (M < 1 || M > R4D_M2D_MTILE * R4D_M2D_MAX_TM) + throw std::runtime_error("r4d gemm_m2xfp4a8_decode: M must be 1..128"); + if (N < 16 || N % 16 || N > R4D_M2D_MAX_N) + throw std::runtime_error("r4d gemm_m2xfp4a8_decode: N must be a multiple of 16 up to 36864"); + if (K < 64 || K % 64) + throw std::runtime_error("r4d gemm_m2xfp4a8_decode: K must be a multiple of 64"); + if (as_group != 0 && as_group != 128) + throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the activation scale is per row or per " + "128 of K"); + const M2dPlan pl = m2d_plan(M, K, N, KS, BK, NT); + const int ks = pl.ks, bk = pl.bk; + if (ks != 1 && ks != 2 && ks != 4 && ks != 8 && ks != 16) + throw std::runtime_error("r4d gemm_m2xfp4a8_decode: KS must be 1, 2, 4, 8 or 16"); + if (bk != 64 && bk != 128) + throw std::runtime_error("r4d gemm_m2xfp4a8_decode: BK must be 64 or 128"); + if (scratch_bytes < m2d_partial_bytes(M, N, ks) || (ks > 1 && !scratch)) + throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the op's scratch is shorter than the split " + "partial; the scratch hook sizes it"); + float* P = (float*)scratch; + unsigned* cnt = m2d_out_ctr((const void*)c); + if (!cnt) throw std::runtime_error("r4d gemm_m2xfp4a8_decode: split counter alloc failed"); + const bool ablk = as_group == 128, nt = pl.nt; + const int nblk = (N + R4D_M2D_DWN * 16 - 1) / (R4D_M2D_DWN * 16); + const int tm = (M + R4D_M2D_MTILE - 1) / R4D_M2D_MTILE; + hipStream_t st = (hipStream_t)stream; + dim3 grid(nblk, 1, ks), block(R4D_M2D_DWN * 32); + auto Ap = (const unsigned char*)a; + auto Sp = (const float*)ascale; + auto Wp = (const unsigned char*)wq; + auto Zp = (const unsigned char*)ws; + auto Mp = (const unsigned char*)wm; + auto Rp = (const unsigned char*)wref; + auto Cp = (uint16_t*)c; +#define M2D_L(BK_, KS_, TM_, NT_, AB_) \ + hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_decode_kernel), grid, block, 0, \ + st, Ap, Sp, Wp, Zp, Mp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc) +#define M2D_L1(BK_, KS_, NT_, AB_) \ + hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_decode1_kernel), grid, block, 0, st, \ + Ap, Sp, Wp, Zp, Mp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc) +#define M2D_AB(BK_, KS_, TM_, NT_) \ + { if (ablk) M2D_L(BK_, KS_, TM_, NT_, true); else M2D_L(BK_, KS_, TM_, NT_, false); } +#define M2D_NT(BK_, KS_, TM_) \ + { if (nt) M2D_AB(BK_, KS_, TM_, true) else M2D_AB(BK_, KS_, TM_, false) } +#define M2D_AB1(BK_, KS_, NT_) \ + { if (ablk) M2D_L1(BK_, KS_, NT_, true); else M2D_L1(BK_, KS_, NT_, false); } +#define M2D_NT1(BK_, KS_) { if (nt) M2D_AB1(BK_, KS_, true) else M2D_AB1(BK_, KS_, false) } +#define M2D_TM(BK_, KS_) \ + { switch (tm) { case 1: M2D_NT1(BK_, KS_) break; case 2: M2D_NT(BK_, KS_, 2) break; \ + case 3: M2D_NT(BK_, KS_, 3) break; case 4: M2D_NT(BK_, KS_, 4) break; \ + case 5: M2D_NT(BK_, KS_, 5) break; case 6: M2D_NT(BK_, KS_, 6) break; \ + case 7: M2D_NT(BK_, KS_, 7) break; default: M2D_NT(BK_, KS_, 8) break; } } +#define M2D_KS(BK_) \ + { switch (ks) { case 1: M2D_TM(BK_, 1) break; case 2: M2D_TM(BK_, 2) break; \ + case 4: M2D_TM(BK_, 4) break; case 8: M2D_TM(BK_, 8) break; \ + default: M2D_TM(BK_, 16) break; } } + if (bk == 64) M2D_KS(64) else M2D_KS(128) +#undef M2D_KS +#undef M2D_TM +#undef M2D_NT1 +#undef M2D_AB1 +#undef M2D_NT +#undef M2D_AB +#undef M2D_L1 +#undef M2D_L +} +} // namespace + +extern "C" int r4d_gemm_m2xfp4a8_decode_max_m(void) { return R4D_M2D_MTILE * R4D_M2D_MAX_TM; } + +// The raw entry, as r4d_gemm_fp8a8_nt_m16: plain C ABI for a caller that sizes the split itself. +// The scratch is the split partial, m2d_partial_bytes at m2d_plan's split (r4d_m2xfp4.h gives +// the sizes a caller can use); `scratch` null runs unsplit only when KS is 1. +extern "C" void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws, long wm, long wref, + long c, int M, int K, int N, int KS, int BK, int NT, + int as_group, int as_rs, long scratch, + long scratch_bytes, long stream, int lda, int ldws, + int ldc) { + m2d_launch(a, ascale, wq, ws, wm, wref, c, M, K, N, KS, BK, NT, as_group, as_rs, stream, scratch, + scratch_bytes, lda, ldws, ldc); +} + +// ============================================================== the plugin ABI entry point +extern "C" int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs* a, RadStream s) { + GemmOps g; + /* No parts: the m2xfp4 declare makes none, so gemm_ops refuses pb1/pb2, as libref does. */ + int rc = gemm_ops(a, &g, 1); + if (rc != RAD_OK) return rc; + if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE); + if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL); + if (g.K % 64) return R4D_NO(RAD_E_SHAPE); + if (g.M > r4d_gemm_m2xfp4a8_decode_max_m() || g.N > R4D_M2D_MAX_N) return R4D_NO(RAD_E_SHAPE); + int as_group = 0, as_rs = 1; + rc = mx_ascale_grid(g, &as_group, &as_rs); + if (rc != RAD_OK) return rc; + R4dMxDecCfg t; + r4d_cfg_mxfp4_decode(a, &t); + // The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order. + const long meta = r4d_addr(g.b) + (long)g.N * g.K / 2; + R4D_TRY("gemm_m2xfp4a8_decode", + m2d_launch(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), meta, + r4d_addr(g.bref), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, t.ks, t.bk, t.nt, + as_group, as_rs, (long)(uintptr_t)s, (long)(uintptr_t)a->scratch, + (long)a->scratch_bytes, (int)g.K, (int)g.N, (int)g.N)); + return RAD_OK; +} + +/* The op's scratch size. A narrower M can split wider than the band's widest M, so the size is the + * widest split over the band times the widest M, an upper bound for every launch. */ +extern "C" int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs* a) { + const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0); + const long long K = r4d_geti_or(a, "K", 0); + if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_m2xfp4a8_decode_max_m()) return 0; + R4dMxDecCfg t; + r4d_cfg_mxfp4_decode(a, &t); + int ks = 1; + for (int m = 1; m <= (int)M; ++m) { + const int k = m2d_plan(m, (int)K, (int)N, t.ks, t.bk, t.nt).ks; + if (k > ks) ks = k; + } + return (int64_t)m2d_partial_bytes((int)M, (int)N, ks); +} diff --git a/libr4d/r4d_gemm_m2xfp4a8_tiled.hip b/libr4d/r4d_gemm_m2xfp4a8_tiled.hip new file mode 100644 index 00000000..bde5efe4 --- /dev/null +++ b/libr4d/r4d_gemm_m2xfp4a8_tiled.hip @@ -0,0 +1,362 @@ +// r4d_gemm_m2xfp4a8_tiled.hip - r4d_gemm_m2xfp4a8_tiled: the M2XFP4 x fp8 GEMM for prefill row +// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout, fold and +// tile of r4d_gemm_mxfp4a8_tiled, plus the weight-side Sg-EM (arXiv 2601.19213 §4.4.2) the decode +// row decodes: per group of 32 K a meta byte of four two-bit subgroup multipliers, folded into the +// e4m3 staging bytes through r4d_m2xfp4.h's second table index, so the WMMA chain, the Wref +// epilogue and the activation scale grids are the mxfp4 kernel's unchanged. +// +// The meta byte is staged beside the exponent byte: one byte per (weight row, 32 of K), in the +// scale plane's [K/32][N] order and row pitch, in the tail of the same stored weight (the relayout +// appends it after the fragment-order codes, r4d_layout.cpp). A staged slot's eight elements sit at +// an offset that is a multiple of 8 inside their 32-column group, so one two-bit field per slot +// covers it whole; the shift is fixed per slot across slabs and read with the geometry the scale +// dword already uses. +// +// The fold's bound: Wref[n] is the row's largest exponent byte as for MXFP4, so d >= 0 holds for +// every block, and the largest element any table cell then holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d +// -- an e4m3 normal at every d >= 0 (r4d_m2xfp4.h). The table is four times the mxfp4 one, 512 +// bytes, still nothing against sW; the LDS copy widens with it. +#include "r4d.h" +#include "r4d_gemm_args.h" +#include "r4d_common.h" +#include "r4d_m2xfp4.h" + +// bf16 output as uint16 pairs (the emulator-compatible spelling, r4d_common.h): the OCP +// rows read __hip_bfloat16 from hip_bf16.h, whose bytes these are. +#include +#include + +#define R4D_M2T_TM 4 // 16-row fragments per wave +#define R4D_M2T_WM 4 // waves along M +#define R4D_M2T_WN 2 // waves along N +#define R4D_M2T_PAD 8 // LDS row pad: 16 lanes reading rows 64 B apart collide 8 ways +#define R4D_M2T_NTHR (R4D_M2T_WM * R4D_M2T_WN * 32) +#define R4D_M2T_BMF (R4D_M2T_WM * R4D_M2T_TM * 16) +#define R4D_M2T_KUNIT 64 // the narrowest K slab, so K must be a multiple of it +// tn=0's M crossover to TN=4 for this kernel, as its tn axis (tGemmMxfp4Tiled) states it. +#define R4D_M2T_TN4_MIN_M 2048 + +typedef int m2t_v2i __attribute__((ext_vector_type(2))); +typedef unsigned m2t_u2 __attribute__((ext_vector_type(2))); +typedef unsigned m2t_u4 __attribute__((ext_vector_type(4))); + +// The re-tile: one thread per 8-byte slot of the fragment-ordered plane; writes are contiguous. +// (r4d_mxfp4a8_tile_a_kernel, shared work; this row runs its own copy so the two units stay +// independent.) +__global__ __launch_bounds__(256) void r4d_m2xfp4a8_tile_a_kernel( + const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K, + long long slots, int lda) { + const long long o = (long long)blockIdx.x * 256 + threadIdx.x; + if (o >= slots) return; + const int ks = K / 16; + const int lane = (int)(o & 31); + const long long f = o >> 5; + const int mt = (int)(f / ks), kst = (int)(f % ks); + const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8; + m2t_u2 v = { 0u, 0u }; + if (r < M) v = *(const m2t_u2*)(A + (size_t)r * lda + k); + *(m2t_u2*)(AT + o * 8) = v; +} + +template +__global__ __launch_bounds__(R4D_M2T_NTHR) void r4d_gemm_m2xfp4a8_tiled_kernel( + const unsigned char* __restrict__ AT, const float* __restrict__ As, + const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, + const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref, + uint16_t* __restrict__ C, int M, int K, int N, int as_rs, int ldws, int ldc) { + constexpr int TM = R4D_M2T_TM, WN = R4D_M2T_WN, NTHR = R4D_M2T_NTHR, BMF = R4D_M2T_BMF; + constexpr int NS = LBK / 16, STR = LBK + R4D_M2T_PAD, BNF = WN * TN * 16; + constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32; + // 4 weight slots (one 16 B read) wherever the tile has enough of them, else 2 (8 B), else 1. + constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1); + constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS); + static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block"); + __shared__ unsigned char sW[BNF * STR]; + __shared__ unsigned int sMag[128]; // kM2xfp4Mag: [16][4][2] words + __shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale + + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int wm = wave / WN, wn = wave % WN; + const int col = lane & 15, kb8 = (lane >> 4) * 8; + const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF; + const int ksteps = K / 16, Mt = (M + 15) >> 4; + + if (tid < 128) sMag[tid] = (&kM2xfp4Mag[0][0][0])[tid]; + + // One A base per M fragment, wave-uniform: readfirstlane keeps it in an SGPR so loads take the + // SADDR form with a 32-bit lane offset. A tile past M reads the last real one. + const unsigned char* abase[TM]; +#pragma unroll + for (int i = 0; i < TM; ++i) { + int mt = (m0 >> 4) + wm * TM + i; + mt = mt < Mt - 1 ? mt : Mt - 1; + abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256); + } + const unsigned int aoff = (unsigned int)lane * 8; + + // The W slots this thread stages, fixed across slabs: WSLOTS adjacent rows of one (n-tile, + // k-step), so the wave reads contiguous bytes; the clamp keeps the vector read aligned. The meta + // shift moves with the slot: its eight elements' offset inside their 32-column group is + // kst*16 + (lane>>4)*8, a multiple of 8 (r4d_m2xfp4.h). + int wrow[NW], wkloc[NW], wrc[NW], wkst[NW], wlanec[NW], wksh[NW]; + unsigned int wref[NW]; +#pragma unroll + for (int it = 0; it < NW; ++it) { + const int sl = it * NTHR * WSLOTS + tid * WSLOTS; + const int lane_ = sl & 31, rest = sl >> 5; + const int kst = rest % NS, ntl = rest / NS; + wrow[it] = ntl * 16 + (lane_ & 15); + wkloc[it] = kst * 16 + (lane_ >> 4) * 8; + wksh[it] = r4d_m2xfp4_kshift(wkloc[it]); + const int gn = n0 + wrow[it]; + wrc[it] = gn < N - WSLOTS ? gn : N - WSLOTS; + wlanec[it] = (lane_ & 16) | (wrc[it] & 15); + wkst[it] = kst; + wref[it] = WSLOTS == 4 ? *(const unsigned int*)(Wref + wrc[it]) + : WSLOTS == 2 ? *(const unsigned short*)(Wref + wrc[it]) + : Wref[wrc[it]]; + } + + v8f acc[TM][TN]; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f); + + // ABLK: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two scales (the + // block starting there and the one before it) a boundary early. + const int trow = m0 + tid < M ? m0 + tid : M - 1; + const float* __restrict__ asrow = As + (size_t)trow * as_rs; + float ns = 0.f, np = 0.f; + const unsigned int* __restrict__ Wp = (const unsigned int*)W; + lds_barrier(); // sMag + + for (int k0 = 0; k0 < K; k0 += LBK) { + // ABLK: at a 128 boundary each row's ratio goes to LDS, published by the staging barrier below + // (sR's previous readers finished before the last slab's closing barrier). A zero block keeps + // the carried scale; after a zero block the carried scale is looked up from the grid. + const bool bnd = ABLK && k0 && (k0 & 127) == 0; + if constexpr (ABLK) { + if (bnd) + sR[tid] = ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(asrow, (k0 >> 7) - 2)) / ns : 1.f; + } + // A fragments for the whole slab, one clause, consumed only at the WMMAs. + m2t_v2i af[TM][NS]; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int st = 0; st < NS; ++st) + af[i][st] = *(const m2t_v2i*)(abase[i] + + (aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256))); + // W slab -> LDS, folded to e4m3. The meta bytes ride the same dword reads as the exponents. + const int kstep0 = k0 / 16; +#pragma unroll + for (int it = 0; it < NW; ++it) { + const unsigned int* src = + &Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]]; + const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP; + unsigned int wq[WSLOTS], wsw, wmw; + if constexpr (WSLOTS == 4) { + const m2t_u4 v = *(const m2t_u4*)src; + wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3]; + wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]); + wmw = *(const unsigned int*)(Wm + (size_t)blk * ldws + wrc[it]); + } else if constexpr (WSLOTS == 2) { + const m2t_u2 v = *(const m2t_u2*)src; + wq[0] = v[0]; wq[1] = v[1]; + wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]); + wmw = *(const unsigned short*)(Wm + (size_t)blk * ldws + wrc[it]); + } else { + wq[0] = *src; + wsw = Ws[(size_t)blk * ldws + wrc[it]]; + wmw = Wm[(size_t)blk * ldws + wrc[it]]; + } +#pragma unroll + for (int q = 0; q < WSLOTS; ++q) { + const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF), + (int)((wsw >> (8 * q)) & 0xFF)); + const int k = (int)((wmw >> (8 * q + wksh[it])) & 3); + const int ti = (d * 4 + k) * 2; + unsigned int lo, hi; + r4d_mxfp4_unpack8_t(wq[q], sMag[ti], sMag[ti + 1], &lo, &hi); + *(m2t_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = m2t_u2{lo, hi}; + } + } + lds_barrier(); + + if constexpr (ABLK) { + // Re-express each row's partial sum in the new block's scale: one ratio a lane a row. + if (bnd) { +#pragma unroll + for (int i = 0; i < TM; ++i) { + const float r = sR[wm * TM * 16 + i * 16 + col]; +#pragma unroll + for (int j = 0; j < TN; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) acc[i][j][e] *= r; + } + } + // The next boundary's scales, issued behind this slab's loads and needed a boundary later. + if ((k0 & 127) == 0 && k0 + 128 < K) { + ns = asrow[(k0 >> 7) + 1]; + np = asrow[k0 >> 7]; + } + } + +#pragma unroll + for (int step = 0; step < NS; ++step) { + const int kk = step * 16 + kb8; + m2t_v2i wf[TN]; +#pragma unroll + for (int j = 0; j < TN; ++j) { + const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk]; + wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4); + } + // Keep one step's W fragments live at a time; otherwise the compiler hoists every step's + // loads above the first WMMA. + __builtin_amdgcn_sched_barrier(0); +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) + acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step], + acc[i][j]); + } + lds_barrier(); + } + + // Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns + // of N fragment j, one 16-byte store per (i, j). 2^(Wref[n]-127) is the float whose exponent + // field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside or all outside N. + float sc[TM]; + if constexpr (ABLK) { + // the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads + sR[tid] = r4d_mxfp4_carried(asrow, (K - 1) >> 7); + lds_barrier(); +#pragma unroll + for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col]; + } else { +#pragma unroll + for (int i = 0; i < TM; ++i) { + const int m = m0 + wm * TM * 16 + i * 16 + col; + sc[i] = As[(size_t)(m < M ? m : M - 1) * as_rs]; + } + } +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int nb = n0 + wn * TN * 16 + j * 16 + kb8; + if (nb >= N) continue; + const m2t_u2 rb = *(const m2t_u2*)(Wref + nb); +#pragma unroll + for (int i = 0; i < TM; ++i) { + const int m = m0 + wm * TM * 16 + i * 16 + col; + if (m >= M) continue; + // rounded as the bf16 store rounds, packed in whole registers (see bf16x2_rne_nan) + float v[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23); + v[e] = acc[i][j][e] * rf * sc[i]; + } + m2t_u4 o; + o.x = bf16x2_rne_nan(v[0], v[1]); + o.y = bf16x2_rne_nan(v[2], v[3]); + o.z = bf16x2_rne_nan(v[4], v[5]); + o.w = bf16x2_rne_nan(v[6], v[7]); + *(m2t_u4*)(C + (size_t)m * ldc + nb) = o; + } + } +} + +extern "C" int r4d_gemm_m2xfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; } + +extern "C" long r4d_m2xfp4a8_tile_a_bytes(int M, int K) { + return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K; +} + +extern "C" void r4d_m2xfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda) { + if (!lda) lda = K; + if (M < 1) throw std::runtime_error("r4d m2xfp4a8_tile_a: M must be >= 1"); + if (K < 16 || K % 16) throw std::runtime_error("r4d m2xfp4a8_tile_a: K must be a multiple of 16"); + const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32; + hipLaunchKernelGGL(r4d_m2xfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256), + 0, (hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, + slots, lda); +} + +extern "C" void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws, long wm, long wref, + long c, int M, int K, int N, int TN, int as_group, + int as_rs, long stream, int ldws, int ldc) { + if (!ldws) ldws = N; + if (!ldc) ldc = N; + if (M < 1) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: M must be >= 1"); + if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: N must be a multiple of 16"); + if (K < R4D_M2T_KUNIT || K % R4D_M2T_KUNIT) + throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: K must be a multiple of 64"); + // tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves fewer than 128 blocks + // (narrow N), where TN=2's extra blocks win. + if (TN == 0) + TN = M >= R4D_M2T_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_M2T_BMF - 1) / R4D_M2T_BMF) >= 128 + ? 4 : 2; + if (TN != 2 && TN != 4) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: TN must be 2 or 4"); + if (as_group != 0 && as_group != 128) + throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: the activation scale is per row or per 128 of K"); + const bool ablk = as_group == 128; + if (ablk && as_rs < (K + 127) / 128) + throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: activation scale rows shorter than ceil(K/128)"); + const bool wide_slab = TN == 2 && K % 128 == 0; + const int bnf = R4D_M2T_WN * TN * 16; + dim3 grid((N + bnf - 1) / bnf, (M + R4D_M2T_BMF - 1) / R4D_M2T_BMF), block(R4D_M2T_NTHR); + auto Ap = (const unsigned char*)at; + auto Sp = (const float*)ascale; + auto Wp = (const unsigned char*)wq; + auto Zp = (const unsigned char*)ws; + auto Mp = (const unsigned char*)wm; + auto Rp = (const unsigned char*)wref; + auto Cp = (uint16_t*)c; + hipStream_t st = (hipStream_t)stream; +#define M2T_LAUNCH(TNv, LBKv, ABv) \ + hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_tiled_kernel), grid, block, 0, st, Ap, Sp, \ + Wp, Zp, Mp, Rp, Cp, M, K, N, as_rs, ldws, ldc) + if (TN == 4) { if (ablk) M2T_LAUNCH(4, 64, true); else M2T_LAUNCH(4, 64, false); } + else if (wide_slab) { if (ablk) M2T_LAUNCH(2, 128, true); else M2T_LAUNCH(2, 128, false); } + else { if (ablk) M2T_LAUNCH(2, 64, true); else M2T_LAUNCH(2, 64, false); } +#undef M2T_LAUNCH +} + +// ============================================================== the plugin ABI entry point +// The row-major activation is re-tiled into the op's scratch and the GEMM reads it there. +extern "C" int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs* a, RadStream s) { + GemmOps g; + /* No parts: the m2xfp4 declare makes none, so gemm_ops refuses pb1/pb2, as libref does. */ + int rc = gemm_ops(a, &g, 1); + if (rc != RAD_OK) return rc; + if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE); + if (!g.ascale) return R4D_NO(RAD_E_INVAL); + /* The per-row reference exponent is required, as in r4d_rad_gemm_mxfp4a8_m64. */ + if (!g.bref) return R4D_NO(RAD_E_INVAL); + if (g.K % R4D_M2T_KUNIT) return R4D_NO(RAD_E_SHAPE); + int as_group = 0, as_rs = 1; + rc = mx_ascale_grid(g, &as_group, &as_rs); + if (rc != RAD_OK) return rc; + const long long slab = r4d_m2xfp4a8_tile_a_bytes((int)g.M, (int)g.K); + if (!a->scratch || a->scratch_bytes < slab) return R4D_NO(RAD_E_INVAL); + R4dMxTileCfg t; + r4d_cfg_mxfp4_tiled(a, &t); + const long at = (long)(uintptr_t)a->scratch; + // The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order. + const long meta = r4d_addr(g.b) + (long)g.N * g.K / 2; + R4D_TRY("gemm_m2xfp4a8_tiled", + r4d_m2xfp4a8_tile_a(r4d_addr(g.a), at, (int)g.M, (int)g.K, (long)(uintptr_t)s, (int)g.K); + r4d_gemm_m2xfp4a8_tiled(at, r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), meta, + r4d_addr(g.bref), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, + t.tn, as_group, as_rs, (long)(uintptr_t)s, (int)g.N, (int)g.N)); + return RAD_OK; +} + +/* The op's scratch, sized at the band's widest M: the fragment-tiled activation in whole 16-row + * fragments. */ +extern "C" int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs* a) { + const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0); + return (int64_t)r4d_m2xfp4a8_tile_a_bytes((int)M, (int)K); +} diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index c435b90e..e0df978e 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -962,6 +962,116 @@ extern "C" int r4d_rad_relayout_mxfp4_gated(const RadParam* p, int n_p, int oper : r4d_rad_relayout_mxfp4(p, n_p, o, enc, sel, pl, n, dst, dst_bytes); } +/* ---- M2XFP4: the M2 analogue of MXFP4 above, the paper's weight-side Sg-EM (arXiv 2601.19213 + * §4.4.2). The quantiser's own scheme "m2xfp4", three TILED planes over the same 32-column groups: + * + * codes fp4_e2m1 [1 x 1] element 2j in bits 0-3 of byte j -- radiance MXFP4's codes + * scale e8m0 [1 x 32] per group, the adaptive bias already folded into the stored byte + * meta u8 [1 x 32] one byte a group: subgroup s = columns [8s, 8s+8), bits [2s, 2s+2) + * + * The exact element is e2m1mag[c&7] . sign(c) . 2^(scale-127) . (1 + k_s/4). What the kernels read + * is the mxfp4 arrangement with the meta plane riding the stored weight's tail, in the scale + * plane's [K/32][N] order: codes in fragment order, then K/32 rows of N meta bytes, so both GEMM + * rows read it with the exponents' own geometry (r4d_gemm_m2xfp4a8_*.hip). b_ref stays each row's + * largest exponent byte, the same derivation a reader of the plane could compute -- and it is what + * bounds the fold: d >= 0 for every block, so the largest e4m3 a table cell holds is the x1.75 + * magnitude 10.5 scaled by 2^-d, a normal at every d >= 0. + * + * Anything else is refused, a transform included: this kernel library decodes one scheme, and a + * weight whose meta plane said something else would decode to other numbers. */ +namespace { +bool m2_planes(const RadEncoding* enc) { + if (!enc || !rad_enc_is(enc, "m2xfp4")) return false; + if (enc->transform[0] || enc->n_planes != 3) return false; + if (enc->plane[0].dtype != RAD_FP4E2M1 || enc->plane[0].block[0] != 1 || + enc->plane[0].block[1] != 1) + return false; + const int s = rad_enc_find(enc, "scale"), m = rad_enc_find(enc, "meta"); + if (s < 0 || m < 0) return false; + if (enc->plane[s].dtype != RAD_E8M0 || enc->plane[s].kind != RAD_PLANE_TILED || + enc->plane[s].block[0] != 1 || enc->plane[s].block[1] != R4D_MXFP4_GROUP) + return false; + if (enc->plane[m].dtype != RAD_U8 || enc->plane[m].kind != RAD_PLANE_TILED || + enc->plane[m].block[0] != 1 || enc->plane[m].block[1] != R4D_MXFP4_GROUP) + return false; + return true; +} + +int m2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out, WGeom* gout) { + if (!out || !pl) return RAD_E_INVAL; + WGeom g; + int rc = wgeom(p, n_p, R4D_MXFP4_GROUP, &g); + if (rc != RAD_OK) return rc; + if (g.group != R4D_MXFP4_GROUP || g.K % 16) return RAD_E_SHAPE; + if (!m2_planes(enc)) return RAD_E_DTYPE; + if (gout) *gout = g; + const long long nblk = g.K / R4D_MXFP4_GROUP; + if (operand == Q_BSCALE || operand == Q_BREF) { + if (!selects(enc, sel, n, "scale") || !dims(pl[0], g.N, nblk)) return RAD_E_SHAPE; + if (operand == Q_BSCALE) fill(out, "r4d.mxfp4.e8m0", R4D_DT_E8M0, nblk, g.N, nblk * g.N); + else fill(out, "r4d.mxfp4.wref", R4D_DT_E8M0, g.N, 1, g.N); + return RAD_OK; + } + if (operand != Q_B) return RAD_E_UNSUPPORTED; + /* The weight operand takes codes and meta: the codes go to fragment order, the meta to the + * stored blob's tail. */ + if (!selects(enc, sel, n, "codes", "meta") || !dims(pl[0], g.N, g.K) || + !dims(pl[1], g.N, nblk)) + return RAD_E_SHAPE; + fill(out, "r4d.m2xfp4.frag.g32.meta", R4D_DT_M2XFP4_FRAG, g.N, g.K, + g.N * g.K / 2 + nblk * g.N); + return RAD_OK; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_m2xfp4(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + return m2_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr); +} + +extern "C" int r4d_rad_relayout_m2xfp4(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, const RadTensor* pl, + int n, void* dst, int64_t dst_bytes) { + RadLayout L; + WGeom g; + const int rc = m2_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes) return RAD_E_SHAPE; + std::memset(dst, 0, (size_t)dst_bytes); + const long long nblk = g.K / R4D_MXFP4_GROUP; + uint8_t* d = (uint8_t*)dst; + if (operand == Q_BSCALE || operand == Q_BREF) { + const uint8_t* e = pdata(pl[0]); + for (long long nn = 0; nn < g.N; ++nn) { + uint8_t mx = 0; + for (long long b = 0; b < nblk; ++b) { + const uint8_t v = e[nn * nblk + b]; + if (operand == Q_BSCALE) d[b * g.N + nn] = v; + if (v > mx) mx = v; + } + if (operand == Q_BREF) d[nn] = mx; + } + return RAD_OK; + } + /* Codes to fragment order (mx_slot, as r4d_rad_relayout_mxfp4), then the meta plane appended: + * canonical [N][K/32] read into stored [K/32][N]. */ + const uint8_t* meta = pdata(pl[1]); + uint8_t* md = d + g.N * g.K / 2; + for (long long nn = 0; nn < g.N; ++nn) { + const uint8_t* row = pdata(pl[0]) + nn * (g.K / 2); + for (long long k = 0; k < g.K; ++k) { + const uint8_t code = (uint8_t)((row[k >> 1] >> (4 * (k & 1))) & 0xF); + const long long idx = mx_slot(g, nn, k); + if (k & 1) d[idx] = (uint8_t)((d[idx] & 0x0Fu) | (uint32_t)(code << 4)); + else d[idx] = (uint8_t)((d[idx] & 0xF0u) | code); + } + for (long long b = 0; b < nblk; ++b) md[b * g.N + nn] = meta[nn * nblk + b]; + } + return RAD_OK; +} + /* ---- the MoE experts. The weight is staged through LDS, so it is not permuted: the int4 plane is * the canonical one with each dword's nibbles reordered for the expansion (byte b holds element b * low and element b+4 high), and the fp8 plane is the canonical one unchanged. `w4a8h` is the same diff --git a/libr4d/r4d_m2xfp4.h b/libr4d/r4d_m2xfp4.h new file mode 100644 index 00000000..cff85bac --- /dev/null +++ b/libr4d/r4d_m2xfp4.h @@ -0,0 +1,129 @@ +// Shared device code for the M2XFP4 GEMMs (r4d_gemm_m2xfp4a8_decode, r4d_gemm_m2xfp4a8_tiled): +// the folded-magnitude table and the eight-element unpack that reads it. The M2 analogue of +// r4d_mxfp4.h: the same e2m1 codes and E8M0 exponents, plus one more per-group byte of weight-side +// Sg-EM metadata (arXiv 2601.19213 §4.4.2), which folds the same way -- through a table, with a +// v_perm_b32 per half-word. +// +// The container ("m2xfp4", the quantiser's scheme) stores, per group of 32 K, an E8M0 exponent byte +// whose adaptive bias b in {-1,0,1} is already folded in, and a meta byte holding one two-bit +// subgroup multiplier k_s per eight columns, s = columns [8s, 8s+8) of the group: the stored byte's +// bits [2s, 2s+2). The exact weight is +// +// w = e2m1mag[c & 7] * sign(c) * 2^(scale - 127) * (1 + k_s / 4) +// +// with e2m1mag = {0, .5, 1, 1.5, 2, 3, 4, 6} and k -> {1.0, 1.25, 1.5, 1.75}. The fold of +// r4d_gemm_mxfp4a8_nt_m64.hip applies to it unchanged: d = Wref[n] - E8M0[n][blk] goes through the +// table, 2^(Wref[n]-127) once in the epilogue. Wref[n] is still the row's largest exponent byte, +// so d >= 0 holds for every block; what the meta adds is bounded the same way -- the largest +// element a table cell holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d, an E4M3 normal for every d >= 0, so +// no cell saturates and the fold is exact in its exponent at every block. +#pragma once + +#include "r4d_mxfp4.h" // the fold clamp r4d_mxfp4_fold_d, the carried-scale reader, GROUP + +// kM2xfp4Mag[d][k] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by +// (1 + k/4) * 2^-d, as packed e4m3 bytes (low word, high word), indexed by the 3-bit magnitude +// through v_perm_b32 -- kMxfp4Mag's table with a second index. Entries are the round-to-nearest-even +// e4m3 of the product, matching the hardware conversion. +// +// Exactness, per magnitude and k, in the normal range of e4m3 (every entry here down to its +// subnormal floor behaves exactly like r4d_mxfp4.h's table one binade earlier, where the 2^-9 step +// is coarse; the entries flush the same way and the sums they miss are invisible next to the +// accumulator): +// - k = 0 is r4d_mxfp4.h's kMxfp4Mag row, byte for byte. +// - k = 1, 2: exact. The products' mantissas (1.25, 1.5 and 1.75 times a magnitude whose own +// mantissa is 1.0 or 1.1) take at most the three e4m3 mantissa bits, at every d while the +// value is normal. +// - k = 3 (x1.75): the even-mantissa magnitudes {0, .5, 1, 2, 4} stay exact (1.11 x 1.0); the odd +// ones {1.5, 3, 6} land on 1.0101, four mantissa bits, and round to the tie's even side -- 2.5, +// 5 and 10 scaled by 2^-d. That is 2^-4.4 relative error on those elements and nothing on the +// rest, accepted here: the CPU decode (and the reference) stay exact, and 6 * 1.75 = 10.5 at +// d = 0 is what the row-maximum bound above has to fit, which it does. +// +// Static: each kernel's code object carries its own copy. +static __device__ __constant__ unsigned int kM2xfp4Mag[16][4][2] = { + {{0x3c383000u, 0x4c484440u}, {0x3f3a3200u, 0x4f4a4742u}, {0x413c3400u, 0x514c4944u}, + {0x423e3600u, 0x524e4a46u}}, + {{0x34302800u, 0x44403c38u}, {0x37322a00u, 0x47423f3au}, {0x39342c00u, 0x4944413cu}, + {0x3a362e00u, 0x4a46423eu}}, + {{0x2c282000u, 0x3c383430u}, {0x2f2a2200u, 0x3f3a3732u}, {0x312c2400u, 0x413c3934u}, + {0x322e2600u, 0x423e3a36u}}, + {{0x24201800u, 0x34302c28u}, {0x27221a00u, 0x37322f2au}, {0x29241c00u, 0x3934312cu}, + {0x2a261e00u, 0x3a36322eu}}, + {{0x1c181000u, 0x2c282420u}, {0x1f1a1200u, 0x2f2a2722u}, {0x211c1400u, 0x312c2924u}, + {0x221e1600u, 0x322e2a26u}}, + {{0x14100800u, 0x24201c18u}, {0x17120a00u, 0x27221f1au}, {0x19140c00u, 0x2924211cu}, + {0x1a160e00u, 0x2a26221eu}}, + {{0x0c080400u, 0x1c181410u}, {0x0f0a0500u, 0x1f1a1712u}, {0x110c0600u, 0x211c1914u}, + {0x120e0700u, 0x221e1a16u}}, + {{0x06040200u, 0x14100c08u}, {0x08050200u, 0x17120f0au}, {0x09060300u, 0x1914110cu}, + {0x0a070400u, 0x1a16120eu}}, + {{0x03020100u, 0x0c080604u}, {0x04020100u, 0x0f0a0805u}, {0x04030200u, 0x110c0906u}, + {0x05040200u, 0x120e0a07u}}, + {{0x02010000u, 0x06040302u}, {0x02010100u, 0x08050402u}, {0x02020100u, 0x09060403u}, + {0x03020100u, 0x0a070504u}}, + {{0x01000000u, 0x03020201u}, {0x01010000u, 0x04020201u}, {0x01010000u, 0x04030202u}, + {0x01010000u, 0x05040302u}}, + {{0x00000000u, 0x02010100u}, {0x00000000u, 0x02010101u}, {0x01000000u, 0x02020101u}, + {0x01000000u, 0x03020101u}}, + {{0x00000000u, 0x01000000u}, {0x00000000u, 0x01010000u}, {0x00000000u, 0x01010100u}, + {0x00000000u, 0x01010100u}}, + {{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x01000000u}, + {0x00000000u, 0x01000000u}}, + {{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, + {0x00000000u, 0x00000000u}}, + {{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, + {0x00000000u, 0x00000000u}}, +}; + +// The two-bit field of a meta byte that covers `koff`, an element offset inside a 32-column group +// that is a multiple of 8 (which the kernels' staging offsets all are): the subgroup s = koff / 8, +// bits [2s, 2s+2). A thread whose eight elements start at koff takes this shift once and one meta +// byte per (row, block) alongside the exponent byte. +static __device__ __forceinline__ int r4d_m2xfp4_kshift(int koff) { + return 2 * ((koff >> 3) & 3); +} + +// Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) -> eight e4m3 bytes +// in k order (word 0 = elements 0..3, word 1 = 4..7), with the exponent difference `d` and the +// subgroup multiplier `k` folded in. r4d_mxfp4_unpack8_t with the [d][k] table row; see there. A +// caller that already holds the row, e.g. in an LDS copy (the tiled kernel's sMag, which keeps the +// lookup off the global load counter the weight and activation loads wait on), calls +// r4d_mxfp4_unpack8_t with it directly. +static __device__ __forceinline__ void r4d_m2xfp4_unpack8(unsigned int wv, int d, int k, + unsigned int* lo, unsigned int* hi) { + r4d_mxfp4_unpack8_t(wv, kM2xfp4Mag[d][k][0], kM2xfp4Mag[d][k][1], lo, hi); +} + +// ---- The raw entry points, kept beside the table rather than in r4d.h so the M2XFP4 kernels' +// whole surface is in their own files (the plugin ABI's entries are r4d_plugin.h's). + +extern "C" { + +// M2XFP4 weight, fp8 activation: the MXFP4 rows at the paper's weight-side Sg-EM (arXiv 2601.19213 +// §4.4.2). Beside each E8M0 exponent per 32 K (whose adaptive bias the quantiser already folded +// in) the weight carries one meta byte per (row, 32 of K): four two-bit subgroup multipliers, the +// subgroup s covering columns [8s, 8s+8) of the group, value k_s in 0..3. The exact weight is +// e2m1mag[c&7] * sign(c) * 2^(scale-127) * (1 + k_s/4); r4d_m2xfp4.h folds it into the same e4m3 +// staging bytes through a second table index, so the fold, the Wref epilogue and the activation +// scale grids are the MXFP4 kernels'. `wm` is the [K/32][N] meta plane, `ldws` its row pitch (0 = +// N); the k=3 multipliers on odd-mantissa codes round as r4d_m2xfp4.h documents, up to 2^-4.4 +// relative. +void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws, long wm, long wref, long c, + int M, int K, int N, int TN, int as_group, int as_rs, long stream, + int ldws = 0, int ldc = 0); +void r4d_m2xfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda = 0); +long r4d_m2xfp4a8_tile_a_bytes(int M, int K); +int r4d_gemm_m2xfp4a8_tiled_group(void); +// The decode band (M <= 128). The plugin ABI's r4d_rad_gemm_m2xfp4a8_decode serves it in the +// engine, the split partial in the op's scratch as for mxfp4a8; this raw entry takes that scratch +// from the caller: KS * M * N * 4 bytes when KS > 1 (a KS of 2 runs as 4 where a 128-wide slab +// would run past K), 16 * M * N * 4 when KS is 0 (the widest split the rule picks), null only at +// KS 1. The arrival counters are the unit's own, one block per output buffer. +void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws, long wm, long wref, long c, + int M, int K, int N, int KS, int BK, int NT, int as_group, + int as_rs, long scratch, long scratch_bytes, long stream, + int lda = 0, int ldws = 0, int ldc = 0); +int r4d_gemm_m2xfp4a8_decode_max_m(void); + +} // extern "C" diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index c8e93c4d..8bdad947 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -466,6 +466,12 @@ int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*); int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs*, RadStream); int r4d_rad_gemm_mxfp4a8_gated(const RadArgs*, RadStream); int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs*); +/* M2XFP4 (the paper's weight-side Sg-EM): the same GEMM bands at the m2xfp4 encoding, one meta + * plane more (r4d_layout.cpp, m2xfp4). */ +int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs*, RadStream); +int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs*); +int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs*, RadStream); +int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs*); int r4d_rad_dequant_w4 (const RadArgs*, RadStream); int r4d_rad_rowtopk (const RadArgs*, RadStream); int64_t r4d_rad_rowtopk_scratch(const RadArgs*); @@ -676,6 +682,10 @@ int r4d_rad_layout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, co const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, void*, int64_t); +int r4d_rad_layout_m2xfp4(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_m2xfp4(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index dda19c07..1d333f19 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -5003,6 +5003,16 @@ static const RadConstraint cGemmMxfp4A8DecodeShortK[] = { static const RadConstraint cGemmMxfp4A8Tiled[] = { C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"), }; +/* The M2XFP4 rows (r4d_gemm_m2xfp4a8_*.hip): the same bands at the m2xfp4 encoding, whose dtype + * string alone separates them -- no skinny M2 row exists, so the decode row takes M <= 128 + * (N <= 36864) and the tiled row the rest: MXDEC outranks TILED wherever both match, as for + * mxfp4a8. */ +static const RadConstraint cGemmM2xfp4A8Decode[] = { + C_LE("M", 128), C_LE("N", 36864), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "m2xfp4"), +}; +static const RadConstraint cGemmM2xfp4A8Tiled[] = { + C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "m2xfp4"), +}; /* r4d_gemm_w8a8_tiled: the same kernel at radix 8. Its asym arm is not declared in r4d.h, so * `w8a8_asym` is absent from the dtype set. */ static const RadConstraint cGemmW8A8Tiled[] = { @@ -7831,6 +7841,42 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gemm_mxfp4a8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 }, +/* M2XFP4: the mxfp4a8 rows at the paper's weight-side Sg-EM (arXiv 2601.19213 §4.4.2) -- per 32 K + * one more byte of weight, four two-bit subgroup multipliers, folded into the same e4m3 staging + * bytes through r4d_m2xfp4.h's table. The bands, tunables (ks/bk/nt and tn resolve through the + * same cfg readers) and relayout contract are the OCP rows', with the meta plane in the stored + * weight's tail (r4d_layout.cpp, m2xfp4) and no skinny row: at these row counts the decode kernel + * covers the whole M <= 128 band, the tiled one prefill. */ +{ "gemm_m2xfp4a8_decode", "gemm_nt_q", "gemm", + "the M2XFP4 GEMM for the DECODE band: the mxfp4a8 decode kernel's split-K across workgroups with " + "a fused last-arriver reduction, the weight unpacked through LDS with its per-subgroup meta " + "multiplier, streaming weight loads", + "M <= 128; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, " + "[K/32][N] E8M0 exponents and per-row reference exponent, and the [K/32][N] meta plane in the " + "stored weight's tail; the split partial in the op's scratch", + "e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K (bias " + "folded) and a two-bit multiplier per 8 K folded into the element against a per-row reference, " + "bf16 C, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXDEC, + ROW(cGemmM2xfp4A8Decode), ROW(tGemmMxfp4Decode), nullptr, + nullptr, nullptr, r4d_rad_gemm_m2xfp4a8_decode, r4d_rad_gemm_m2xfp4a8_decode_scratch, + r4d_rad_layout_m2xfp4, r4d_rad_relayout_m2xfp4 }, + +{ "gemm_m2xfp4a8_tiled", "gemm_nt_q", "gemm", + "the M2XFP4 GEMM tiled for PREFILL row counts: the mxfp4a8 tiled kernel's 256-row block, the " + "activation re-tiled into the op's scratch, the weight with its meta multipliers unpacked once " + "per K slab into LDS", + "any M; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, " + "[K/32][N] E8M0 exponents and per-row reference exponent, and the [K/32][N] meta plane in the " + "stored weight's tail; the re-tiled activation in the op's scratch", + "e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K (bias " + "folded) and a two-bit multiplier per 8 K folded into the element against a per-row reference, " + "bf16 C, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_TILED, + ROW(cGemmM2xfp4A8Tiled), ROW(tGemmMxfp4Tiled), nullptr, + nullptr, nullptr, r4d_rad_gemm_m2xfp4a8_tiled, r4d_rad_gemm_m2xfp4a8_tiled_scratch, + r4d_rad_layout_m2xfp4, r4d_rad_relayout_m2xfp4 }, + /* Band read off the entry point's own rejection tests. */ { "gemm_w4a8_prefill", "gemm_nt_q", "gemm", "the 4-bit GEMM for PREFILL row counts, where the matrix pipe rather than the weight stream is " diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 32c54d1e..053ae877 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -4848,6 +4848,141 @@ static void mxfp4a8_m_invariant(const Plugin& pl, const char* row, int64_t N, in } +/* The M2XFP4 rows (r4d_gemm_m2xfp4a8_*.hip): mxfp4a8_numeric's shape checks at the m2xfp4 + * encoding -- a third plane of per-subgroup multipliers, whose every byte value is valid, drawn + * full range so k = 3 is in regular rotation, beside the bias-folded exponents. The bound is the + * mxfp4 row's plus the table's accepted k = 3 rounding: a quarter of the weights at up to 2^-4.4 + * each is about 1.2% of a whole dot, so 4e-2 holds the same margin the 1e-2 does there. The + * relayout is exercised for real: the weight operand takes codes and meta, and the stored blob the + * launch reads is this hook's output. The output starts as NaN, as there. */ +static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K, + int tn, bool ablk = false, std::vector extra = {}) { + if (!sel(row)) return; + char nm[160]; + std::string ex; + for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival); + std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld tn=%d%s%s", row, (long long)M, + (long long)N, (long long)K, tn, ablk ? " ascale=row x 128" : "", ex.c_str()); + const RadKernelInfo* r = find(pl, row); + if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } + const int64_t nblk = K / 32; + + Planes p; + rad_enc_clear(&p.enc); + rad_enc_copy_str(p.enc.scheme, "m2xfp4"); + rad_enc_add_plane(&p.enc, "codes", RAD_FP4E2M1, 1, 1); + rad_enc_add_plane(&p.enc, "scale", RAD_E8M0, 1, 32); + rad_enc_add_plane(&p.enc, "meta", RAD_U8, 1, 32); + p.size(N, K); + const int ic = p.find("codes"), is = p.find("scale"), im = p.find("meta"); + if (ic < 0 || is < 0 || im < 0) { ok(nm, false, "encoding has no m2xfp4 planes"); return; } + /* codes and exponents as mxfp4_fill draws them (deep: exponents the fold's subnormal floor + * reaches), the meta full range so every multiplier and every subgroup phase appears */ + mxfp4_fill(p, ic, is, N, K, 0x71u, true); + for (int64_t i = 0; i < (int64_t)p.data[(size_t)im].size(); ++i) + p.data[(size_t)im][(size_t)i] = (uint8_t)st_mix32((uint32_t)i ^ 0x4d2eu); + std::vector lp = { PI("N", N), PI("K", K), PI("group", 32) }; + std::vector wq, ws, wr; + const int rw = stored(r, lp, 2, p, { "codes", "meta" }, &wq); + const int rs = stored(r, lp, 3, p, { "scale" }, &ws); + const int rr = stored(r, lp, 6, p, { "scale" }, &wr); + if (rw != RAD_OK || rs != RAD_OK || rr != RAD_OK) { + ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs) + "/" + + std::to_string(rr)); + return; + } + + const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1; + std::vector ha((size_t)(M * K)); + std::vector av((size_t)(M * K)), as((size_t)(M * asc)); + for (int64_t i = 0; i < M; ++i) { + for (int64_t c = 0; c < asc; ++c) { + const uint32_t h = st_mix32((uint32_t)(i * asc + c) ^ 0xa5u); + as[(size_t)(i * asc + c)] = + ablk ? ((i + c) % 11 == 5 ? 0.0f : 0.002f * (float)(1 + h % 97)) + : 0.0125f * (float)(1 + h % 5); + } + for (int64_t k = 0; k < K; ++k) { + const bool zero = ablk && as[(size_t)(i * asc + k / 128)] == 0.0f; + const float v = zero ? 0.0f : mxfp4_act(i, k, 0x3cu); + rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, v); + av[(size_t)(i * K + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * K + k); + } + } + std::vector hy((size_t)(M * N), 0x7fc0); /* bf16 NaN */ + void* d_a = dalloc(ha.size()); + void* d_s = dalloc(as.size() * 4); + void* d_w = dalloc(wq.size()); + void* d_e = dalloc(ws.size()); + void* d_r = dalloc(wr.size()); + void* d_y = dalloc(hy.size() * 2); + if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_y, hy.data(), hy.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice); + st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice); + st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice); + std::vector ts = { + T(d_a, RAD_F8E4M3, { M, K }), + ablk ? T(d_s, RAD_F32, { M, asc }) : T(d_s, RAD_F32, { M }), + T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }), + T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(d_r, RAD_U8, { (int64_t)wr.size() }), + }; + absent(ts[5]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), + PS("dtype", "m2xfp4") }; + if (tn) ps.push_back(PI("tn", tn)); + for (const RadParam& p : extra) ps.push_back(p); + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + if (r->scratch) { + const int64_t sb = r->scratch(&a); + if (sb > 0) { + a.scratch = dalloc((size_t)sb); + a.scratch_bytes = sb; + if (!a.scratch) { ok(nm, false, "hipMalloc failed"); return; } + } + } + const int rc = r->launch(&a, (RadStream) nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { + ok(nm, false, "rc=" + std::to_string(rc)); + return; + } + st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost); + + /* Every column for small N, an odd stride otherwise (as mxfp4a8_numeric), always including the + * last column. The exact decode: the e2m1 code, the subgroup's stored multiplier, and the + * folded exponent. */ + const int64_t nstep = N > 96 ? (N / 96) | 1 : 1; + double num = 0, den = 0; + for (int64_t i = 0; i < M; ++i) + for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) { + double acc = 0; + for (int64_t k = 0; k < K; ++k) { + const uint8_t meta = p.data[(size_t)im][(size_t)(n * nblk + k / 32)]; + const int kk = (int)(((meta >> (2 * ((k % 32) / 8))) & 3)); + const double w = + (double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) * + (1.0 + kk / 4.0) * + (double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32); + acc += (double)av[(size_t)(i * K + k)] * w * + (ablk ? (double)as[(size_t)(i * asc + k / 128)] : 1.0); + } + if (!ablk) acc *= (double)as[(size_t)i]; + const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc; + num += d * d; + den += acc * acc; + } + const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num); + char d[96]; + std::snprintf(d, sizeof d, "rel_l2 %.3e", rel); + ok(nm, rel < 4e-2, d); +} + /* What givens_numeric runs: the sequential rotation to f16, or the dense rotation with either * quantiser. */ enum class GvCase { Rotate, DenseFp8, DenseI8 }; @@ -28003,6 +28138,18 @@ static void device_phase(const Plugin& pl) { mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 13, 272, 1152, 0, false, { PI("ks", ks), PI("bk", bk), PI("nt", nt) }); } + /* The M2XFP4 rows: the decode band's rule and band edges, the tiled row at both widths and + * past the tn crossover, and both activation grids, at the three-plane encoding. */ + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 272, 640, 0, false); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 272, 640, 0, true); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 40, 400, 2560, 0, true); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 128, 512, 2560, 0, true); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 5, 1040, 576, 0, true); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 96, 14336, 640, 0, true); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 40, 272, 640, 2, false); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 400, 640, 4, true); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 2100, 512, 2560, 0, true); + m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 272, 576, 2, true); gemm_case(pl, "gemm_w4a8_tiled", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4); gemm_case(pl, "gemm_w8a8_tiled", "w8a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K, 256*(K/128)*2); gemm_case(pl, "gemm_w4a8_prefill", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f28a146d..0f0fdf10 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -405,7 +405,7 @@ endif() # ================================================================== libr4d's kernels, on the host # # Some libr4d ops (the sandwich-norm joins, expert_scale) have no libref oracle by design -# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of fourteen units +# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of sixteen units # written against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins, # expert_scale, the QSA block selection, the runtime-LoRA pair, the F32 routing projection's tile # forms, GLM's mHC read with its chunk split, the F32-scale E4M3 GEMM's forms, GLM's KDA @@ -416,7 +416,8 @@ endif() # deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select, the host # arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, for the LoRA pair libref # itself when the test can load it, for KDA libref itself, and for the DSA split the unsplit -# kernels. +# kernels. The other two, the M2XFP4 decode and tiled GEMMs, are checked against an f64 decode of +# the weight. # # Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang # C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so @@ -431,14 +432,18 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_ ${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip ${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip ${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip - ${R4D_DIR}/r4d_dsa.hip) -set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa) + ${R4D_DIR}/r4d_dsa.hip + ${R4D_DIR}/r4d_gemm_m2xfp4a8_decode.hip ${R4D_DIR}/r4d_gemm_m2xfp4a8_tiled.hip) +# The M2XFP4 units' plugin entries call two cfg readers that r4d_rows.cpp defines, which is not in +# this build: cfg_stub.cpp defines them at their axis defaults, in both arms below. +set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa m2xfp4) set(R4D_EMU_BUILT OFF) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") # No fiber switch for this ISA. elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND NOT RAD_ASAN AND NOT RAD_TSAN) set_source_files_properties(${R4D_EMU_HIP} PROPERTIES LANGUAGE CXX COMPILE_OPTIONS "-x;c++") - add_library(r4d_emu_kernels OBJECT ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp) + add_library(r4d_emu_kernels OBJECT ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/cfg_stub.cpp + ${R4D_EMU}/emu/emu.cpp) target_include_directories(r4d_emu_kernels PUBLIC ${R4D_EMU}/emu ${R4D_EMU} ${R4D_DIR}) target_link_libraries(r4d_emu_kernels PUBLIC rad_abi) # As in libr4d: the joins must match the unfused chain bit for bit, so no FMA contraction. @@ -471,7 +476,8 @@ else() ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp ${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp ${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp - ${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp) + ${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp + ${R4D_EMU}/cfg_stub.cpp) get_filename_component(stem ${src} NAME_WE) set(lang "") if(src MATCHES "\\.hip$") @@ -508,7 +514,7 @@ else() endif() endif() if(R4D_EMU_BUILT) - foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa) + foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa m2xfp4) add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t}) endforeach() # The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel, @@ -519,7 +525,7 @@ if(R4D_EMU_BUILT) endforeach() set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse - r4d_emu_dsa + r4d_emu_dsa r4d_emu_m2xfp4 PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT}) # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can # load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within diff --git a/tests/r4d_emu/cfg_stub.cpp b/tests/r4d_emu/cfg_stub.cpp new file mode 100644 index 00000000..7bdea75e --- /dev/null +++ b/tests/r4d_emu/cfg_stub.cpp @@ -0,0 +1,17 @@ +/* cfg_stub.cpp -- the two tuned-configuration readers the M2XFP4 GEMM units call + * (r4d_cfg_mxfp4_decode, r4d_cfg_mxfp4_tiled), which libr4d defines on its declaration side + * (r4d_rows.cpp) beside the row tables. That side is not in the emu build, and every r4d_emu_* + * binary links every unit, so the readers are defined once here. Every axis default of + * tGemmMxfp4Decode and tGemmMxfp4Tiled is 0, the kernels' own rule, so reading the key or 0 is + * what r4d_rows.cpp's readers return for a caller with no tuned point. */ +#include "r4d_args.h" + +extern "C" void r4d_cfg_mxfp4_decode(const RadArgs* a, R4dMxDecCfg* out) { + out->ks = (int)rad_args_geti_or(a, "ks", 0); + out->bk = (int)rad_args_geti_or(a, "bk", 0); + out->nt = (int)rad_args_geti_or(a, "nt", 0); +} + +extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) { + out->tn = (int)rad_args_geti_or(a, "tn", 0); +} diff --git a/tests/r4d_emu/emu/hip/hip_runtime.h b/tests/r4d_emu/emu/hip/hip_runtime.h index 8f46b49e..3dbff0c3 100644 --- a/tests/r4d_emu/emu/hip/hip_runtime.h +++ b/tests/r4d_emu/emu/hip/hip_runtime.h @@ -169,7 +169,9 @@ inline void __threadfence() {} template inline T emu_atomic_fetch_add(T* p, T v) { const T o = *p; *p = o + v; return o; } /* The device allocations a unit makes for itself (counter blocks): host memory here. */ inline hipError_t hipMalloc(void** p, size_t n) { *p = std::calloc(n ? n : 1, 1); return *p ? 0 : 2; } +inline hipError_t hipMemset(void* p, int v, size_t n) { std::memset(p, v, n); return 0; } inline hipError_t hipMemsetAsync(void* p, int v, size_t n, hipStream_t) { std::memset(p, v, n); return 0; } +inline hipError_t hipFree(void* p) { std::free(p); return 0; } struct alignas(8) uint2 { unsigned x, y; }; struct alignas(16) uint4 { unsigned x, y, z, w; }; diff --git a/tests/r4d_emu/test_m2xfp4.cpp b/tests/r4d_emu/test_m2xfp4.cpp new file mode 100644 index 00000000..f6e08fa6 --- /dev/null +++ b/tests/r4d_emu/test_m2xfp4.cpp @@ -0,0 +1,405 @@ +/* tests/r4d_emu: the M2XFP4 x fp8 GEMMs (r4d_gemm_m2xfp4a8_decode.hip, r4d_gemm_m2xfp4a8_tiled.hip) + * on the host SIMT emulator. The container's m2xfp4 encoding (the paper's weight-side Sg-EM, + * arXiv 2601.19213 §4.4.2) is synthesised from random f32 weights by an in-test scalar quantiser + * implementing the spec: per group of 32 columns an E8M0 exponent with the adaptive bias (-1, 0, 1, + * drawn at random) folded into the stored byte, and a meta byte of four two-bit subgroup + * multipliers with k = 3 in heavy rotation; the codes are the e2m1 roundings of the exact + * dequantiser's inverse. + * The stored bytes are then built the way r4d_rad_relayout_m2xfp4 builds them (fragment-order + * codes, the meta plane appended in the exponents' [K/32][N] order), and both kernels run against + * an f64 CPU reference of the exact decode, at the FP8 WMMA's tolerance plus the table's accepted + * k = 3 rounding (rel_l2 < 4e-2, see run_cases). Cases cover both activation scale grids (per row, + * per (row, 128) with a zero block), M across the decode band's band edges (1, 8, 16, 40, 128) and + * the tiled row's, the one-fragment prefetch form (M <= 16), both K slabs (64 and 128), and a + * split-K launch on the decode kernel. + * + * The table itself is held to arithmetic first: every kM2xfp4Mag[d][k] cell must be the + * round-to-nearest-even e4m3 of e2m1mag * (1 + k/4) * 2^-d; the k = 0..2 rows must be exact while + * the product is a normal e4m3 value, and the k = 3 odd-mantissa entries must be the tie's even + * side (2.5, 5, 10 scaled by 2^-d). The unpack is held to the same arithmetic over every code at + * every (d, k). + * + * The declaration side (r4d_rows.cpp) is not in the emu build, so the two cfg readers it defines, + * which the units' plugin entries call, are stubbed in cfg_stub.cpp at their axis defaults (0 = the + * kernels' own rules), which is what an untuned call gets. This test calls the raw entries, so it + * runs no stub; everything it runs is the library's own code. + */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "r4d.h" +#include "r4d_m2xfp4.h" +#include +#include +#include +#include +#include +#include +#include + +extern const char* emu_last_kernel; + +/* ------------------------------------------------------------------ arithmetic e4m3 / e2m1 */ + +/* Round-to-nearest-even e4m3 (OCP FP8, 1-4-3, bias 7, subnormals at 2^-9, 0x7F/0xFF NaN), the + * conversion the device tables and the WMMA's own converts use. */ +static uint8_t rne_e4m3(double v) { + if (v == 0) return std::signbit(v) ? 0x80 : 0; /* the kernels keep a sign on zero */ + const uint8_t sign = v < 0 ? 0x80 : 0; + double a = std::fabs(v); + if (a > 480) return (uint8_t)(sign | 0x7E); + int e = 0; + while (a >= 2.0) { a *= 0.5; ++e; } + while (a < 1.0) { a *= 2.0; --e; } + int m; + if (e < -6) { /* subnormal: 2^-9 steps of the value itself */ + double q = std::fabs(v) * 512.0; + double fl = std::floor(q); + const double frac = q - fl; + int qi = (int)fl; + if (frac > 0.5 || (frac == 0.5 && (qi & 1))) ++qi; + if (qi >= 8) return (uint8_t)(sign | 0x08); /* up to min normal 2^-6 */ + return (uint8_t)(sign | qi); + } + double q = (a - 1.0) * 8.0; + m = (int)q; + const double frac = q - m; + if (frac > 0.5 || (frac == 0.5 && (m & 1))) ++m; + if (m == 8) { m = 0; ++e; } + return (uint8_t)(sign | ((e + 7) << 3) | m); +} + +static double e4m3_f64(uint8_t b) { + const double s = b & 0x80 ? -1.0 : 1.0; + const int e = (b >> 3) & 15, m = b & 7; + if (e == 0) return s * m * 0.001953125; /* 2^-9 steps */ + return s * std::ldexp(1.0 + m / 8.0, e - 7); +} + +/* The e2m1 magnitudes, and the quantiser's RNE code for a magnitude against them (ties to the even + * code, as the hardware's convert and the CPU reference agree). */ +static const double kE2m1Mag[8] = { 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0 }; +static uint8_t rne_e2m1(double v) { + double a = std::fabs(v); + int best = 0; + double bd = 1e300; + for (int i = 0; i < 8; ++i) { + const double d = std::fabs(a - kE2m1Mag[i]); + if (d < bd || (d == bd && !(best & 1))) { bd = d; best = i; } + } + return (uint8_t)(best | (v < 0 ? 8 : 0)); +} +static double e2m1_f64(uint8_t code) { + return (code & 8 ? -1.0 : 1.0) * kE2m1Mag[code & 7]; +} + +/* ------------------------------------------------------------------ the table checks */ + +static int check_lut() { + int fails = 0; + for (int d = 0; d < 16; ++d) + for (int k = 0; k < 4; ++k) + for (int m = 0; m < 8; ++m) { + const uint8_t got = (uint8_t)((kM2xfp4Mag[d][k][m >> 2] >> (8 * (m & 3))) & 0xFF); + const double exact = kE2m1Mag[m] * (1.0 + k / 4.0) * std::ldexp(1.0, -d); + const uint8_t want = rne_e4m3(exact); + if (got != want) { + std::printf("FAIL lut d=%d k=%d mag=%d: %02x, want %02x (%.6g)\n", d, k, m, + got, want, exact); + ++fails; + continue; + } + /* k = 0..2 exact wherever the product is a normal e4m3 value; k = 3 only the + * odd-mantissa magnitudes round, and to the tie's even side. */ + if (e4m3_f64(got) != exact) { + const bool k3tie = k == 3 && (m == 3 || m == 5 || m == 7); + const double rounded = k3tie ? std::ldexp(m == 3 ? 2.5 : m == 5 ? 5.0 : 10.0, -d) + : exact; + if (k3tie && e4m3_f64(got) == rounded) continue; + /* the subnormal floor: like r4d_mxfp4.h's table one binade earlier, the 2^-9 + * step rounds once the product falls in it; exactness is only claimed while + * the product is normal (>= 2^-6), and every k = 0..2 normal product is */ + if (k <= 2 && exact >= 0.015625 && std::fabs(exact) > 0) { + std::printf("FAIL lut k=%d d=%d mag=%d: %02x decodes %.6g, want %.6g\n", k, + d, m, got, e4m3_f64(got), exact); + ++fails; + } + } + } + /* and the k = 0 rows are r4d_mxfp4.h's, byte for byte (a memcmp would walk the [k] axis) */ + static const unsigned kM0[16][2] = { + {0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u}, {0x2c282000u, 0x3c383430u}, + {0x24201800u, 0x34302c28u}, {0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u}, + {0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u}, {0x03020100u, 0x0c080604u}, + {0x02010000u, 0x06040302u}, {0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u}, + {0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, + {0x00000000u, 0x00000000u}, + }; + for (int d = 0; d < 16; ++d) + if (kM2xfp4Mag[d][0][0] != kM0[d][0] || kM2xfp4Mag[d][0][1] != kM0[d][1]) { + std::printf("FAIL lut: the k=0 row d=%d is not kMxfp4Mag\n", d); + ++fails; + } + return fails; +} + +/* The unpack against arithmetic, over every 16-bit pattern at both halves of a word and random + * words, at every (d, k). */ +static int check_unpack() { + int fails = 0; + auto one = [&](uint32_t word, int d, int k) { + uint32_t lo = 0, hi = 0; + r4d_m2xfp4_unpack8(word, d, k, &lo, &hi); + for (int j = 0; j < 8; ++j) { + const uint8_t code = (uint8_t)((word >> (4 * j)) & 0xF); + const uint8_t got = (uint8_t)((j < 4 ? (lo >> (8 * j)) : (hi >> (8 * (j - 4)))) & 0xFF); + const double exact = e2m1_f64(code) * (1.0 + k / 4.0) * std::ldexp(1.0, -d); + const uint8_t want = rne_e4m3(exact); + if (got != want) { + if (fails < 12) + std::printf("FAIL unpack w=%08x d=%d k=%d j=%d: %02x, want %02x\n", word, d, k, + j, got, want); + ++fails; + } + } + }; + for (int d = 0; d < 16; ++d) + for (int k = 0; k < 4; ++k) { + for (uint32_t v = 0; v < 65536; ++v) { + one(v, d, k); + if (v < 256) { one(v << 24, d, k); one(v << 16, d, k); } + } + } + std::mt19937 rng(11); + for (int i = 0; i < 20000; ++i) one(rng(), (int)(rng() % 16), (int)(rng() % 4)); + return fails; +} + +/* ------------------------------------------------------------------ the GEMM cases */ + +struct Case { + const char* name; + const char* kernel; // the decode row's two forms, or the tiled row + int M, N, K; + bool ablk; // the activation scale per (row, 128 of K), with a zero block + int ks; // the decode launch's split (0 = the kernel's rule) +}; + +/* The in-test quantiser's planes for one weight [N][K]: codes (packed e2m1, element 2j in bits + * 0-3 of byte j), the per-(row, 32) exponents with the bias folded in, the meta bytes, and the + * f64 exact dequant the reference multiplies. */ +struct M2Weight { + std::vector codes; // [N][K/2] + std::vector scale; // [N][K/32] + std::vector meta; // [N][K/32] + std::vector exact; // [N][K], the spec's decode +}; + +static M2Weight m2_quantise(const std::vector& w, int N, int K, std::mt19937& rng) { + const int nblk = K / 32; + M2Weight m; + m.codes.assign((size_t)N * K / 2, 0); + m.scale.assign((size_t)N * nblk, 0); + m.meta.assign((size_t)N * nblk, 0); + m.exact.assign((size_t)N * K, 0.0); + std::uniform_int_distribution bias(-1, 1); + for (int n = 0; n < N; ++n) + for (int b = 0; b < nblk; ++b) { + double absmax = 0.0; + for (int j = 0; j < 32; ++j) absmax = std::max(absmax, (double)std::fabs(w[(size_t)n * K + b * 32 + j])); + /* the exponent the six-magnitude grid needs, plus the adaptive bias, folded into the + * stored byte; a zero group keeps a small exponent, its codes all zero */ + int e8 = absmax > 0 ? (int)std::ceil(std::log2(absmax / 6.0)) : -30; + e8 += bias(rng); + if (e8 < -30) e8 = -30; + if (e8 > 30) e8 = 30; + const uint8_t sbyte = (uint8_t)(e8 + 127); + uint8_t mbyte = 0; + for (int s = 0; s < 4; ++s) { + /* k = 3 in heavy rotation, the multiplier the rounding lives on */ + const int k = (n + b + s * 3 + (int)(rng() % 2)) & 3; + mbyte |= k << (2 * s); + for (int j = 0; j < 8; ++j) { + const int col = b * 32 + s * 8 + j; + const double scale = std::ldexp(1.0 + k / 4.0, e8); + const uint8_t code = rne_e2m1(w[(size_t)n * K + col] / scale); + m.codes[(size_t)n * K / 2 + col / 2] |= + (uint8_t)(code << (4 * (col & 1))); + m.exact[(size_t)n * K + col] = + e2m1_f64(code) * std::ldexp(1.0, e8) * (1.0 + k / 4.0); + } + } + m.scale[(size_t)n * nblk + b] = sbyte; + m.meta[(size_t)n * nblk + b] = mbyte; + } + return m; +} + +/* The stored weight, as r4d_rad_relayout_m2xfp4 writes it: codes in WMMA fragment order, then the + * meta plane in the exponents' [K/32][N] order, and the exponent plane and per-row reference + * beside them. */ +static void m2_store(const M2Weight& m, int N, int K, std::vector* wq, + std::vector* ws, std::vector* wm, + std::vector* wref) { + const int nblk = K / 32; + wq->assign((size_t)N * K / 2 + (size_t)nblk * N, 0); + ws->assign((size_t)nblk * N, 0); + wm->assign((size_t)nblk * N, 0); + wref->assign(N, 0); + /* fragment order: slot = ((t * ks + ksi) * 32 + lh * 16 + r) * 4 + bin, element 2j in the low + * nibble of byte j (r4d_layout.cpp, mx_slot) */ + const int ks16 = K / 16; + for (int n = 0; n < N; ++n) { + const int t = n / 16, r = n % 16; + uint8_t ref = 0; + for (int b = 0; b < nblk; ++b) { + const uint8_t s = m.scale[(size_t)n * nblk + b]; + (*ws)[(size_t)b * N + n] = s; + (*wm)[(size_t)b * N + n] = m.meta[(size_t)n * nblk + b]; + if (s > ref) ref = s; + } + (*wref)[n] = ref; + for (int k = 0; k < K; ++k) { + const uint8_t code = (uint8_t)((m.codes[(size_t)n * K / 2 + k / 2] >> (4 * (k & 1))) & 0xF); + const int ksi = k / 16, kin = k % 16; + const int lh = kin / 8, bin = (kin % 8) / 2; + const size_t idx = (size_t)((t * ks16 + ksi) * 32 + lh * 16 + r) * 4 + bin; + (*wq)[idx] |= (uint8_t)(code << (4 * (k & 1))); + } + } +} + +static double bf16_f64(uint16_t h) { + const double s = h & 0x8000 ? -1.0 : 1.0; + const int e = (h >> 7) & 0xFF, m = h & 0x7F; + if (e == 0) return s * m * std::ldexp(1.0, -133); /* zero / bf16 subnormal */ + return s * std::ldexp(1.0 + m / 128.0, e - 127); +} + +static int run_cases() { + static const Case all[] = { + { "decode1, K 128, rule split 16, per-row scales", + "(r4d_gemm_m2xfp4a8_decode1_kernel<128, 16, false, false>)", 1, 48, 128, false, 0 }, + { "decode1, K 64, split 4", "(r4d_gemm_m2xfp4a8_decode1_kernel<64, 4, false, false>)", + 8, 16, 64, false, 4 }, + { "decode1, M 16, block scales", "(r4d_gemm_m2xfp4a8_decode1_kernel<128, 2, false, true>)", + 16, 128, 256, true, 2 }, + { "decode, M 40 three fragments, odd K slab 192", + "(r4d_gemm_m2xfp4a8_decode_kernel<64, 1, 3, false, false>)", 40, 272, 192, false, 1 }, + { "decode, M 128 all fragments, block scales with a zero block", + "(r4d_gemm_m2xfp4a8_decode_kernel<128, 1, 8, false, true>)", 128, 128, 128, true, 1 }, + { "tiled, TN 2 just past the decode band, wide slab", + "(r4d_gemm_m2xfp4a8_tiled_kernel<2, 128, false>)", 129, 64, 128, false, 0 }, + { "tiled, TN 2, K 192 takes the 64 slab", + "(r4d_gemm_m2xfp4a8_tiled_kernel<2, 64, false>)", 300, 64, 192, false, 0 }, + { "tiled, TN 2, block scales", "(r4d_gemm_m2xfp4a8_tiled_kernel<2, 128, true>)", + 256, 128, 128, true, 0 }, + }; + int fails = 0, cases = 0; + for (const Case& c : all) { + std::mt19937 rng(2000 + cases); + std::normal_distribution nd(0.0, 1.0); + const int nkb = (c.K + 127) / 128; + /* random f32 weights -> the m2xfp4 planes */ + std::vector wf((size_t)c.N * c.K); + for (auto& v : wf) v = (float)(3.5 * nd(rng)); + const M2Weight m = m2_quantise(wf, c.N, c.K, rng); + std::vector wq, ws, wm, wref; + m2_store(m, c.N, c.K, &wq, &ws, &wm, &wref); + /* fp8 activations and their grid. The bytes are the quantised values; the grid's scale is + * applied once, where the kernel applies it: per row in the epilogue, per (row, 128) at + * each boundary -- the reference multiplies the same way. */ + const int PA = c.ablk ? nkb : 1; + std::vector a((size_t)c.M * c.K); + std::vector as((size_t)c.M * PA); + for (int i = 0; i < c.M; ++i) + for (int q = 0; q < PA; ++q) { + /* block 1 of every fourth row is zero: the carried-scale path */ + const float s = c.ablk && i % 4 == 1 && q == 1 + ? 0.0f + : std::ldexp(1.0f, (int)((rng() % 7) - 3)) * (1.0f + (rng() % 97) / 97.0f); + as[(size_t)i * PA + q] = s; + } + for (int i = 0; i < c.M; ++i) + for (int k = 0; k < c.K; ++k) { + const float block_scale = as[(size_t)i * PA + (c.ablk ? k / 128 : 0)]; + const float v = (float)(nd(rng) * 2.0); + /* a zero-scale block's activation bytes are zero (the block-scaled quantisers + * produce nothing there), and the kernels carry the previous scale through */ + a[(size_t)i * c.K + k] = + block_scale == 0.0f ? 0 : rne_e4m3(v / block_scale); + } + /* the f64 reference: the activation's bytes (times the block grid, when there is one) and + * the exact weight decode, which already carries its 2^(scale - 127) */ + std::vector reff((size_t)c.M * c.N); + for (int i = 0; i < c.M; ++i) + for (int n = 0; n < c.N; ++n) { + double acc = 0.0; + for (int k = 0; k < c.K; ++k) + acc += e4m3_f64(a[(size_t)i * c.K + k]) * + (c.ablk ? (double)as[(size_t)i * PA + k / 128] : 1.0) * + m.exact[(size_t)n * c.K + k]; + if (!c.ablk) acc *= (double)as[(size_t)i]; + reff[(size_t)i * c.N + n] = acc; + } + /* launch. The scratch is sized for the widest split the band's rule can pick (16), which + * the ABI's scratch hook bounds the same way; the arrival counters are the unit's own, + * one block per output buffer. */ + std::vector got((size_t)c.M * c.N, 0x7777); + const long wq_ptr = (long)(uintptr_t)wq.data(); + const long scratch_bytes = 16l * c.M * c.N * (long)sizeof(float); + std::vector scratch((size_t)(scratch_bytes / sizeof(float)), 0.0f); + emu_last_kernel = ""; + ++cases; + if (std::strstr(c.kernel, "tiled")) { + std::vector at((size_t)r4d_m2xfp4a8_tile_a_bytes(c.M, c.K)); + r4d_m2xfp4a8_tile_a((long)(uintptr_t)a.data(), (long)(uintptr_t)at.data(), c.M, c.K, + 0, 0); + r4d_gemm_m2xfp4a8_tiled((long)(uintptr_t)at.data(), (long)(uintptr_t)as.data(), + wq_ptr, (long)(uintptr_t)ws.data(), (long)(uintptr_t)wm.data(), + (long)(uintptr_t)wref.data(), (long)(uintptr_t)got.data(), + c.M, c.K, c.N, 0, c.ablk ? 128 : 0, PA, + 0, c.N, c.N); + } else { + r4d_gemm_m2xfp4a8_decode((long)(uintptr_t)a.data(), (long)(uintptr_t)as.data(), + wq_ptr, (long)(uintptr_t)ws.data(), (long)(uintptr_t)wm.data(), + (long)(uintptr_t)wref.data(), (long)(uintptr_t)got.data(), + c.M, c.K, c.N, c.ks, 0, 0, c.ablk ? 128 : 0, PA, + (long)(uintptr_t)scratch.data(), scratch_bytes, 0, 0, c.N, + c.N); + } + /* every launch lands on one form; a moved bound shows by name */ + if (!std::strstr(emu_last_kernel, c.kernel)) { + std::printf("FAIL %s: ran %s, want %s\n", c.name, + emu_last_kernel ? emu_last_kernel : "(nothing)", c.kernel); + ++fails; + continue; + } + double num = 0, den = 0, worst = 0; + for (size_t i = 0; i < reff.size(); ++i) { + const double d = bf16_f64(got[i]) - reff[i]; + num += d * d; + den += reff[i] * reff[i]; + worst = std::max(worst, std::fabs(d) / (std::fabs(reff[i]) + 1e-3)); + } + const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num); + /* The FP8 WMMA's tolerance, plus the table's accepted k = 3 rounding: the mxfp4 row's + * 1e-2 with the ~1.2% whole-dot contribution a full rotation of k = 3 subgroups adds + * (a quarter of the weights at up to 2^-4.4 each). Cancellation can make a single + * element's relative error unbounded, so the aggregate is what is held. */ + if (rel >= 4e-2) { + std::printf("FAIL %s: rel_l2 %.3e, worst %.3e\n", c.name, rel, worst); + ++fails; + } + } + std::printf("%d gemm case(s), %d failure(s)\n", cases, fails); + return fails; +} + +int main() { + int fails = check_lut(); + fails += check_unpack(); + fails += run_cases(); + if (fails) std::printf("FAIL m2xfp4 (%d)\n", fails); + return fails ? 1 : 0; +} diff --git a/tools/kbench_core.cpp b/tools/kbench_core.cpp index 628d08f2..5d0e9ab5 100644 --- a/tools/kbench_core.cpp +++ b/tools/kbench_core.cpp @@ -60,6 +60,10 @@ const std::vector g_tol = { * gated GEMM also writes an E4M3 twin of its result, which a rounding difference in the GEMM * moves by whole code steps (see g_opd_tol). */ { "gemm_nt_q_gated", "*", 3e-2 }, + /* The m2xfp4 fold's k = 3 multipliers round the odd-mantissa magnitudes as r4d_m2xfp4.h + * documents, up to 2^-4.4 relative on a quarter of the weights; r4d_selftest holds these rows + * to the same 4e-2. */ + { "gemm_nt_q", "m2xfp4", 4e-2 }, { "gemm_nt", "bf16", 8e-3 }, { "gemm_nt", "f16", 4e-3 }, { "gemm_nt", "f32", 2e-5 },