This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/libr4d/r4d_gemm_m2xfp4a8_decode.hip
T

652 lines
31 KiB
Plaintext

// 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 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 everything downstream of the fold -- the Wref epilogue, the
// activation scale grids, the split -- is the mxfp4 kernel's unchanged.
//
// 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
// traffic the row gives up for the extra half stop of precision.
//
// 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). Nothing else moves: the split, slab and load
// rule, the fused last-arriver reduction and its counters, the scratch contract and the
// concurrency promise are the mxfp4 decode row's, with this row's own state (its counters are
// keyed on the output, like the original's).
#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 <cstdint>
#include <map>
#include <mutex>
#include <stdexcept>
#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 <bool NT, typename T>
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 <int DTM>
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 <int DTM, int DKS, bool ABLK>
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 <int DBK, int DKS, int DTM, bool NT, bool ABLK>
__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<NT>((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<DTM, DKS, ABLK>(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 <int DBK, int DKS, bool NT, bool ABLK>
__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<NT>((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<DTM, DKS, ABLK>(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 now ride the op's scratch (m2d_partial_bytes); the per-output library
// allocation this replaced was a pointer a recorded pass could not relocate.
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule).
// The mxfp4 decode kernel's rule: the meta byte adds weight-stream traffic, not work at any of the
// points the rule trades, so the rule itself carries over. 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;
}
/* The scratch: the split partial when ks > 1, then the arrival counters. The counters live in
* the scratch rather than in a library-owned allocation because the scratch is a declared op
* buffer: a recorded pass relocates it with the other operands, while a pointer the library
* allocated itself is baked into the recorded kernarg and cannot be relocated. */
constexpr size_t m2d_ctr_count() { return R4D_M2D_MAX_N / (R4D_M2D_DWN * 16); }
long m2d_partial_bytes(int M, int N, int ks) {
return (ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0) +
(long)m2d_ctr_count() * (long)sizeof(unsigned);
}
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 part of a partitioned weight reads windows of larger planes; 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 || scratch_bytes < m2d_partial_bytes(M, N, ks))
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the op's scratch is shorter than the split "
"partial and the arrival counters; the scratch hook sizes it");
float* P = (float*)scratch;
unsigned* cnt = (unsigned*)((unsigned char*)P +
(ks > 1 ? (size_t)ks * (size_t)M * (size_t)N * sizeof(float) : 0));
/* Every launch enters with the counters zero: the scratch is shared across ops, and a replayed
* pass writes the same slots. One 1.1 KiB memset beside the launch is not measurable. */
if (hipMemsetAsync(cnt, 0, m2d_ctr_count() * sizeof(unsigned), (hipStream_t)stream) != hipSuccess)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: zeroing the arrival counters 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<BK_, KS_, TM_, NT_, AB_>), 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<BK_, KS_, NT_, AB_>), 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(M, N, KS) long; `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;
int rc = gemm_ops(a, &g, 1, /*parts=*/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);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
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, mp.n);
if (rc != RAD_OK) return rc;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
const long long kb = (g.K + 127) / 128;
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order: the part
// window opens at n0 of it as of the exponent plane, at n0 * K / 2 of the codes.
const long meta0 = (long)g.N * g.K / 2;
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
R4D_TRY("gemm_m2xfp4a8_decode",
m2d_launch(r4d_addr(g.a) + p * g.K, r4d_addr(g.ascale) + (long)(p * kb * 4),
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
r4d_addr(g.b) + meta0 + n0, r4d_addr(g.bref) + n0,
r4d_addr(g.y) + n0 * 2,
(int)g.M, (int)g.K, (int)np, t.ks, t.bk, t.nt, as_group, as_rs,
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes,
(int)(mp.lda ? mp.lda : 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. Parts of a
* partitioned weight split at their own N and run in turn sharing the scratch, so the bound is the
* largest part's. */
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);
long long bound[4];
mx_part_bounds(N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound);
int64_t worst = 0;
for (int i = 0; i < 3; ++i) {
const long long np = bound[i + 1] - bound[i];
if (np < 16) continue;
int ks = 1;
for (int m = 1; m <= (int)M; ++m) {
const int k = m2d_plan(m, (int)K, (int)np, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
}
const int64_t b = (int64_t)m2d_partial_bytes((int)M, (int)np, ks);
if (b > worst) worst = b;
}
const int64_t ctr = (int64_t)m2d_ctr_count() * (int64_t)sizeof(unsigned);
return worst > ctr ? worst : ctr;
}