libr4d: givens_quant_act_fp8 kernel; mxfp4a8 GEMMs take parts as launches over windows

The rotate+scale+quantise kernel does a (part, group) per wave with the stages' tables prefetched.
The three MXFP4 GEMM rows learn row pitches (lda, ldws, ldc) and launch once per weight part; the
layout hook accepts the codes/exponent planes of a givens-encoded weight. r4d_selftest checks the
kernel against an f64 rotation and every GEMM row's parts against the planes' meaning.
This commit is contained in:
Malic Zilyas committed 2026-10-08 23:35:43 +02:00
1 parent 1213c05cd8
commit 36e3b78c76
11 files changed
+626 -87

No files matched your search

+1
View File
@@ -123,6 +123,7 @@ set(R4D_UNITS
"r4d_gemm_fp8a16_nt_m1|"
"r4d_gemm_fp8a8|"
"r4d_quant_act_fp8|"
"r4d_givens_quant_act_fp8|"
"r4d_fused_quant_fp8|"
"r4d_gram_accum_fp8|"
"r4d_qsa_block_key_bf16|"
+6 -3
View File
@@ -570,7 +570,8 @@ void r4d_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, i
// as_group 0 = one f32 activation scale per row, 128 = one per (row, 128 of K) at row stride as_rs.
void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW,
int as_group, int as_rs, long stream);
int as_group, int as_rs, long stream,
int lda = 0, int ldws = 0, int ldc = 0);
int r4d_gemm_mxfp4a8_nt_m64_max_m(void);
int r4d_gemm_mxfp4a8_nt_m64_group(void);
// The same weight tiled for PREFILL: a 256-row block reads A fragments straight from a
@@ -579,8 +580,10 @@ int r4d_gemm_mxfp4a8_nt_m64_group(void);
// the per-wave column width in 16-column fragments. as_group 0 = one f32 activation scale per row,
// 128 = one per (row, 128 of K) at row stride as_rs.
void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int TN, int as_group, int as_rs, long stream);
void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream);
int M, int K, int N, int TN, int as_group, int as_rs, long stream,
int ldws = 0, int ldc = 0);
// `lda` is the activation's row pitch in bytes (0 = K), for a window of a wider plane.
void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda = 0);
long r4d_mxfp4a8_tile_a_bytes(int M, int K);
int r4d_gemm_mxfp4a8_tiled_group(void);
// The DECODE band (M <= 128) is r4d_rad_gemm_mxfp4a8_decode alone: its split-K partial is the op's
+54 -3
View File
@@ -326,7 +326,7 @@ struct GemmOps {
* the block-scaled fp8 family's quantisers, which every fused producer in arch/common writes) is
* group 128, read at the operand's own row stride. Anything else is refused by shape: a grid read
* at the wrong width is an answer that is merely wrong. */
static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) {
static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs, int parts = 1) {
const RadTensor* s = g.ascale;
if (!s || g.M <= 0) return R4D_NO(RAD_E_INVAL);
long long cols = 1, rstride = 1;
@@ -340,11 +340,62 @@ static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) {
rstride = cols;
}
const long long kb = (g.K + 127) / 128;
if (cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; }
if (cols == kb && rstride >= kb) { *group = 128; *rs = (int)rstride; return RAD_OK; }
/* PARTS: the activation's copies sit side by side in a row, so its scale row is `parts` times
* as long; each part reads its own kb of them at the row stride. */
if (parts == 1 && cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; }
if (cols == kb * parts && rstride >= kb * parts) { *group = 128; *rs = (int)rstride; return RAD_OK; }
return R4D_NO(RAD_E_SHAPE);
}
/* THE PARTS OF A PARTITIONED MXFP4 WEIGHT (gemm_nt_q's `pb1`/`pb2`), as launches.
*
* A fused projection whose pieces were rotated apart (ParoQuant: gate|up, q|k|v) has one copy of
* the activation a piece, written side by side in a row of `a` -- [M, parts * K] -- and its scales
* the same, so the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet THEIR copy. A part is
* then the ordinary product over a window of the planes: the activation from byte p * K of each row
* and its scales from p * ceil(K/128), the fragment-order weight from tile n0 / 16 (its bytes are
* n0 * K / 2 in), the exponents and reference from column n0, the output from column n0, the last
* three with the full planes' row pitch. So the kernels learn only row pitches (`lda`, `ldws`,
* `ldc`) and a part is one launch of the kernel the shape would have picked anyway.
*
* `pb1` = 0 is one part and `pb2` = 0 ends the second part at N, as libref reads them. Bounds are
* whole 16-row tiles (the weight's fragment unit). Returns the parts in `p`, K corrected to the
* op's own (gemm_ops read the row's width, which is parts * K), and the activation's row pitch in
* `lda`. */
struct MxParts {
int n = 1;
long long n0[3] = { 0, 0, 0 }, n1[3] = { 0, 0, 0 };
long long lda = 0; /* 0: the plane's own K */
};
static inline int mx_parts(const RadArgs* a, GemmOps* g, MxParts* p) {
const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0);
p->n = 1;
p->n0[0] = 0;
p->n1[0] = g->N;
p->lda = 0;
if (pb1 <= 0 && pb2 <= 0) return RAD_OK;
const long long K = r4d_geti_or(a, "K", 0);
if (K <= 0) return R4D_NO(RAD_E_INVAL);
const long long e1 = pb1 > 0 ? (pb1 < g->N ? pb1 : g->N) : g->N;
long long e2 = pb2 > 0 ? (pb2 < g->N ? pb2 : g->N) : g->N;
if (e2 < e1) e2 = e1;
const long long bound[4] = { 0, e1, e2, g->N };
const int segs = e2 < g->N ? 3 : (e1 < g->N ? 2 : 1);
if (g->K != (long long)segs * K || (e1 % 16) || (e2 % 16)) return R4D_NO(RAD_E_SHAPE);
p->n = 0;
for (int i = 0; i < 3; ++i)
if (bound[i + 1] > bound[i]) {
p->n0[p->n] = bound[i];
p->n1[p->n] = bound[i + 1];
++p->n;
}
if (p->n != segs) return R4D_NO(RAD_E_SHAPE); /* an empty middle part has no copy to meet */
p->lda = g->K;
g->K = K;
return RAD_OK;
}
/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major and the weight is
* an opaque packed blob whose element count the layout hook owns -- so the weight's SHAPE is not
* checked here beyond being present, which is deliberate: the byte count that matters is the one
+53 -28
View File
@@ -119,8 +119,8 @@ template <int DTM, int DKS, bool ABLK>
static __device__ __forceinline__ void mxd_epilogue(
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int N, int n0, int wave, int col, int kb8, int ks,
int kb_end, unsigned* s_last, float* sR) {
__hip_bfloat16* __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_MXD_DWN * 32, BND = R4D_MXD_DWN * 16;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
const int tid = threadIdx.x;
@@ -149,7 +149,7 @@ static __device__ __forceinline__ void mxd_epilogue(
#pragma unroll
for (int e = 0; e < 8; ++e)
o.h[e] = (__hip_bfloat16)(ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i]);
*(mxd_u4*)(C + (size_t)m * N + nb) = o.v;
*(mxd_u4*)(C + (size_t)m * ldc + nb) = o.v;
}
}
}
@@ -189,7 +189,7 @@ static __device__ __forceinline__ void mxd_epilogue(
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 * N + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
C[(size_t)m * ldc + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
}
}
}
@@ -199,7 +199,8 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs, int lda, int ldws,
int ldc) {
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
constexpr int STR = DBK + R4D_MXD_PAD;
@@ -245,7 +246,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
*(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
*(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * lda + k0 + c);
}
}
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3
@@ -269,7 +270,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern
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 * N + gc + q]);
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * ldws + gc + q]);
unsigned int lo, hi;
r4d_mxfp4_unpack8(q ? wv[1] : wv[0], d, &lo, &hi);
*(mxd_u2*)(&sW[(r + q) * STR + kloc]) = mxd_u2{lo, hi};
@@ -302,7 +303,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
mxd_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);
}
@@ -318,7 +319,8 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_ker
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
__hip_bfloat16* __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_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
@@ -381,7 +383,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_ker
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1;
ra[j] = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
ra[j] = *(const mxd_u4*)(A + (size_t)rc * lda + k0 + c);
}
}
const int kstep0 = k0 / 16;
@@ -392,7 +394,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_ker
rw[it] = mxd_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 * N + s_gc[it] + q];
for (int q = 0; q < VEC; ++q) rd[it][q] = (int)Ws[(size_t)blk * ldws + s_gc[it] + q];
}
};
auto store = [&]() {
@@ -450,7 +452,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_ker
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
mxd_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);
}
@@ -508,7 +510,7 @@ long mxd_partial_bytes(int M, int N, int ks) {
void mxd_launch(long a, long ascale, long wq, long ws, 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) {
long scratch_bytes, int lda, int ldws, int ldc) {
if (M < 1 || M > R4D_MXD_MTILE * R4D_MXD_MAX_TM)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: M must be 1..128");
if (N < 16 || N % 16 || N > R4D_MXD_MAX_N)
@@ -543,10 +545,10 @@ void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M,
auto Cp = (__hip_bfloat16*)c;
#define MXD_L(BK_, KS_, TM_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode_kernel<BK_, KS_, TM_, NT_, AB_>), grid, block, 0, \
st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
#define MXD_L1(BK_, KS_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode1_kernel<BK_, KS_, NT_, AB_>), grid, block, 0, st, \
Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
#define MXD_AB(BK_, KS_, TM_, NT_) \
{ if (ablk) MXD_L(BK_, KS_, TM_, NT_, true); else MXD_L(BK_, KS_, TM_, NT_, false); }
#define MXD_NT(BK_, KS_, TM_) \
@@ -583,35 +585,58 @@ extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) {
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);
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_mxfp4a8_decode_max_m() || g.N > R4D_MXD_MAX_N) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
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);
R4D_TRY("gemm_mxfp4a8_decode",
mxd_launch(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), 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));
const long long kb = (g.K + 127) / 128;
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_mxfp4a8_decode",
mxd_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.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 core sizes the op's scratch from this. `M` is the band's widest, and a narrower M can split
* wider (the fill rule asks for more blocks at M <= 24), so the size is the widest split over the
* band times its widest M -- an upper bound on every launch the band can make. */
* band times its widest M -- an upper bound on every launch the band can make. A partitioned
* weight launches each part at ITS rows, which splits wider than the whole would, so the bound is
* the largest of the parts' (they run one after another and share the scratch). */
extern "C" int64_t r4d_rad_gemm_mxfp4a8_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_mxfp4a8_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 = mxd_plan(m, (int)K, (int)N, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0);
const long long e1 = pb1 > 0 ? (pb1 < N ? pb1 : N) : N;
long long e2 = pb2 > 0 ? (pb2 < N ? pb2 : N) : N;
if (e2 < e1) e2 = e1;
const long long bound[4] = { 0, e1, e2, N };
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 = mxd_plan(m, (int)K, (int)np, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
}
const int64_t b = (int64_t)mxd_partial_bytes((int)M, (int)np, ks);
if (b > worst) worst = b;
}
return (int64_t)mxd_partial_bytes((int)M, (int)N, ks);
return worst;
}
+31 -14
View File
@@ -115,7 +115,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int WV, int SK, int as_rs) {
int M, int K, int N, int WV, int SK, int as_rs, int lda, int ldws, int ldc) {
extern __shared__ float red[];
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
const int col_local = wave / SK, ksplit = wave % SK;
@@ -189,7 +189,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
for (int i = 0; i < MT; i++) {
int r = (mt0 + i) * 16 + nlane;
r = r < M - 1 ? r : M - 1;
const unsigned int* pa = (const unsigned int*)(A + (size_t)r * K + kg + mhalf);
const unsigned int* pa = (const unsigned int*)(A + (size_t)r * lda + kg + mhalf);
af[i][0] = (int)pa[0];
af[i][1] = (int)pa[1];
}
@@ -200,7 +200,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
// wave reads 128 contiguous bytes. In checkpoint order these would be sixteen rows K/2 bytes
// apart -- a fully strided read on the operand that dominates traffic.
const unsigned int wv = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane];
const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * N + n]));
const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * ldws + n]));
#pragma unroll
for (int i = 0; i < MT; i++)
acc[j][i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(af[i], wf, acc[j][i]);
@@ -232,7 +232,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
if (n >= N || m >= M) continue;
float v = 0.f;
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
C[(size_t)m * N + n] =
C[(size_t)m * ldc + n] =
(__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * (ABLK ? 1.f : As[m]));
}
}
@@ -243,7 +243,14 @@ extern "C" int r4d_gemm_mxfp4a8_nt_m64_group(void) { return R4D_GEMM_MXFP4_GROUP
extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW,
int as_group, int as_rs, long stream) {
int as_group, int as_rs, long stream,
int lda, int ldws, int ldc) {
// The operands of one PART of a partitioned weight (ParoQuant) are windows of larger planes:
// the activation a row of lda bytes, the exponents a row of ldws, the output a row of ldc.
// 0 is the plane's own width, which is every other caller.
if (!lda) lda = K;
if (!ldws) ldws = N;
if (!ldc) ldc = N;
if (M < 1 || M > R4D_GEMM_MXFP4_MAX_M)
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: M must be 1..64");
if (N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: N must be a multiple of 16");
@@ -273,9 +280,10 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
#define LAUNCH(MTv, NPv) \
do { \
if (ablk) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, true>), grid, block, \
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs, lda, ldws, ldc); \
else hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, false>), grid, block, \
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs, \
lda, ldws, ldc); \
} while (0)
#define LAUNCH_MB(NPv) switch (MB) { \
case 1: LAUNCH(1, NPv); break; \
@@ -309,18 +317,27 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
* so gemm_nt_q carries it as a trailing optional weight operand. Without it the fold has no
* reference and every element would be scaled against zero. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
const int group = r4d_gemm_mxfp4a8_nt_m64_group();
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
if (rc != RAD_OK) return rc;
Cfg c;
rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c);
if (rc != RAD_OK) return rc;
R4D_TRY("gemm_mxfp4a8_nt_m64",
r4d_gemm_mxfp4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
as_group, as_rs, (long)(uintptr_t)s));
const long long kb = (g.K + 127) / 128;
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_mxfp4a8_nt_m64",
r4d_gemm_mxfp4a8_nt_m64(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.bref) + n0, r4d_addr(g.y) + n0 * 2,
(int)g.M, (int)g.K, (int)np, c.wv, c.sk, c.mb, c.npw,
as_group, as_rs, (long)(uintptr_t)s,
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N));
}
return RAD_OK;
}
+44 -24
View File
@@ -101,7 +101,7 @@ static __device__ __forceinline__ void mxt_lds_barrier() {
// contiguous and each lane reads one 8-byte group of one row.
__global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
long long slots) {
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;
@@ -110,7 +110,7 @@ __global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
const int mt = (int)(f / ks), kst = (int)(f % ks);
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
mxt_u2 v = { 0u, 0u };
if (r < M) v = *(const mxt_u2*)(A + (size_t)r * K + k);
if (r < M) v = *(const mxt_u2*)(A + (size_t)r * lda + k);
*(mxt_u2*)(AT + o * 8) = v;
}
@@ -119,7 +119,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_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__ Wref, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int as_rs) {
int M, int K, int N, int as_rs, int ldws, int ldc) {
constexpr int TM = R4D_MXT_TM, WN = R4D_MXT_WN, NTHR = R4D_MXT_NTHR, BMF = R4D_MXT_BMF;
constexpr int NS = LBK / 16, STR = LBK + R4D_MXT_PAD, BNF = WN * TN * 16;
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
@@ -213,14 +213,14 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
if constexpr (WSLOTS == 4) {
const mxt_u4 v = *(const mxt_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 * N + wrc[it]);
wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
} else if constexpr (WSLOTS == 2) {
const mxt_u2 v = *(const mxt_u2*)src;
wq[0] = v[0]; wq[1] = v[1];
wsw = *(const unsigned short*)(Ws + (size_t)blk * N + wrc[it]);
wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
} else {
wq[0] = *src;
wsw = Ws[(size_t)blk * N + wrc[it]];
wsw = Ws[(size_t)blk * ldws + wrc[it]];
}
#pragma unroll
for (int q = 0; q < WSLOTS; ++q) {
@@ -306,7 +306,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
o.h[e] = (__hip_bfloat16)(acc[i][j][e] * rf * sc[i]);
}
*(mxt_u4*)(C + (size_t)m * N + nb) = o.v;
*(mxt_u4*)(C + (size_t)m * ldc + nb) = o.v;
}
}
}
@@ -317,17 +317,20 @@ extern "C" long r4d_mxfp4a8_tile_a_bytes(int M, int K) {
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
}
extern "C" void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream) {
extern "C" void r4d_mxfp4a8_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 mxfp4a8_tile_a: M must be >= 1");
if (K < 16 || K % 16) throw std::runtime_error("r4d mxfp4a8_tile_a: K must be a multiple of 16");
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
hipLaunchKernelGGL(r4d_mxfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256), 0,
(hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots);
(hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots, lda);
}
extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int TN, int as_group, int as_rs,
long stream) {
long stream, int ldws, int ldc) {
if (!ldws) ldws = N;
if (!ldc) ldc = N;
if (M < 1) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: M must be >= 1");
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: N must be a multiple of 16");
if (K < R4D_MXT_KUNIT || K % R4D_MXT_KUNIT)
@@ -355,7 +358,7 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l
hipStream_t st = (hipStream_t)stream;
#define MXT_LAUNCH(TNv, LBKv, ABv) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
Wp, Zp, Rp, Cp, M, K, N, as_rs)
Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc)
if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); }
else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); }
else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); }
@@ -364,35 +367,52 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l
// ============================================================== the plugin ABI entry point
// The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there.
// A partitioned weight re-tiles each part's copy of the activation into its own slab of the
// scratch and runs the GEMM over that part's rows (mx_parts).
extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) {
GemmOps g;
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.K % R4D_MXT_KUNIT) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
/* The per-row reference exponent, as in r4d_rad_gemm_mxfp4a8_m64: without it the fold has no
* reference and every element would be scaled against zero. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
if (!a->scratch || a->scratch_bytes < r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K))
return R4D_NO(RAD_E_INVAL);
if (g.K % R4D_MXT_KUNIT) 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;
const long long slab = r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K);
if (!a->scratch || a->scratch_bytes < slab * mp.n) return R4D_NO(RAD_E_INVAL);
R4dMxTileCfg t;
r4d_cfg_mxfp4_tiled(a, &t);
const long at = (long)(uintptr_t)a->scratch;
R4D_TRY("gemm_mxfp4a8_tiled",
r4d_mxfp4a8_tile_a(r4d_addr(g.a), at, (int)g.M, (int)g.K, (long)(uintptr_t)s);
r4d_gemm_mxfp4a8_tiled(at, r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale),
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));
const long kb = (long)((g.K + 127) / 128);
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
const long at = (long)(uintptr_t)a->scratch + (long)(p * slab);
R4D_TRY("gemm_mxfp4a8_tiled",
r4d_mxfp4a8_tile_a(r4d_addr(g.a) + p * g.K, at, (int)g.M, (int)g.K,
(long)(uintptr_t)s, (int)(mp.lda ? mp.lda : g.K));
r4d_gemm_mxfp4a8_tiled(at, r4d_addr(g.ascale) + p * kb * 4, r4d_addr(g.b) + n0 * g.K / 2,
r4d_addr(g.bscale) + n0, r4d_addr(g.bref) + n0,
r4d_addr(g.y) + n0 * 2, (int)g.M, (int)g.K, (int)np, t.tn,
as_group, as_rs, (long)(uintptr_t)s, (int)g.N, (int)g.N));
}
return RAD_OK;
}
/* The core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of
* the activation, whole 16-row fragments. */
* the activation, whole 16-row fragments -- one a part. */
extern "C" int64_t r4d_rad_gemm_mxfp4a8_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_mxfp4a8_tile_a_bytes((int)M, (int)K);
const long long N = r4d_geti_or(a, "N", 0);
const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0);
const long long e1 = pb1 > 0 ? (pb1 < N ? pb1 : N) : N;
long long e2 = pb2 > 0 ? (pb2 < N ? pb2 : N) : N;
if (e2 < e1) e2 = e1;
const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K) * parts;
}
+206
View File
@@ -0,0 +1,206 @@
// ParoQuant's activation side: channel scale, Givens rotations, then the per-(row, 128-column)
// symmetric E4M3 quantiser of r4d_quant_act_fp8.hip. The weight it pairs with is stored as
// v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product <v, x'> with
// x' = x . D^-1 . G_1 ... G_S is <w, x>: the rotation is the activation's to do, once a token, and
// the weight is read by the plain MXFP4 GEMM unchanged.
//
// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns --
// that is how the checkpoint is trained, and the converter refuses one that does -- so a group is a
// closed system: its 128 values are rotated by S stages of 64 disjoint pairs and then quantised
// with ONE scale. A wave owns a group. The values sit in LDS (128 floats a wave, no barrier
// needed: a wave's LDS accesses are in order, and the pairs of a stage are disjoint so no two lanes
// touch one address), each lane takes two pairs a stage, and the absmax is a wave reduction. The
// quantiser after it is quant_act_fp8's, byte for byte.
//
// PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row yields `parts` rotated
// copies, side by side: q is [M, parts * K] and scale [M, parts * K/128]. A (part, group) pair is
// one unit of work, one wave's (a row is several blocks, grid.y). The tables stack the parts
// as the "givens" encoding does -- stages rows each of pairs and angle, one row of channel scales.
//
// THE CHANNEL SCALE IS A DIVIDE, because the encoding's t.scale is the factor the stored row was
// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the
// reference (libref) divides in f32 too, so the two agree on this step exactly.
//
// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or
// two, which is also what libref's libm is. The rotation is a handful of FMAs on top of that; the
// quantiser's rounding to E4M3 then swallows nearly all of the difference, and rad-kbench-style
// comparisons against the reference allow one code of disagreement per element.
//
// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d.h"
#include "r4d_emit.h"
#include "r4d_fp8_args.h"
#include "r4d_fp8_wmma.h"
namespace {
constexpr uint32_t kWave = 32;
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr uint32_t kGroup = 128;
constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2
// kPre stages' tables are loaded and their angles' sine and cosine taken BEFORE the first of them is
// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS
// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency
// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages.
constexpr uint32_t kPre = 8;
__device__ __forceinline__ void wave_sync() {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront");
__builtin_amdgcn_wave_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront");
}
// One wave rotates and quantises one (part, group) of one row: grid.x is the row, and grid.y
// spreads a row's `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is
// several blocks and a decode step of a few rows still fills the part. A wave that has no group
// returns at once; nothing in the kernel is a block barrier.
__global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel(
const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs,
const float* __restrict__ angle, const float* __restrict__ rscale, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages,
uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) {
__shared__ float sbuf[kWaves][kGroup];
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint32_t item = blockIdx.y * kWaves + wave;
if (item >= parts * nkb) return;
const uint32_t part = item / nkb, g = item % nkb;
const uint32_t c0 = g * kGroup;
const size_t xrow = (size_t)row * x_ld;
float* buf = sbuf[wave];
// channel scale: v = x / D, four consecutive columns a lane
{
const float4 d = *(const float4*)(rscale + (size_t)part * K + c0 + lane * 4u);
const uint32_t xc = c0 + lane * 4u;
const float v0 = __uint_as_float((uint32_t)x[xrow + xc + 0] << 16) / d.x;
const float v1 = __uint_as_float((uint32_t)x[xrow + xc + 1] << 16) / d.y;
const float v2 = __uint_as_float((uint32_t)x[xrow + xc + 2] << 16) / d.z;
const float v3 = __uint_as_float((uint32_t)x[xrow + xc + 3] << 16) / d.w;
*(float4*)(buf + lane * 4u) = make_float4(v0, v1, v2, v3);
}
for (uint32_t st0 = 0; st0 < stages; st0 += kPre) {
const uint32_t nst = (stages - st0) < kPre ? (stages - st0) : kPre;
int2 ab[kPre][kPairsPerLane];
float th[kPre][kPairsPerLane], cs[kPre][kPairsPerLane], sn[kPre][kPairsPerLane];
#pragma unroll
for (uint32_t k = 0; k < kPre; ++k)
if (k < nst) {
const size_t trow = (size_t)part * stages + st0 + k;
const int32_t* pr = pairs + trow * K + c0;
const float* an = angle + trow * (K / 2u) + g * (kGroup / 2u);
#pragma unroll
for (uint32_t u = 0; u < kPairsPerLane; ++u) {
const uint32_t j = lane + u * kWave;
ab[k][u] = *(const int2*)(pr + 2u * j);
th[k][u] = an[j];
}
}
#pragma unroll
for (uint32_t k = 0; k < kPre; ++k)
if (k < nst)
#pragma unroll
for (uint32_t u = 0; u < kPairsPerLane; ++u) sincosf(th[k][u], &sn[k][u], &cs[k][u]);
wave_sync(); // the scaled row (or the previous chunk's last stage) is in LDS
#pragma unroll
for (uint32_t k = 0; k < kPre; ++k)
if (k < nst) {
#pragma unroll
for (uint32_t u = 0; u < kPairsPerLane; ++u) {
const int ia = ab[k][u].x - (int)c0, ib = ab[k][u].y - (int)c0;
const float va = buf[ia], vb = buf[ib];
buf[ia] = fmaf(cs[k][u], va, sn[k][u] * vb);
buf[ib] = fmaf(cs[k][u], vb, -sn[k][u] * va);
}
wave_sync();
}
}
const float4 r = *(const float4*)(buf + lane * 4u);
float v[4] = { r.x, r.y, r.z, r.w };
float m = 0.0f;
#pragma unroll
for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j]));
m = r4d_wave_max(m);
const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f;
if (lane == 0) s[(size_t)row * s_ld + (size_t)part * nkb + g] = sc;
const float inv = 1.0f / sc;
int pk = 0;
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true);
*(uint32_t*)(q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = (uint32_t)pk;
}
} // namespace
// x [M][K] bf16, `x_ld` elements a row (0 = K)
// pairs [parts*stages][K] int32 column indices; (pairs[2j], pairs[2j+1]) is pair j
// angle [parts*stages][K/2] f32
// rscale [parts][K] f32, the factor the stored row was multiplied by
// q [M][parts*K] E4M3
// s [M][parts*K/128] f32
static int givens_quant_launch(long x, long pairs, long angle, long rscale, long q, long s, int M,
int K, int parts, int stages, int x_ld, int q_ld, int s_ld,
const R4dSink& sk) {
if (!x || !pairs || !angle || !rscale || !q || !s) return -1;
if (M <= 0 || K <= 0 || parts <= 0 || stages <= 0) return -2;
if (K % (int)kGroup) return -3; // a rotation group cannot straddle the end of a row
if (!x_ld) x_ld = K;
const int nkb = K / (int)kGroup;
if (!q_ld) q_ld = parts * K;
if (!s_ld) s_ld = parts * nkb;
const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves;
const int rc = R4D_EMIT(sk, givens_quant_act_fp8_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0,
(const uint16_t*)x, (const int32_t*)pairs, (const float*)angle,
(const float*)rscale, (uint8_t*)q, (float*)s, (uint32_t)K,
(uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, (uint32_t)x_ld,
(uint32_t)q_ld, (uint32_t)s_ld);
if (rc != RAD_OK) return -4;
return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0;
}
extern "C" int r4d_givens_quant_act_fp8_group(void) { return (int)kGroup; }
// ============================================================== the plugin ABI entry point
enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Q = 4, GV_S = 5 };
static int rad_givens_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) {
const RadTensor* x = r4d_opt(a, GV_X);
const RadTensor* pr = r4d_opt(a, GV_PAIRS);
const RadTensor* an = r4d_opt(a, GV_ANGLE);
const RadTensor* rs = r4d_opt(a, GV_RSCALE);
const RadTensor* q = r4d_opt(a, GV_Q);
const RadTensor* sc = r4d_opt(a, GV_S);
if (!x || !pr || !an || !rs || !q || !sc) return R4D_NO(RAD_E_INVAL);
if (x->rank < 2 || q->rank != 2 || sc->rank != 2 || pr->rank != 2 || an->rank != 2 ||
rs->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32)
return R4D_NO(RAD_E_DTYPE);
// rows are dim 0 and everything after it is the row, as quant_act_fp8 reads them
const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1);
const long long grp = (long long)kGroup, nkb = K / grp;
const long long parts = r4d_geti_or(a, "parts", 1), stages = r4d_geti_or(a, "stages", 0);
if (r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1)
return R4D_NO(RAD_E_SHAPE);
if (q->shape[0] != M || q->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE);
if (sc->shape[0] != M || sc->shape[1] != parts * nkb) return R4D_NO(RAD_E_SHAPE);
// the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles
if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE);
if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(q->data, 4))
return R4D_NO(RAD_E_ALIGN);
const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE);
const int e = givens_quant_launch(r4d_addr(x), r4d_addr(pr), r4d_addr(an), r4d_addr(rs),
r4d_addr(q), r4d_addr(sc), (int)M, (int)K, (int)parts,
(int)stages, (int)xp, (int)qp, (int)sp, sk);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
R4D_ENTRY(r4d_rad_givens_quant_act_fp8, rad_givens_quant_act_fp8_body)
+25 -1
View File
@@ -615,6 +615,29 @@ extern "C" int r4d_rad_unrelayout_w2a8(const RadParam* p, int n_p, int operand,
* exponents to [K/32][N], and b_ref is each row's largest exponent -- a reduction over the plane,
* which is a derivation any reader of the plane could make and so not a choice. */
namespace {
/* A ROTATED MXFP4 WEIGHT (ParoQuant): the same two planes -- e2m1 codes, an E8M0 exponent a 32 --
* stored in the basis the "givens" transform names, with the rotation's tables beside them. The
* GEMM reads the codes and exponents exactly as it reads an unrotated weight; the rotation is the
* activation's (givens_quant_act_fp8), and the tables are separate weight operands of that op, so
* nothing here touches them. What is checked is that they are there and are the kind of
* rotation the quantiser applies: a transform this library does not read would hand the kernel
* codes that decode to other numbers. */
bool mx_paro_enc(const RadEncoding* e, long long K) {
if (!e || !rad_enc_is(e, "affine") || std::strncmp(e->transform, "givens", RAD_ENC_STR) != 0) return false;
if (e->n_planes < 5 || !rad_enc_valid(e)) return false;
if (std::strncmp(e->plane[0].role, "codes", RAD_ENC_STR) != 0 || e->plane[0].dtype != RAD_FP4E2M1 ||
e->plane[0].block[0] != 1 || e->plane[0].block[1] != 1) return false;
const int s = rad_enc_find(e, "scale");
if (s != 1 || e->plane[s].dtype != RAD_E8M0 || e->plane[s].kind != RAD_PLANE_TILED ||
e->plane[s].block[0] != 1 || e->plane[s].block[1] != R4D_MXFP4_GROUP) return false;
const int p = rad_enc_find(e, "t.pairs"), an = rad_enc_find(e, "t.angle"), sc = rad_enc_find(e, "t.scale");
if (p < 0 || an < 0 || sc < 0) return false;
if (e->plane[p].dtype != RAD_I32 || e->plane[an].dtype != RAD_F32 || e->plane[sc].dtype != RAD_F32)
return false;
// the quantiser rotates whole groups of 128 columns, one scale per group
return K % 128 == 0 && e->plane[p].extent[1] == K;
}
int mx_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;
@@ -622,7 +645,8 @@ int mx_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
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 (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, R4D_MXFP4_GROUP)) return RAD_E_DTYPE;
if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, R4D_MXFP4_GROUP) &&
!mx_paro_enc(enc, g.K)) return RAD_E_DTYPE;
if (gout) *gout = g;
const long long nblk = g.K / R4D_MXFP4_GROUP;
if (operand == Q_BSCALE || operand == Q_BREF) {
+2
View File
@@ -319,6 +319,8 @@ int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream);
int r4d_rad_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream);
int r4d_rad_had_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_givens_quant_act_fp8 (const RadArgs*, RadStream);
int r4d_rad_givens_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream);
int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream);
int r4d_rad_gated_quant_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
+52
View File
@@ -704,12 +704,18 @@ static const RadOperandSpec oGemmNt[] = {
{ "y", RAD_OPD_OUT, 0 },
};
/* `pb1` and `pb2` are ParoQuant's, and the mxfp4a8 rows alone read them: the weight's rows
* [0, pb1), [pb1, pb2) and [pb2, N) each meet their own copy of the activation, side by side in a
* row of `a` (so `a` is [M, parts * K]). 0 leaves a bound out. Optional, and absent from every
* other grid: a fused projection whose pieces were not rotated apart has one activation. */
static const RadParamSpec pGemmNtQ[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "N", RAD_P_INT, RAD_REQUIRED },
{ "K", RAD_P_INT, RAD_REQUIRED },
{ "group", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "pb1", RAD_P_INT, RAD_OPTIONAL },
{ "pb2", RAD_P_INT, RAD_OPTIONAL },
};
/* docs/OPS.md's `gemm_nt_q` is `a`, `a_scale`, `b`w, `b_scale`w -> `y`. Two of libr4d's six
* quantised GEMMs need a seventh operand each and neither is expressible as a weight aux stream,
@@ -1045,6 +1051,26 @@ static const RadOperandSpec oQuantActFp8[] = {
{ "scale", RAD_OPD_OUT, 0 },
};
/* `givens_quant_act_fp8` is ParoQuant's activation side, and libref declared this schema first
* (the loader refuses two that differ). The tables are the "givens" encoding's, as WEIGHT operands;
* see libref/ref_quant.cpp for the contract and r4d_givens_quant_act_fp8.hip for the kernel. */
static const RadParamSpec pGivensQuantAct[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
{ "group", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "stages", RAD_P_INT, RAD_REQUIRED },
{ "parts", RAD_P_INT, RAD_REQUIRED },
};
static const RadOperandSpec oGivensQuantAct[] = {
{ "x", RAD_OPD_IN, 0 },
{ "pairs", RAD_OPD_WEIGHT, 0 },
{ "angle", RAD_OPD_WEIGHT, 0 },
{ "rscale", RAD_OPD_WEIGHT, 0 },
{ "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 },
};
/* `gram_accum` is a NEW OP and this plugin fixes its schema. It is the calibration half of GPTQ:
* `h += x^T x` over an E4M3 activation, accumulated across every launch of a corpus.
*
@@ -2298,6 +2324,16 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("had_quant_act_i8g", pQuantActFp8, oQuantActFp8,
"quant_act_i8g with a `group`-wide Hadamard along K first; pairs with an i8 weight stored "
"rotated, its scale carrying the residual factor of `group`."),
SCHEMA("givens_quant_act_fp8", pGivensQuantAct, oGivensQuantAct,
"ParoQuant's activation quantiser: x is divided by the channel scale `rscale`, rotated by "
"`stages` rounds of disjoint Givens pairs (a' = a cos t + b sin t, b' = b cos t - a sin t, "
"pairs as column indices of the row, each inside one scale group), then quantised as "
"quant_act_fp8 does: scale = amax / 448 per `group`. `parts` rotated copies are written "
"side by side -- q is [M, parts * n], scale [M, parts * n / group] -- part p from table "
"rows [p * stages, (p + 1) * stages) of `pairs` and `angle` and row p of `rscale`: a "
"fused projection's pieces were each rotated on their own. Only a weight stored with "
"the \"givens\" transform reads the result; it is NOT quant_act_fp8's output in either "
"direction."),
SCHEMA("had_quant_act_fp8", pQuantActFp8, oQuantActFp8,
"the same, with a `group`-wide Hadamard along K applied BEFORE the absmax. Pairs with "
"an expert weight stored at dtype w4a8h, which carries the matching rotation and the "
@@ -5115,6 +5151,22 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_had_quant_act_fp8, nullptr, nullptr, nullptr,
r4d_shape_quant_act_fp8, nullptr, nullptr, r4d_rad_had_quant_act_fp8_describe },
/* ParoQuant's rotation and the quantiser in one pass, because the rotation changes the maximum the
* scale is taken over and so cannot be a separate launch ahead of quant_act_fp8 without writing
* and re-reading the rotated row. It exists for the MXFP4 weight stored rotated and for nothing
* else. */
{ "givens_quant_act_fp8", "givens_quant_act_fp8", "quant",
"the channel scale, ParoQuant's Givens rotations, then per-(row, 128-column) symmetric E4M3 "
"quantisation, once for each rotated part of a fused projection",
"n a multiple of 128 -- a rotation group cannot straddle the end of a row -- and group 128, "
"which is both the rotation group and the weight scale's activation block",
"bf16 in, E4M3 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale per (row, part, "
"128 columns); the tables are the weight's int32 pairs, f32 angles and f32 channel scales",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cHadQuantActFp8), NOTUNE,
nullptr, nullptr, r4d_rad_givens_quant_act_fp8, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, r4d_rad_givens_quant_act_fp8_describe },
{ "quant_act_i8g", "quant_act_i8g", "quant",
"per-(row, 128-column) symmetric int8 quantisation of a bf16 activation",
"quant_act_fp8's: n a multiple of 4, group 128, a ragged last group written zero-padded",
+152 -14
View File
@@ -3604,11 +3604,19 @@ static float mxfp4_act(int64_t i, int64_t k, uint32_t seed) {
* spread over two decades and every eleventh block's is ZERO with zero codes behind it (an
* all-zero activation block), which is the case the kernels carry their previous scale through. */
static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K,
int tn, bool ablk = false, std::vector<RadParam> extra = {}) {
int tn, bool ablk = false, std::vector<RadParam> extra = {},
int64_t pb1 = 0, int64_t pb2 = 0) {
if (!sel(row)) return;
/* PARTS (ParoQuant): the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy
* of the activation, the copies side by side in a row. `K` is one copy's width. */
const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N;
const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N;
const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); };
char nm[160];
std::string ex;
for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival);
if (parts > 1) ex += " parts=" + std::to_string(parts);
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);
@@ -3633,20 +3641,21 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
}
const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1;
std::vector<uint8_t> ha((size_t)(M * K));
std::vector<float> av((size_t)(M * K)), as((size_t)(M * asc));
const int64_t PK = parts * K, PA = parts * asc; /* a row of `a`, and of its scale */
std::vector<uint8_t> ha((size_t)(M * PK));
std::vector<float> av((size_t)(M * PK)), as((size_t)(M * PA));
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)] =
for (int64_t c = 0; c < PA; ++c) {
const uint32_t h = st_mix32((uint32_t)(i * PA + c) ^ 0xa5u);
as[(size_t)(i * PA + 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;
for (int64_t k = 0; k < PK; ++k) {
const bool zero = ablk && as[(size_t)(i * PA + (k / K) * asc + (k % 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);
rad_store_f32(ha.data(), RAD_F8E4M3, i * PK + k, v);
av[(size_t)(i * PK + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * PK + k);
}
}
std::vector<uint16_t> hy((size_t)(M * N), 0);
@@ -3663,8 +3672,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice);
st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_a, RAD_F8E4M3, { M, K }),
ablk ? T(d_s, RAD_F32, { M, asc }) : T(d_s, RAD_F32, { M }),
T(d_a, RAD_F8E4M3, { M, PK }),
ablk ? T(d_s, RAD_F32, { M, PA }) : 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() }),
};
@@ -3672,6 +3681,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "mxfp4a8") };
if (tn) ps.push_back(PI("tn", tn));
if (pb1) ps.push_back(PI("pb1", pb1));
if (pb2) ps.push_back(PI("pb2", pb2));
for (const RadParam& p : extra) ps.push_back(p);
RadArgs a;
std::memset(&a, 0, sizeof(a));
@@ -3702,11 +3713,12 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
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;
const int pt = part_of(n);
for (int64_t k = 0; k < K; ++k) {
const double w = (double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) *
(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);
acc += (double)av[(size_t)(i * PK + pt * K + k)] * w *
(ablk ? (double)as[(size_t)(i * PA + pt * 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;
@@ -3721,6 +3733,111 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
}
/* PAROQUANT'S ACTIVATION QUANTISER AGAINST A DOUBLE-PRECISION ROTATION. The tables are real
* pairings -- every stage of every group is a random permutation of the group's 128 columns read
* as 64 pairs -- with angles over (-pi, pi) and channel scales over (0.5, 2), drawn through
* st_mix32 of their coordinates. The reference divides, rotates in f64 and takes the absmax; the
* kernel's scale must match it to the rounding of its f32 sincos, and every dequantised element
* must sit within the E4M3 grid of the reference (half a step at the top of the range is 1/16 of
* the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */
static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages) {
const char* row = "givens_quant_act_fp8";
if (!sel(row)) return;
char nm[160];
std::snprintf(nm, sizeof nm, "%s numeric M=%lld K=%lld parts=%d stages=%d", row, (long long)M,
(long long)K, parts, stages);
const RadKernelInfo* r = find(pl, row);
if (!r || !r->launch) { ok(nm, false, "row absent"); return; }
const int64_t G = 128, ng = K / G;
std::vector<uint16_t> hx((size_t)(M * K));
std::vector<float> xv((size_t)(M * K));
for (int64_t i = 0; i < M; ++i)
for (int64_t k = 0; k < K; ++k) {
const uint32_t h = st_mix32((uint32_t)(i * 0x10001 + k) ^ 0x77u);
const float v = (float)((int)(h % 4001) - 2000) * 0.002f * (i % 4 == 3 ? 40.0f : 1.0f);
hx[(size_t)(i * K + k)] = h_to_bf16(v);
xv[(size_t)(i * K + k)] = h_bf16(hx[(size_t)(i * K + k)]);
}
const int64_t NPS = (int64_t)parts * stages;
std::vector<int32_t> pairs((size_t)(NPS * K));
std::vector<float> ang((size_t)(NPS * K / 2)), rs((size_t)(parts * K));
for (int64_t ps = 0; ps < NPS; ++ps) {
for (int64_t g = 0; g < ng; ++g) {
std::vector<int32_t> perm((size_t)G);
for (int i = 0; i < G; ++i) perm[(size_t)i] = i;
for (int i = (int)G - 1; i > 0; --i)
std::swap(perm[(size_t)i],
perm[st_mix32((uint32_t)(ps * 7919 + g * 104729 + i)) % (uint32_t)(i + 1)]);
for (int i = 0; i < G; ++i) pairs[(size_t)(ps * K + g * G + i)] = (int32_t)(g * G + perm[(size_t)i]);
}
for (int64_t j = 0; j < K / 2; ++j)
ang[(size_t)(ps * K / 2 + j)] =
(float)(st_mix32((uint32_t)(ps * 31337 + j) ^ 0x5bu) % 6283) / 1000.0f - 3.1415f;
}
for (int64_t i = 0; i < parts * K; ++i)
rs[(size_t)i] = 0.5f + (float)(st_mix32((uint32_t)i ^ 0xc3u) % 1500) / 1000.0f;
void* d_x = dalloc(hx.size() * 2);
void* d_p = dalloc(pairs.size() * 4);
void* d_a = dalloc(ang.size() * 4);
void* d_r = dalloc(rs.size() * 4);
void* d_q = dalloc((size_t)(M * parts * K));
void* d_s = dalloc((size_t)(M * parts * ng) * 4);
if (!d_x || !d_p || !d_a || !d_r || !d_q || !d_s) { ok(nm, false, "hipMalloc failed"); return; }
st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_p, pairs.data(), pairs.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_a, ang.data(), ang.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_r, rs.data(), rs.size() * 4, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_x, RAD_BF16, { M, K }), T(d_p, RAD_I32, { NPS, K }), T(d_a, RAD_F32, { NPS, K / 2 }),
T(d_r, RAD_F32, { (int64_t)parts, K }), T(d_q, RAD_F8E4M3, { M, parts * K }),
T(d_s, RAD_F32, { M, parts * ng }),
};
std::vector<RadParam> ps = { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"),
PI("stages", stages), PI("parts", parts) };
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;
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; }
std::vector<uint8_t> hq((size_t)(M * parts * K));
std::vector<float> hs((size_t)(M * parts * ng));
st_memcpy(hq.data(), d_q, hq.size(), hipMemcpyDeviceToHost);
st_memcpy(hs.data(), d_s, hs.size() * 4, hipMemcpyDeviceToHost);
double worst_scale = 0, worst_val = 0;
std::vector<double> b((size_t)K);
for (int64_t i = 0; i < M; ++i)
for (int p = 0; p < parts; ++p) {
for (int64_t k = 0; k < K; ++k) b[(size_t)k] = (double)xv[(size_t)(i * K + k)] / (double)rs[(size_t)(p * K + k)];
for (int st = 0; st < stages; ++st)
for (int64_t j = 0; j < K / 2; ++j) {
const int64_t ia = pairs[(size_t)((p * stages + st) * K + 2 * j)];
const int64_t ib = pairs[(size_t)((p * stages + st) * K + 2 * j + 1)];
const double t = ang[(size_t)((p * stages + st) * (K / 2) + j)], c = std::cos(t), sn = std::sin(t);
const double va = b[(size_t)ia], vb = b[(size_t)ib];
b[(size_t)ia] = va * c + vb * sn;
b[(size_t)ib] = vb * c - va * sn;
}
for (int64_t g = 0; g < ng; ++g) {
double amax = 0;
for (int k = 0; k < G; ++k) amax = std::max(amax, std::fabs(b[(size_t)(g * G + k)]));
const double sc = hs[(size_t)(i * parts * ng + p * ng + g)];
worst_scale = std::max(worst_scale, std::fabs(sc - amax / 448.0) / (amax / 448.0 + 1e-30));
for (int k = 0; k < G; ++k) {
const double deq = (double)rad_load_f32(hq.data(), RAD_F8E4M3, i * parts * K + p * K + g * G + k) * sc;
worst_val = std::max(worst_val, std::fabs(deq - b[(size_t)(g * G + k)]) / (amax + 1e-30));
}
}
}
char d[96];
std::snprintf(d, sizeof d, "scale rel %.2e, value/amax %.3f", worst_scale, worst_val);
ok(nm, worst_scale < 1e-4 && worst_val < 0.07, d);
}
/* TWO DECODE GEMMS THE ENGINE MAY OVERLAP (gemm_mxfp4a8_decode is a concurrent row: its split partial
* is the op's scratch and its arrival counters are keyed on the output). Each GEMM has its own
* weights, activations and output and a DISJOINT slice of one scratch allocation, with a split
@@ -12233,6 +12350,17 @@ static void device_phase(const Plugin& pl) {
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 64, 512, 2560, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 5, 1040, 576, 0, true);
mxd_overlap_case(pl);
/* PARTS (ParoQuant): each part of the weight against its own copy of the activation, with
* bounds that do not fall on a tile of any kernel's, two parts and three, at every band. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 400, 640, 0, true, {}, 144);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 400, 640, 0, true, {}, 144, 288);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 400, 2560, 0, true, {}, 128);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 40, 512, 2560, 0, true, {}, 128, 384);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 4, 34816, 5120, 0, true, {}, 17408);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 2, true, {}, 192);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4, true, {}, 96, 304);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0, true, {}, 256);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 34816, 5120, 0, true, {}, 17408);
/* Above 64 rows, every branch of the measured table: 110+ column blocks, 48+, 8 or
* fewer (with a K that is not a multiple of 128, so the slab falls back to 64), a deep K
* on both sides of M=80, and the plain case; then every split and slab forced. */
@@ -12649,6 +12777,16 @@ static void device_phase(const Plugin& pl) {
moe_w4_rot(pl);
}
if (sel("givens_quant_act_fp8")) {
if (!g_case) std::printf("\nParoQuant's rotate-and-quantise, against an f64 rotation\n");
givens_numeric(pl, 1, 128, 1, 8);
givens_numeric(pl, 3, 5120, 1, 8);
givens_numeric(pl, 5, 5120, 2, 8);
givens_numeric(pl, 64, 17408, 1, 8);
givens_numeric(pl, 300, 6144, 2, 8);
givens_numeric(pl, 7, 5120, 3, 2);
}
if (sel("gram_accum")) {
if (!g_case) std::printf("\nthe GPTQ calibration accumulator, against an f64 host Gram\n");
gram_accum_case(pl);