libr4d: moe_gemm_mxfp4a8's small-M form at GLM's TP8 slices -- a one-stream verify pass is a chain of short expert launches

At 1 to 48 tokens a chunk (8 to 384 routed rows) the expert-major forms spent their time around
the loads rather than on them. Taking the loads out left gate_up at 72 of its 115 us at six
tokens; what remained was the skeleton of each block: 289 grid rows for the few touched experts,
activation scales read row by row from LDS behind a divergent branch, weight rows loaded through
generic pointers (flat loads, which every LDS wait also waits for), loads behind branches so each
store waited for the whole prefetch, and __syncthreads' workgroup fence. With 160 blocks resident
at 21.8 KiB of LDS each, the last round of an expert-major launch ran nearly empty, at the latency
of one block's chain.

moe_mxfp4_small_kernel keeps the expert-major per-element sequence, and so its bytes:

- block row y takes the y-th touched expert, counted by ballot over the offsets, so the grid has
  min(experts, rows) + 1 rows;
- weight codes stay packed in LDS and are decoded at the fragment read, halving the weight tile;
  gate_up stages 512 of K, reading 256 bytes of each weight row at once, down its 128-byte rows
  whole over four column tiles;
- loads are unconditional from clamped addresses and masked at the store, weight rows load
  through global pointers, the barriers order LDS only, and a 128 of K reads its activation scales
  and eight fragment pairs before its WMMA chains.

The rule takes it at GLM's TP8 slices for gate_up to 384 routed rows and down to 32; from five
tokens down reads 3 to 5 % slower than the staged form and keeps it. Other shapes are unchanged.
A deeper register prefetch, a barrier-free form with B straight from global memory and A tiles
sized to the chunk's tokens measured no faster.

Measured at the TP8 slices (r4d_selftest --cold 256 --perfmx), expert-major against small-M:

  tokens          1      3      6      8     16     48
  gate_up, us  36.8   79.5  120.5  145.0  230.3  416.7
               31.4   69.5  101.4  122.4  206.8  390.0

  tokens          1      2      3      4
  down, us     21.2   26.0   34.3   39.5
               16.4   22.5   33.2   37.9

Byte for byte against the expert-major forms over 1 to 48 tokens at every form tried (perfmx with
the old form kept beside it during the work), and in r4d_emu against the host restatement: three
GLM TP8 cases, with runs longer than one tile, dropped slots and E8M0 codes 0 and 255.
r4d_selftest checks the new band against libref at 1 to 48 tokens, and --perfmx names the form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NunzeandClaude Opus 5.5 committed 2026-10-21 15:26:57 +02:00
1 parent 332b5fa986
commit 961a9b3f13
3 files changed
+293 -6

No files matched your search

