decode launches: gate_up + gated_quant_fp8 folded for MXFP4 (gemm_nt_q_gated_mx)

A decode step on Qwen3.8-27B at TP2 issues 631 kernels a card, and a dependent kernel costs the card
3.5-6.4 us in a replayed graph on gfx1201 however little it does, so launches are about 13 % of a
step.

- gemm_nt_q_gated_mx: gemm_nt_q_gated over an OCP-MXFP4 weight (b_ref after b_scale; a new op, not
  an optional operand on the old one). Row gemm_mxfp4a8_gated_gemv: M <= 8, a block per 128-column
  group of the gated output, a wave per gate or up tile running all of the gemv WMMA form's partials
  in its order, then gated_quant_fp8's epilogue -- byte-identical to gemv + gated_quant_fp8
  (selftest, M = 1..8, Qwen's and TranslateGemma's gate_up). The MLP block declares it for a plain
  MXFP4 gate_up when a loaded library declares the op (libref does not), so a CPU-only engine takes
  the pair. Layout hooks map its b_ref (operand 4) to gemm_nt_q's index, so the weight is stored once.
  The fold: 82.5 us against 81 + 4.6 for the pair at Qwen's gate_up, 98.8 against 104 + 4.7 at
  TranslateGemma's.
- --perfmxd times gated_quant_fp8 and the fold beside the gemv row at a gate_up shape.

Greedy texts of four prompts, speculation 0 and 3, identical to the production build.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
mici81andClaude Opus 5.5 authored and StillDeadcode committed 2026-10-25 09:59:53 +01:00
1 parent 486c933161
commit f16854499c
9 files changed
+497 -7

No files matched your search