+239
View File
@@ -837,6 +837,228 @@ __global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel(
}
}
/* The small-M form at GLM's TP8 slices: expert-major with the same per-element sequence as the two
* forms above, so their bytes. A verify pass of one stream routes 8 to 48 rows over as many
* experts, and there those forms spend their time around the loads: an expert's block was a long
* chain of short stages, and the blocks the LDS admitted came in rounds whose last one ran nearly
* empty. This form shortens and thins the chain:
* - Block row y takes the y-th touched expert (a wave counts the non-empty runs by ballot), so the
* grid has min(experts, rows) + 1 rows rather than one an expert, most of them idle.
* - Weight codes stay packed in LDS and are decoded at the fragment read, which halves the
* weight tile; gate_up stages 512 of K, so a stage reads 256 bytes of each weight row where the
* 256 stage read 128, and down reads its 128-byte rows whole over four column tiles.
* - Loads are unconditional from clamped addresses and masked at the store, so a store waits for
* its own stage and not the prefetch; weight rows load through global pointers, the barriers
* order LDS only, and a 128 of K reads its activation scales and eight fragment pairs before its
* WMMA chains. */
template <int StageK>
struct MxSmall {
static constexpr int Threads = 128, BN = 64, KB = StageK / 128, PA = StageK + 8,
PB = StageK / 2 + 8;
static constexpr int AChunks = StageK / Threads, WChunks = BN * StageK / 32 / Threads,
SChunks = (BN * KB + Threads - 1) / Threads;
mx_u4 a[AChunks], w[WChunks];
uint32_t s[SChunks];
float sa;
uint32_t ok;
};
template <int StageK, int ColTiles>
__global__ __launch_bounds__(128) void moe_mxfp4_small_kernel(
const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1,
const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
using St = MxSmall<StageK>;
constexpr int BN = St::BN, Threads = St::Threads, KB = St::KB, PA = St::PA, PB = St::PB;
static_assert(St::AChunks <= 8 && St::WChunks <= 16 && St::SChunks <= 4 &&
16 * KB <= Threads && BN * PB >= 4 * 513,
"stage chunks must fit the load mask and the offsets the weight tile");
__shared__ __align__(16) uint8_t aa[16 * PA], bb[BN * PB];
__shared__ uint32_t ss[BN * KB];
__shared__ float sa[16 * KB];
__shared__ int src[16];
__shared__ int pick;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int colb = blockIdx.x * (BN * ColTiles);
if ((int)blockIdx.y == (int)gridDim.y - 1) {
const int r0 = offset[m.experts];
for (long i = tid; i < (long)(m.T - r0) * BN * ColTiles; i += Threads) {
const int n = colb + (int)(i % (BN * ColTiles));
if (n < m.N) y[(long)(r0 + i / (BN * ColTiles)) * m.yr + n] = 0;
}
return;
}
{
// The offsets in the weight tile, whose bytes are free until the first stage.
int* offs = reinterpret_cast<int*>(bb);
#pragma unroll
for (int q = 0; q < 5; ++q) {
const int x = tid + q * Threads;
if (x <= m.experts) offs[x] = offset[x];
}
lds_barrier();
if (wave == 0) {
int want = blockIdx.y, found = -1;
for (int base = 0; base < m.experts; base += 32) {
const int x = base + lane;
const bool live = x < m.experts && offs[x + 1] > offs[x];
const uint32_t mask = __builtin_amdgcn_ballot_w32(live);
const int n = __builtin_popcount(mask);
if (want < n) {
const uint32_t below = mask & ((1u << lane) - 1u);
found = base + __builtin_ctz(__builtin_amdgcn_ballot_w32(
live && __builtin_popcount(below) == want));
break;
}
want -= n;
}
if (lane == 0) pick = found;
}
lds_barrier();
}
const int e = pick;
if (e < 0) return;
const int lo = offset[e], hi = offset[e + 1];
const int cls = e & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts;
const auto* w = entry(cls ? w1 : w0, m.wstep[cls], e / 2);
const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], e / 2);
const int ksn = (kc + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + BN - 1) / BN),
S = tiles * ksn;
const int rowbase = (lane >> 4) * 8, mycol = wave * 16 + (lane & 15);
auto wrow = [&](int n, bool& valid) {
const int within = n % pw;
valid = n < m.N && within < cw;
return (n / pw) * cw + within;
};
for (int r0 = lo; r0 < hi; r0 += 16) {
lds_barrier();
if (tid < 16) {
const int r = r0 + tid, flat = r < hi ? sorted[r] : -1;
const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk;
src[tid] = ar >= 0 && ar < m.Arows ? ar : -1;
}
lds_barrier();
bool rv[8];
#pragma unroll
for (int j = 0; j < 8; ++j) rv[j] = src[rowbase + j] >= 0;
auto load = [&](int s, St& L) {
const int col0 = colb + (s / ksn) * BN, k0 = (s % ksn) * StageK;
uint32_t ok = 0;
#pragma unroll
for (int i = 0; i < St::AChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16),
d = (j % (StageK / 16)) * 16, ar = src[r];
const bool v = ar >= 0 && k0 + d < kc;
__builtin_memcpy(&L.a[i], a + (v ? (long)ar * m.ar + k0 + d : 0), 16);
ok |= (uint32_t)v << i;
}
#pragma unroll
for (int i = 0; i < St::WChunks; ++i) {
const int j = tid + i * Threads, c = j / (StageK / 32),
d = (j % (StageK / 32)) * 16;
bool valid;
const int wn = wrow(col0 + c, valid);
const bool v = valid && k0 + 2 * d < kc;
const r4d_u32x4 q = mx_ldg16(w + (v ? (long)wn * m.wrow[cls] + k0 / 2 + d : 0));
L.w[i] = mx_u4{ q[0], q[1], q[2], q[3] };
ok |= (uint32_t)v << (8 + i);
}
#pragma unroll
for (int i = 0; i < St::SChunks; ++i) {
const int j = tid + i * Threads, c = j / KB, kb = k0 + (j % KB) * 128;
bool valid;
const int wn = wrow(col0 + c, valid);
const bool v = j < BN * KB && valid && kb < kc;
L.s[i] = mx_ldg4(ws + (v ? (long)wn * m.srow[cls] + kb / 32 : 0));
ok |= (uint32_t)v << (24 + i);
}
{
const int ar = src[(tid / KB) & 15], kb = k0 + (tid % KB) * 128;
const bool v = tid < 16 * KB && ar >= 0 && kb < kc;
L.sa = as[v ? (long)ar * m.asr + kb / 128 : 0];
ok |= (uint32_t)v << 28;
}
L.ok = ok;
};
auto store = [&](const St& L) {
#pragma unroll
for (int i = 0; i < St::AChunks; ++i) {
const int j = tid + i * Threads, r = j / (StageK / 16),
d = (j % (StageK / 16)) * 16;
*reinterpret_cast<mx_u4*>(aa + r * PA + d) =
(L.ok >> i) & 1u ? L.a[i] : mx_u4{ 0, 0, 0, 0 };
}
#pragma unroll
for (int i = 0; i < St::WChunks; ++i) {
const int j = tid + i * Threads, c = j / (StageK / 32),
d = (j % (StageK / 32)) * 16;
const mx_u4 q = (L.ok >> (8 + i)) & 1u ? L.w[i] : mx_u4{ 0, 0, 0, 0 };
*reinterpret_cast<uint2*>(bb + c * PB + d) = uint2{ q[0], q[1] };
*reinterpret_cast<uint2*>(bb + c * PB + d + 8) = uint2{ q[2], q[3] };
}
#pragma unroll
for (int i = 0; i < St::SChunks; ++i) {
const int j = tid + i * Threads;
if (j < BN * KB) ss[j] = (L.ok >> (24 + i)) & 1u ? L.s[i] : 0x7f7f7f7fu;
}
if (tid < 16 * KB) sa[(tid % KB) * 16 + tid / KB] = (L.ok >> 28) & 1u ? L.sa : 0.f;
};
auto total = r4d_fp8::acc_zero();
auto compute = [&](int s) {
const int k0 = (s % ksn) * StageK;
#pragma unroll
for (int kb = 0; kb < KB; ++kb) {
if (k0 + kb * 128 >= kc) break;
const uint32_t exps = ss[mycol * KB + kb];
float act[8];
#pragma unroll
for (int row = 0; row < 8; ++row) act[row] = sa[kb * 16 + rowbase + row];
r4d_fp8::i2v fa[8], fb[8];
#pragma unroll
for (int t = 0; t < 8; ++t) {
const int k = kb * 128 + 16 * t;
fa[t] = r4d_fp8::frag<StageK>(aa, 0, k, lane);
const uint2 v = mx_codes8(
*reinterpret_cast<const uint32_t*>(bb + mycol * PB + (k + rowbase) / 2));
fb[t] = r4d_fp8::i2v{ (int)v.x, (int)v.y };
}
r4d_fp8::f8v raw[4];
#pragma unroll
for (int g = 0; g < 4; ++g)
raw[g] = r4d_fp8::mma(fa[2 * g], fb[2 * g], r4d_fp8::acc_zero());
#pragma unroll
for (int g = 0; g < 4; ++g) raw[g] = r4d_fp8::mma(fa[2 * g + 1], fb[2 * g + 1], raw[g]);
#pragma unroll
for (int g = 0; g < 4; ++g) {
const uint32_t exp = (exps >> (8 * g)) & 0xffu;
const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u
: exp ? (exp << 23)
: 0x00400000u);
#pragma unroll
for (int row = 0; row < 8; ++row)
if (rv[row]) total[row] += raw[g][row] * act[row] * scale;
}
}
if (s % ksn == ksn - 1) {
const int n = colb + (s / ksn) * BN + mycol;
#pragma unroll
for (int row = 0; row < 8; ++row) {
const int r = r0 + rowbase + row;
if (r < hi && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]);
}
total = r4d_fp8::acc_zero();
}
};
St L;
load(0, L);
for (int s = 0; s < S; ++s) {
store(L);
lds_barrier();
if (s + 1 < S) load(s + 1, L);
compute(s);
lds_barrier();
}
}
}
int table(const RadTensor* t, uint32_t dtype, int bits, long experts, long n, long k, long* step,
int* row) {
if (!t || !t->data || t->rank != 3 || t->dtype != dtype || t->shape[0] < experts ||
@@ -934,6 +1156,23 @@ int body(const RadArgs* a, RadStream stream) {
if (wide) return MX_P64(64, 128, 128, 1, false);
return bm == 64 ? MX_P64(64, 64, 256, 1, false) : MX_P64(32, 64, 256, 1, false);
#undef MX_P64
}
/* The small-M form at GLM's TP8 slices, ahead of the expert-major band: gate_up up to 384
* routed rows, down up to 32, where it stops gaining (at 5 to 8 tokens it reads 3 to 5 %
* slower than the staged form). Measured at those slices (perfmx, cold), expert-major against
* small-M: gate_up at 1, 3, 6, 8, 16 and 48 tokens 36.8/31.4, 79.5/69.5, 120.5/101.4,
* 145.0/122.4, 230.3/206.8 and 416.7/390.0 us; down at 1, 2 and 4 tokens 21.2/16.4, 26.0/22.5
* and 39.5/37.9 us. */
if (tp8 && m.T <= (m.K <= 256 ? 32 : 384)) {
const long rows = std::min<long>(m.experts, m.T) + 1;
#define MX_SMALL(SK, CT) \
R4D_EMIT(stream, (moe_mxfp4_small_kernel<SK, CT>), \
dim3(((long)m.N + 64 * CT - 1) / (64 * CT), rows), dim3(128), 0, \
(const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \
w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \
(uint16_t*)y->data, m)
return m.K <= 256 ? MX_SMALL(256, 4) : MX_SMALL(512, 1);
#undef MX_SMALL
}
/* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted
* rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form
+13 -5
View File
@@ -15007,8 +15007,8 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co
*
* The form is the launcher's rule, mirrored here only to name it and count the expert slices it
* streams: a (job, expert) pair reads the whole slice across the column blocks, so row groups
* re-read an expert once per group its run spans, the expert-major decode form once per 16 of its
* rows, and the P64 and GLM prefill forms once per job. */
* re-read an expert once per group its run spans, the expert-major and small-M forms once per 16
* of its rows, and the P64 and GLM prefill forms once per job. */
static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_t top_k,
bool f8 = false, const char* skew = nullptr) {
if (iters <= 0) iters = 100;
@@ -15235,11 +15235,12 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_
const int64_t pbm = pwide || (K > 256 && Tr >= 12288) ? 64 : 32;
const bool p64 =
glm && Tr >= (P.srt ? 5760 : 769) && (Tr + pbm - 1) / pbm + E <= 65535;
const bool expert = !p64 && (f8 || Tr <= (glm ? (P.srt ? 6143 : 768) : 511));
const bool pipe = !p64 && !expert && glm;
const bool small = glm && Tr <= (P.srt ? 32 : 384);
const bool expert = !p64 && !small && (f8 || Tr <= (glm ? (P.srt ? 6143 : 768) : 511));
const bool pipe = !p64 && !small && !expert && glm;
const int64_t jr = p64 ? pbm : pipe ? 32 : 16;
int64_t streams = 0;
if (p64 || pipe || expert)
if (p64 || pipe || expert || small)
for (int64_t e = 0; e < E; ++e)
streams += (off[(size_t)(e + 1)] - off[(size_t)e] + jr - 1) / jr;
else
@@ -15249,6 +15250,7 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_
p64 ? fmt("P64 BM%lld BN%d K%d", (long long)pbm, pwide ? 128 : 64,
K > 256 && !pwide ? 256 : 128) +
(K <= 256 ? " x4, A resident" : "") + (pwide ? ", LDS out" : "")
: small ? fmt("small-M K%d x%d tiles", K <= 256 ? 256 : 512, K <= 256 ? 4 : 1)
: expert ? fmt("expert-major K%d x%d tiles", K <= 256 ? 128 : 256,
K <= 256 || (f8 && Tr < 128) ? 4 : 1)
: pipe ? std::string("GLM prefill form, jobs of 32 rows")
@@ -26495,6 +26497,12 @@ static void device_phase(const Plugin& pl) {
mx_experts_check(pl, m, shape % 2 ? 2 : 1, false, shape == 2 ? "sorted" : "token",
shape, true, 288, 8);
}
// At GLM's TP8 slices the small-M form for gate_up to 384 routed rows and down to 32,
// the expert-major form for down above, with dropped slots.
for (int m : { 1, 3, 4, 6, 8, 12, 48 }) {
mx_experts_check(pl, m, 2, m % 2 == 0, "token", 3, false, 288, 8, true);
mx_experts_check(pl, m, 1, m % 2 != 0, "sorted", 4, m == 3, 288, 8, true);
}
// At GLM's TP8 slices the expert-major form to its bound (gate_up 768 rows, down below
// P64's 5760), then P64 by its rule: gate_up BM32 BN64 K256 from 769 rows, BM64 BN64 K256
// from 12288 and BM64 BN128 K128 with the LDS output from 24576; down BM32 BN64 K128 x4
+41 -1
View File
@@ -7,7 +7,8 @@
* slice the P64 form with streamed A. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, dropped
* slots inside runs and past the routed rows, columns an odd expert does not have, a shorter K for
* odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes and pointer
* tables. The table decode is also held to the arithmetic one over every code. */
* tables. At GLM's TP8 slices below P64 the small-M form, with runs longer than one tile. The
* table decode is also held to the arithmetic one over every code. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
@@ -201,6 +202,45 @@ int main() {
glm_runs({ 200, 33, 300, 31, 200 }),
20,
"(moe_mxfp4_p64_kernel<32, 64, 256, 1, false>)" },
{ "GLM TP8 gate_up, small-M form, four tokens",
512,
4096,
512,
4096,
2,
8,
false,
true,
false,
glm_runs({ 1, 2, 1, 3, 1, 6, 1, 2, 9, 1 }),
5,
"(moe_mxfp4_small_kernel<512, 1>)" },
{ "GLM TP8 gate_up, small-M form, runs past one tile",
512,
4096,
512,
4096,
2,
8,
false,
true,
true,
glm_runs({ 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }),
2,
"(moe_mxfp4_small_kernel<512, 1>)" },
{ "GLM TP8 down, small-M form, a run past one tile",
4096,
256,
4096,
256,
1,
8,
true,
true,
true,
glm_runs({ 3, 1, 17, 2, 1, 1, 1 }),
5,
"(moe_mxfp4_small_kernel<256, 4>)" },
{ "GLM TP8 down, P64 BM32 BN64 K128 x4, A resident",
4096,
256,