+39
View File
@@ -510,6 +510,45 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre
}
}
/* ==========================================================================================
* gemm_nt_q_gated_mx -- the same fold over an OCP-MXFP4 weight.
* (row: gemm_mxfp4a8_gated_gemv; kernel: libr4d/r4d_gemm_mxfp4a8_gemv.hip, the gated form)
*
* Operands: [0] a [1] a_scale [2] b [3] b_scale [4] b_ref [5] q [6] scale [7] out_bf16
*
* The GEMM step is gemm_nt_q at dtype mxfp4a8 with `b_ref` in its last operand. `group` is the
* weight's 32 on the GEMM and the activation's 128 on the quantiser, so the quantiser's is set, not
* mirrored.
*/
extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const char* dt = r4d_pgets(p, n_p, "dtype");
if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED;
if (pi(p, n_p, "group", 32) != 32) return RAD_E_UNSUPPORTED;
if (!dt || std::strcmp(dt, "mxfp4a8")) return RAD_E_UNSUPPORTED;
if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED;
switch (step) {
case 0: {
Step s(out, "gemm_nt_q");
s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K")
.mirror(p, n_p, "group").mirror(p, n_p, "dtype");
/* a, a_scale, b, b_scale, y, a_sum, b_ref */
return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, 4 });
}
case 1: {
Step s(out, "gated_quant_fp8");
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128)
.pstr("dtype", "bf16").mirror(p, n_p, "act");
return s.wire({ RAD_FUSE_TMP(0), 5, 6, 7 }); /* gate_up, q, scale, out_bf16 */
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* gdn_conv_recurrent_update -- the decode convolution folded into the recurrent update's prologue.
* (row: gdn_conv_recurrent_update_k128_v128_bf16; kernel: libr4d/
+190
View File
@@ -35,9 +35,11 @@
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include "r4d_q8.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#define R4D_MXG_MAX_M 8
@@ -346,3 +348,191 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) {
}
return RAD_OK;
}
// ============================================================== the gated form (gemm_nt_q_gated_mx)
//
// The gate_up GEMM with gated_quant_fp8's pass in its epilogue, so the [M, 2n] bf16 product is never
// written and the quantiser is not a launch of its own. One block a 128-column group of the gated
// output (one activation scale group of the down projection's input): sixteen waves, one 16-column
// weight tile each -- the group's eight gate tiles (weight rows 128 g ..) and its eight up tiles (rows
// n + 128 g ..).
//
// Byte-identical to the WMMA form above followed by gated_quant_fp8. A wave runs, for its tile, what
// all R4D_MXG_KW waves of that kernel run: partial v sums chunks v, v + KW, .. in order, and the
// partials are added v = 0, 1, .. from zero, as that kernel's epilogue adds its waves' rows of sP.
// Only one partial is live at a time, which is why the chunks are taken in that order rather than
// in K order. The scaled sum is rounded to bf16 by the same conversion, and from there the arithmetic
// is r4d_fused_quant_fp8.hip's gated_quant_fp8_kernel: silu(gate) * up rounded to bf16, the group's
// amax, scale amax / 448, codes through q8_pack4.
namespace {
__device__ __forceinline__ float mxg_bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
__device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as r4d_fused_quant_fp8.hip's f2bf
const uint32_t u = __float_as_uint(f);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
} // namespace
template <bool ABLK>
__global__ __launch_bounds__(16 * 32)
void r4d_gemm_mxfp4a8_gated_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, uint8_t* __restrict__ Q, float* __restrict__ S,
uint16_t* __restrict__ Y, int M, int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld,
int y_ld) {
constexpr int KW = R4D_MXG_KW;
__shared__ uint16_t sG[16][R4D_MXG_MAX_M][16]; // bf16 gate (waves 0..7) and up (8..15)
const int lane = threadIdx.x & 31;
const int wave = __builtin_amdgcn_readfirstlane(threadIdx.x >> 5);
const int nt = (wave >> 3) * (n >> 4) + blockIdx.x * 8 + (wave & 7); // this wave's weight tile
const int col = lane & 15, khalf = lane >> 4;
const int row = col;
const bool live = row < M;
const int ksteps = K >> 4, chunks = K >> 7;
const unsigned* __restrict__ Wp = (const unsigned*)W;
const int ref = (int)Wref[nt * 16 + col];
mxg_v8f sum = (mxg_v8f)(0.f);
for (int v = 0; v < KW; ++v) {
mxg_v8f tot = (mxg_v8f)(0.f);
for (int ch = v; ch < chunks; ch += KW) {
unsigned wv[8];
#pragma unroll
for (int s = 0; s < 8; ++s)
wv[s] = __builtin_nontemporal_load(&Wp[((size_t)nt * ksteps + ch * 8 + s) * 32 + lane]);
int e8[4];
#pragma unroll
for (int q = 0; q < 4; ++q) e8[q] = (int)Ws[(size_t)(ch * 4 + q) * ldws + nt * 16 + col];
mxg_v2i af[8];
#pragma unroll
for (int s = 0; s < 8; ++s) {
if (live) {
const unsigned* pa = (const unsigned*)(A + (size_t)row * lda + (ch * 8 + s) * 16 + khalf * 8);
af[s][0] = (int)pa[0]; af[s][1] = (int)pa[1];
} else {
af[s][0] = 0; af[s][1] = 0;
}
}
mxg_v8f acc = (mxg_v8f)(0.f);
#pragma unroll
for (int s = 0; s < 8; ++s) {
unsigned lo, hi;
r4d_mxfp4_unpack8(wv[s], r4d_mxfp4_fold_d(ref, e8[s >> 1]), &lo, &hi);
mxg_v2i wf;
wf[0] = (int)lo; wf[1] = (int)hi;
acc = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[s], acc);
}
const float sc = ABLK ? (live ? As[(size_t)row * as_rs + ch] : 0.f) : 1.f;
#pragma unroll
for (int e = 0; e < 8; ++e) tot[e] = fmaf(acc[e], sc, tot[e]);
}
#pragma unroll
for (int e = 0; e < 8; ++e) sum[e] += tot[e];
}
// acc[e] (and so sum[e]): row (lane & 15), column khalf * 8 + e of the tile.
if (live) {
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int c = khalf * 8 + e;
const float rf = __int_as_float((int)Wref[nt * 16 + c] << 23);
const __hip_bfloat16 h = (__hip_bfloat16)(ABLK ? sum[e] * rf : sum[e] * rf * As[(size_t)row * as_rs]);
sG[wave][row][c] = *(const uint16_t*)&h;
}
}
__syncthreads();
// gated_quant_fp8: one wave a row, a lane four consecutive columns of the group.
if (wave < M) {
const int m = wave, c0 = lane * 4, t = c0 >> 4, cc = c0 & 15;
const size_t gcol = (size_t)blockIdx.x * 128 + c0;
float vq[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float g = mxg_bf2f(sG[t][m][cc + j]);
const float a = g / (1.0f + expf(-g));
const uint16_t h = mxg_f2bf(a * mxg_bf2f(sG[8 + t][m][cc + j]));
if (Y) Y[(size_t)m * y_ld + gcol + j] = h;
vq[j] = mxg_bf2f(h);
}
float mx = fmaxf(fmaxf(fabsf(vq[0]), fabsf(vq[1])), fmaxf(fabsf(vq[2]), fabsf(vq[3])));
mx = r4d_wave_max(mx);
const float sc = mx > 0.0f ? mx * (1.0f / q8_top<false>()) : 1.0f;
if (lane == 0) S[(size_t)m * s_ld + blockIdx.x] = sc;
const float inv = 1.0f / sc;
*(uint32_t*)(Q + (size_t)m * q_ld + gcol) = q8_pack4<false>(vq[0], vq[1], vq[2], vq[3], inv);
}
}
namespace {
void mxgg_launch(bool ablk, const void* a, const void* as, const void* w, const void* ws,
const void* wr, void* q, void* s, void* y, int M, int K, int n, int as_rs, int lda,
int ldws, int q_ld, int s_ld, int y_ld, RadStream stream) {
const dim3 grid((uint32_t)(n / 128)), block(16 * 32);
hipStream_t st = (hipStream_t)stream;
if (ablk)
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel<true>), grid, block, 0, st,
(const unsigned char*)a, (const float*)as, (const unsigned char*)w,
(const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s,
(uint16_t*)y, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld);
else
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel<false>), grid, block, 0, st,
(const unsigned char*)a, (const float*)as, (const unsigned char*)w,
(const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s,
(uint16_t*)y, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld);
}
} // namespace
/* The gated GEMM's shim. Operand indices are `gemm_nt_q_gated_mx`'s (oGemmNtQGatedMx in
* r4d_rows.cpp): gemm_nt_q_gated's with the per-row reference `b_ref` after `b_scale`. The weight
* is one [N, K] plane, gate rows then up rows, N = 2 * the gated width; no parts. */
enum { MXGG_A = 0, MXGG_AS = 1, MXGG_B = 2, MXGG_BS = 3, MXGG_BR = 4, MXGG_Q = 5, MXGG_S = 6,
MXGG_Y = 7 };
extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, MXGG_A);
const RadTensor* xs = r4d_opt(a, MXGG_AS);
const RadTensor* w = r4d_opt(a, MXGG_B);
const RadTensor* ws = r4d_opt(a, MXGG_BS);
const RadTensor* wr = r4d_opt(a, MXGG_BR);
const RadTensor* q = r4d_opt(a, MXGG_Q);
const RadTensor* sc = r4d_opt(a, MXGG_S);
const RadTensor* y = r4d_opt(a, MXGG_Y);
if (!x || !xs || !w || !ws || !wr || !q || !sc) return R4D_NO(RAD_E_INVAL);
if (q->rank != 2 || sc->rank != 2 || x->rank < 2) return R4D_NO(RAD_E_SHAPE);
if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (r4d_geti_or(a, "group", 32) != 32) return R4D_NO(RAD_E_SHAPE);
const char* act = r4d_gets(a, "act");
if (!act || std::strcmp(act, "silu")) return R4D_NO(RAD_E_UNSUPPORTED);
/* The gated width from `q`, the buffer written; N and K from the op's parameters, since the
* weight operands are packed bytes. */
const long long M = q->shape[0], nout = q->shape[1];
const long long N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0);
if (M < 1 || M > R4D_MXG_MAX_M || nout < 128 || nout % 128) return R4D_NO(RAD_E_SHAPE);
if (N != 2 * nout || K < 128 || K % 128) return R4D_NO(RAD_E_SHAPE);
if (x->shape[0] != M || r4d_numel(x) != M * K) return R4D_NO(RAD_E_SHAPE);
if (sc->shape[0] != M || sc->shape[1] != nout / 128) return R4D_NO(RAD_E_SHAPE);
if (y && (y->shape[0] != M || y->shape[1] != nout)) return R4D_NO(RAD_E_SHAPE);
/* The activation scale per (row, 128 of K), or per row. */
bool ablk;
long long as_rs;
if (xs->rank == 2 && xs->shape[0] == M && xs->shape[1] == K / 128) {
ablk = true;
as_rs = r4d_row_pitch(xs);
} else if (xs->rank == 1 && xs->shape[0] == M) {
ablk = false;
as_rs = 1;
} else {
return R4D_NO(RAD_E_SHAPE);
}
const long long lda = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
const long long yp = y ? r4d_row_pitch(y) : 0;
if (lda < 0 || as_rs < 0 || qp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || !r4d_aligned(q->data, 4) ||
!r4d_aligned(ws->data, 4) || !r4d_aligned(wr->data, 4) || qp % 4)
return R4D_NO(RAD_E_ALIGN);
R4D_TRY("gemm_mxfp4a8_gated",
mxgg_launch(ablk, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data,
y ? y->data : nullptr, (int)M, (int)K, (int)nout, (int)as_rs, (int)lda, (int)N,
(int)qp, (int)sp, (int)yp, s));
return RAD_OK;
}
+19
View File
@@ -939,6 +939,25 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand,
return RAD_OK;
}
/* gemm_nt_q_gated_mx's weights are gemm_nt_q's mxfp4a8 planes in the same stored forms, but its
* `b_ref` is operand 4, where gemm_nt_q has `y`: mapped to gemm_nt_q's index, so both ops ask for
* the reference plane in one form and the loader stores it once. */
static int mx_gated_operand(int operand) { return operand == 4 ? Q_BREF : operand; }
extern "C" int r4d_rad_layout_mxfp4_gated(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
return r4d_rad_layout_mxfp4(p, n_p, mx_gated_operand(operand), enc, sel, pl, n, out);
}
extern "C" int r4d_rad_relayout_mxfp4_gated(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) {
return r4d_rad_relayout_mxfp4(p, n_p, mx_gated_operand(operand), enc, sel, pl, n, dst,
dst_bytes);
}
/* ---- 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
+6
View File
@@ -459,6 +459,7 @@ int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
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);
int r4d_rad_dequant_w4 (const RadArgs*, RadStream);
int r4d_rad_rowtopk (const RadArgs*, RadStream);
int64_t r4d_rad_rowtopk_scratch(const RadArgs*);
@@ -665,6 +666,10 @@ int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const in
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_layout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*,
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_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*,
@@ -917,6 +922,7 @@ int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam*, int, uint64_t, int, RadFu
int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gemm_nt_q_gated_mx (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
+41
View File
@@ -1627,6 +1627,20 @@ static const RadOperandSpec oGemmNtQGated[] = {
{ "scale", RAD_OPD_OUT, 0 },
{ "out_bf16", RAD_OPD_OUT, 1 },
};
/* The same fold over an OCP-MXFP4 gate_up weight, which gemm_nt_q reads with a per-row reference
* exponent (`b_ref`) beside its scale plane. A schema of its own rather than an optional operand on
* gemm_nt_q_gated: an op's operand count is part of its contract with the plugins already built
* against it. */
static const RadOperandSpec oGemmNtQGatedMx[] = {
{ "a", RAD_OPD_IN, 0 },
{ "a_scale", RAD_OPD_IN, 0 },
{ "b", RAD_OPD_WEIGHT, 0 },
{ "b_scale", RAD_OPD_WEIGHT, 0 },
{ "b_ref", RAD_OPD_WEIGHT, 0 },
{ "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 },
{ "out_bf16", RAD_OPD_OUT, 1 },
};
/* The gate in a separate operand, as in a gated attention: the gate is a column slice of the
* [q|gate] projection and `x` the attention output, two buffers with different pitches. A row is a
@@ -3363,6 +3377,10 @@ static const RadOpSchema kSchemas[] = {
"columns) and optionally the bf16 product, and no [M, 2n] tensor is ever written. "
"Byte-identical to the two ops it replaces, which is what makes it substitutable "
"rather than a second numerical path."),
SCHEMA("gemm_nt_q_gated_mx", pGemmNtQGated, oGemmNtQGatedMx,
"gemm_nt_q_gated over an OCP-MXFP4 [2n, K] gate_up weight: gemm_nt_q at dtype mxfp4a8 "
"(`b_ref` the per-row reference exponent) with gated_quant_fp8's pass folded into the "
"epilogue, byte-identical to the two ops it replaces."),
SCHEMA("gate_quant_fp8", pGateQuantFp8, oGateQuantFp8,
"the same, with the gate in its own operand rather than packed beside x."),
SCHEMA("quant_act_fp8", pQuantActFp8, oQuantActFp8,
@@ -4808,6 +4826,12 @@ static const RadConstraint cGemmNtQGatedFp8[] = {
C_LE("M", 64), C_DIV("K", 256), C_DIV("N", 256), C_GE("N", 2048),
C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"),
};
/* r4d_gemm_mxfp4a8_gated_gemv: the gemv row's WMMA form (K a multiple of 128, M <= 8) with a block
* per 128-column group of the gated output (N/2 a multiple of 128). */
static const RadConstraint cGemmNtQGatedMx[] = {
C_LE("M", 8), C_DIV("K", 128), C_DIV("N", 256), C_EQ("group", 32), C_IN("dtype", "mxfp4a8"),
C_IN("act", "silu"),
};
static const RadConstraint cGateQuantFp8[] = {
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
};
@@ -7742,6 +7766,23 @@ 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_gemv, nullptr,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_gated_gemv", "gemm_nt_q_gated_mx", "gemm",
"the gemv row's WMMA form over a gate_up weight with gated_quant_fp8's pass in its epilogue: a "
"block per 128-column group of the gated output, a wave per gate or up tile running all of that "
"form's K partials in its order, so the [M, 2n] bf16 product is never written",
"M <= 8; K a multiple of 128; N a multiple of 256 (the gated width a multiple of the 128-column "
"scale group); act silu only; the skinny kernel's fragment-order weight, [K/32][N] E8M0 "
"exponents and per-row reference exponent, gate rows then up rows",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K, and the "
"QUANTISER's outputs: E4M3 codes, an f32 scale per (row, 128 columns) and an optional bf16 "
"product. Byte-identical to gemm_mxfp4a8_gemv followed by gated_quant_fp8",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGemmNtQGatedMx), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gated, nullptr,
r4d_rad_layout_mxfp4_gated, r4d_rad_relayout_mxfp4_gated, nullptr, nullptr,
/* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */
r4d_fuse_gemm_nt_q_gated_mx },
{ "gemm_mxfp4a8_decode", "gemm_nt_q", "gemm",
"the OCP-MXFP4 GEMM for the DECODE band: split-K across workgroups with a fused last-arriver "
"reduction, the weight unpacked through LDS, streaming weight loads",
+153
View File
@@ -6073,6 +6073,127 @@ static void w4a8_multi_user_exact(const Plugin& pl) {
}
}
/* ---- the MXFP4 gated fold, against the pair it replaces -------------------------------------
*
* gemm_mxfp4a8_gated_gemv (gemm_nt_q_gated_mx) against gemm_mxfp4a8_gemv followed by
* gated_quant_fp8, on the same weight bytes (one relayout, through the gemv row's hooks, which the
* gated row shares) and activation. Codes, scales and the bf16 product must be identical, and the
* codes mostly non-zero (zeroed buffers compare equal). Run twice: with `out_bf16`, and without it,
* where the codes and scales must still match. */
static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K, bool ablk) {
const char* row = "gemm_mxfp4a8_gated_gemv";
if (!sel(row)) return;
char nm[160];
std::snprintf(nm, sizeof nm, "%s byte-identical to gemv + gated_quant_fp8, M=%lld N=%lld K=%lld%s",
row, (long long)M, (long long)N, (long long)K, ablk ? " ascale=row x 128" : "");
const RadKernelInfo* rg = find(pl, row);
const RadKernelInfo* rv = find(pl, "gemm_mxfp4a8_gemv");
const RadKernelInfo* rq = find(pl, "gated_quant_fp8");
if (!rg || !rv || !rq || !rg->layout || !rg->relayout) { ok(nm, false, "row or hooks absent"); return; }
Planes p;
p.enc = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
p.size(N, K);
const int ic = p.find("codes"), is = p.find("scale");
if (ic < 0 || is < 0) { ok(nm, false, "encoding has no codes/scale plane"); return; }
mxfp4_fill(p, ic, is, N, K, 0x51u, true);
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 32) };
std::vector<uint8_t> wq, ws, wr;
/* Stored through the gated row's own hooks (its `b_ref` is operand 4), so the gemv row reading
* the same bytes also checks that both ops store the planes in one form. */
if (stored(rg, lp, 2, p, { "codes" }, &wq) != RAD_OK || stored(rg, lp, 3, p, { "scale" }, &ws) != RAD_OK ||
stored(rg, lp, 4, p, { "scale" }, &wr) != RAD_OK) {
ok(nm, false, "relayout refused");
return;
}
const int64_t nkb = K / 128, n = N / 2, gkb = n / 128;
std::vector<uint8_t> ha((size_t)(M * K));
std::vector<float> as((size_t)(M * (ablk ? nkb : 1)));
for (int64_t i = 0; i < M; ++i) {
if (ablk)
for (int64_t c = 0; c < nkb; ++c)
as[(size_t)(i * nkb + c)] = 0.002f * (float)(1 + st_mix32((uint32_t)(i * nkb + c)) % 97);
else
as[(size_t)i] = 0.0125f * (float)(1 + st_mix32((uint32_t)i ^ 0xa5u) % 5);
for (int64_t k = 0; k < K; ++k) rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, mxfp4_act(i, k, 0x3cu));
}
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((size_t)(M * N * 2));
void* d_q[3] = { dalloc((size_t)(M * n)), dalloc((size_t)(M * n)), dalloc((size_t)(M * n)) };
void* d_z[3] = { dalloc((size_t)(M * gkb * 4)), dalloc((size_t)(M * gkb * 4)), dalloc((size_t)(M * gkb * 4)) };
void* d_b[2] = { dalloc((size_t)(M * n * 2)), dalloc((size_t)(M * n * 2)) };
if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y || !d_q[2] || !d_z[2] || !d_b[1]) {
ok(nm, false, "hipMalloc failed");
return;
}
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);
const RadTensor ta = T(d_a, RAD_F8E4M3, { M, K });
const RadTensor tas = ablk ? T(d_s, RAD_F32, { M, nkb }) : T(d_s, RAD_F32, { M });
const RadTensor tw = T(d_w, RAD_U8, { (int64_t)wq.size() }), te = T(d_e, RAD_U8, { (int64_t)ws.size() });
const RadTensor tr = T(d_r, RAD_U8, { (int64_t)wr.size() });
/* The pair. */
RadTensor none = T(nullptr, RAD_F32, { 1 });
absent(none);
int rc = launch_row(rv, { ta, tas, tw, te, T(d_y, RAD_BF16, { M, N }), none, tr },
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") });
if (rc == RAD_OK)
rc = launch_row(rq, { T(d_y, RAD_BF16, { M, N }), T(d_q[0], RAD_F8E4M3, { M, n }),
T(d_z[0], RAD_F32, { M, gkb }), T(d_b[0], RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") });
if (rc != RAD_OK) { ok(nm, false, "the pair: rc=" + std::to_string(rc)); return; }
/* The fold, with and without the bf16 product. */
const std::vector<RadParam> gp = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "mxfp4a8"), PS("act", "silu") };
for (int v = 1; v <= 2; ++v) {
st_memset(d_q[v], 0, (size_t)(M * n));
st_memset(d_z[v], 0, (size_t)(M * gkb * 4));
}
st_memset(d_b[1], 0, (size_t)(M * n * 2));
rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[1], RAD_F8E4M3, { M, n }),
T(d_z[1], RAD_F32, { M, gkb }), T(d_b[1], RAD_BF16, { M, n }) }, gp);
if (rc == RAD_OK)
rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[2], RAD_F8E4M3, { M, n }),
T(d_z[2], RAD_F32, { M, gkb }), none }, gp);
if (rc != RAD_OK) { ok(nm, false, "the fold: rc=" + std::to_string(rc)); return; }
std::vector<uint8_t> c[3];
std::vector<float> z[3];
for (int v = 0; v < 3; ++v) {
c[v].resize((size_t)(M * n));
z[v].resize((size_t)(M * gkb));
st_memcpy(c[v].data(), d_q[v], c[v].size(), hipMemcpyDeviceToHost);
st_memcpy(z[v].data(), d_z[v], z[v].size() * 4, hipMemcpyDeviceToHost);
}
std::vector<uint16_t> b0((size_t)(M * n)), b1((size_t)(M * n));
st_memcpy(b0.data(), d_b[0], b0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(b1.data(), d_b[1], b1.size() * 2, hipMemcpyDeviceToHost);
int nc = 0, nz = 0, nb = 0, nc2 = 0, nz2 = 0, live = 0;
for (size_t i = 0; i < c[0].size(); ++i) {
nc += c[0][i] != c[1][i];
nc2 += c[0][i] != c[2][i];
live += c[1][i] != 0;
}
for (size_t i = 0; i < z[0].size(); ++i) {
nz += std::memcmp(&z[0][i], &z[1][i], 4) != 0;
nz2 += std::memcmp(&z[0][i], &z[2][i], 4) != 0;
}
for (size_t i = 0; i < b0.size(); ++i) nb += b0[i] != b1[i];
ok(nm, nc == 0 && nz == 0 && nb == 0 && nc2 == 0 && nz2 == 0 && live > (int)c[1].size() / 2,
"codes differ " + std::to_string(nc) + "/" + std::to_string(nc2) + ", scales " +
std::to_string(nz) + "/" + std::to_string(nz2) + ", bf16 " + std::to_string(nb) +
", nonzero " + std::to_string(live) + " of " + std::to_string(c[1].size()));
}
/* ---- the audio generator's ops and their optional forms, against libref's arithmetic ----------
*
* Each case builds its operands on the host, runs the row, and compares with the host port of the
@@ -13140,6 +13261,31 @@ static void mx_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "mxfp4a8") };
perf_row(pl, row, ts, ps, d_w, wq.size(), copies, (double)(wq.size() + ws.size()), iters);
/* At a gate_up shape the gemv row's GEMM is half of a pair: time the other half
* (gated_quant_fp8 over its output) and the fold that replaces both. */
if (!std::strcmp(row, "gemm_mxfp4a8_gemv") && N % 256 == 0 && K % 128 == 0) {
const int64_t n = N / 2;
void* d_q = dalloc((size_t)(M * n));
void* d_z = dalloc((size_t)(M * (n / 128) * 4));
if (!d_q || !d_z) { std::printf(" gated: hipMalloc failed\n"); continue; }
RadTensor nob = T(nullptr, RAD_BF16, { M, n });
absent(nob);
perf_row(pl, "gated_quant_fp8", { T(d_y, RAD_BF16, { M, N }), T(d_q, RAD_F8E4M3, { M, n }),
T(d_z, RAD_F32, { M, n / 128 }), nob },
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") },
d_y, (size_t)(M * N * 2), 1, (double)(M * N * 2), iters, 0);
const RadKernelInfo* rg = find(pl, "gemm_mxfp4a8_gated_gemv");
std::vector<uint8_t> gr;
if (rg && stored(rg, lp, 4, p, { "scale" }, &gr) == RAD_OK && gr == wr)
perf_row(pl, "gemm_mxfp4a8_gated_gemv",
{ T(d_a, RAD_F8E4M3, { M, K }), T(d_s, RAD_F32, { M, nkb }),
T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }),
T(d_r, RAD_U8, { (int64_t)wr.size() }), T(d_q, RAD_F8E4M3, { M, n }),
T(d_z, RAD_F32, { M, n / 128 }), nob },
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8"),
PS("act", "silu") },
d_w, wq.size(), copies, (double)(wq.size() + ws.size()), iters);
}
}
}
@@ -27203,6 +27349,13 @@ static void device_phase(const Plugin& pl) {
mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_gemv", 1088, 576, true);
mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_gemv", 1056, 576, false);
mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_decode", 5120, 5120, true);
/* The gated fold against the pair it replaces (gemv + gated_quant_fp8): Qwen's and
* TranslateGemma's per-rank gate_up at every M of the band, one group of 128 at the smallest
* K, and the per-row activation scale. */
for (const int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8 }) mxfp4a8_gated_case(pl, m, 17408, 5120, true);
mxfp4a8_gated_case(pl, 8, 21504, 5376, true);
mxfp4a8_gated_case(pl, 3, 256, 128, true);
mxfp4a8_gated_case(pl, 5, 1024, 640, false);
/* Parts (ParoQuant): each weight part against its own activation copy, with bounds off any
* kernel's tile, two and three parts, at every band. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 400, 640, 0, true, {}, 144);