radiance 2.0.0

Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an
int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block
FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such
weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5,
Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0
serves all of them.

Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new
Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill
reworked, and a reworked adaptive draft window.

Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its
configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool
in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server,
each accelerator's memory by model, model states over time.

Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by
AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests
keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410);
eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d
large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi
(#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon
(#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and
multi-model serving as asked for in #367 and #109.

Plugin ABI 39: out-of-tree plugins need to be rebuilt.

Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
Deadcode committed 2026-11-14 22:32:28 +01:00
1 parent b4c04b6042
commit ddcb9c69bb
696 files changed
+120770 -56596

No files matched your search

-17
View File
@@ -1,17 +0,0 @@
/* cfg_stub.cpp -- the two tuned-configuration readers the M2XFP4 GEMM units call
* (r4d_cfg_mxfp4_decode, r4d_cfg_mxfp4_tiled), which libr4d defines on its declaration side
* (r4d_rows.cpp) beside the row tables. That side is not in the emu build, and every r4d_emu_*
* binary links every unit, so the readers are defined once here. Every axis default of
* tGemmMxfp4Decode and tGemmMxfp4Tiled is 0, the kernels' own rule, so reading the key or 0 is
* what r4d_rows.cpp's readers return for a caller with no tuned point. */
#include "r4d_args.h"
extern "C" void r4d_cfg_mxfp4_decode(const RadArgs* a, R4dMxDecCfg* out) {
out->ks = (int)rad_args_geti_or(a, "ks", 0);
out->bk = (int)rad_args_geti_or(a, "bk", 0);
out->nt = (int)rad_args_geti_or(a, "nt", 0);
}
extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) {
out->tn = (int)rad_args_geti_or(a, "tn", 0);
}
+119 -41
View File
@@ -1,6 +1,8 @@
#include "hip/hip_runtime.h"
#include "rad_plugin.h"
#include <algorithm>
#include <cstdio>
#include <emmintrin.h>
#include <cstdlib>
#include <cstring>
#include <memory>
@@ -59,9 +61,29 @@ struct Sched {
int slot[64][2][32] = {};
int tag[64][2][32] = {}; /* which op, and its uniform operand, each lane posted */
unsigned xparity[1024] = {};
/* each wave's live lanes and returned-lane mask, kept as lanes return: a barrier arrival
* reads them rather than walking the wave */
int walive[64] = {};
unsigned wdone[64] = {};
/* the wave generation whose exchange slots have been checked and poisoned, by parity */
unsigned xchecked[64][2] = {};
/* bumped by every barrier arrival and every lane's return: a round that leaves it unchanged
* made no progress */
uint64_t progress = 0;
} S;
void yield() { Fiber& me = S.f[S.cur]; emu_switch(&me.sp, S.main_sp); }
/* Hands the core to the next live fiber of the round, in thread order, or back to the scheduler
* after the last: the order fibers run in is the scheduler's own, at one switch a hand-off. */
void yield() {
Fiber& me = S.f[S.cur];
for (int t = S.cur + 1; t < S.nthreads; ++t)
if (!S.f[t].done) {
S.cur = t;
emu_switch(&me.sp, S.f[t].sp);
return;
}
emu_switch(&me.sp, S.main_sp);
}
/* Lanes of wave `w` that have not returned. A cross-lane op on the card runs over the active lanes:
* a lane that has returned takes no part, and the op completes without it (a read of its value is
@@ -73,21 +95,16 @@ int g_wmma_pending[64]; /* the wave exchange now forming is a WMMA's, which ev
* arrive, so a lane reads this before it can be overwritten. */
unsigned g_absent[64];
unsigned wave_done_mask(int w);
unsigned wave_done_mask(int w) {
unsigned m = 0;
for (int i = 0; i < 32 && w * 32 + i < S.nthreads; ++i) m |= (unsigned)S.f[w * 32 + i].done << i;
return m;
}
int wave_alive(int w) {
int n = 0;
for (int i = w * 32; i < w * 32 + 32 && i < S.nthreads; ++i) n += !S.f[i].done;
return n;
}
unsigned wave_done_mask(int w) { return S.wdone[w]; }
int wave_alive(int w) { return S.walive[w]; }
extern "C" void emu_trampoline() {
S.body(S.ctx);
S.f[S.cur].done = true;
/* The lanes still running may be waiting at a wave exchange only this lane had yet to reach. */
const int w = (int)S.f[S.cur].tid.x >> 5;
--S.walive[w];
S.wdone[w] |= 1u << ((int)S.f[S.cur].tid.x & 31);
++S.progress;
if (S.warrive[w] > 0 && S.warrive[w] == wave_alive(w)) {
if (g_wmma_pending[w]) {
std::fprintf(stderr, "emu: block (%u,%u,%u), wave %d: lane %d returned while the others wait at a "
@@ -125,6 +142,7 @@ void __syncthreads() {
/* Clearing the next generation's slot here, as the barrier completes, keeps it ahead of every
* write to it (threads arrive at g + 1 only after g completes) and behind every read of the
* slot it shares a residue with (g - 2's, read before arriving at g - 1). */
++S.progress;
if (++S.arrive == S.nthreads) { S.arrive = 0; S.or_acc[(g + 1) % 3] = 0; ++S.gen; return; }
me.waiting = 1;
while (S.gen == g) yield();
@@ -140,6 +158,7 @@ int __syncthreads_or(int p) {
static void wave_barrier(int w) {
Fiber& me = S.f[S.cur];
const unsigned g = S.wgen[w];
++S.progress;
if (++S.warrive[w] == wave_alive(w)) {
g_absent[w] = wave_done_mask(w);
S.warrive[w] = 0; ++S.wgen[w]; g_wmma_pending[w] = 0;
@@ -163,6 +182,10 @@ static const int* exchange(int v, int* lane, int tag) {
S.slot[w][par][*lane] = v;
S.tag[w][par][*lane] = tag;
wave_barrier(w);
/* The exchange's slots are checked and poisoned once, by the first lane to read them: the
* wave's generation names the exchange until every live lane has read it. */
if (S.xchecked[w][par] == S.wgen[w]) return S.slot[w][par];
S.xchecked[w][par] = S.wgen[w];
for (int i = 0; i < 32; ++i) {
if ((g_absent[w] >> i) & 1u) { /* a lane that had returned: no value; a read of it shows */
S.slot[w][par][i] = 0x7fbadbad;
@@ -203,7 +226,12 @@ static void wmma_whole_wave(int w) {
}
}
/* One 16x16x16 WMMA: each lane posts its A and B elements, then reads the whole tile back. `ga`
* and `gb` are the exchange slots of one element type, [wave][parity][lane][element]. */
* and `gb` are the exchange slots of one element type, [wave][parity][lane][element].
*
* A lane's eight outputs are rows M = 8h + e of column N. Its operands are converted once, A
* transposed to [k][e], and the eight sums run in two SSE2 registers: each step multiplies and
* then adds (the file builds with -ffp-contract=off), every output in k order from c, as the
* hardware's own order is restated in the tests' host references. */
template <class T, class V, class Cvt>
static emu_v8f emu_wmma(T (&ga)[64][2][32][8], T (&gb)[64][2][32][8], V a, V b, emu_v8f c,
Cvt cvt) {
@@ -213,36 +241,71 @@ static emu_v8f emu_wmma(T (&ga)[64][2][32][8], T (&gb)[64][2][32][8], V a, V b,
wmma_whole_wave(w);
wave_barrier(w);
const int N = l & 15, h = l >> 4;
emu_v8f d;
for (int e = 0; e < 8; ++e) {
const int M = 8 * h + e;
float acc = c[e];
for (int k = 0; k < 16; ++k)
acc += cvt(ga[w][par][M + 16 * (k >> 3)][k & 7]) * cvt(gb[w][par][N + 16 * (k >> 3)][k & 7]);
d[e] = acc;
alignas(16) float at[16][8];
float bt[16];
for (int k = 0; k < 16; ++k) {
const int slot = 16 * (k >> 3), el = k & 7;
bt[k] = cvt(gb[w][par][N + slot][el]);
for (int e = 0; e < 8; ++e) at[k][e] = cvt(ga[w][par][8 * h + e + slot][el]);
}
__m128 lo = _mm_setr_ps(c[0], c[1], c[2], c[3]), hi = _mm_setr_ps(c[4], c[5], c[6], c[7]);
for (int k = 0; k < 16; ++k) {
const __m128 bk = _mm_set1_ps(bt[k]);
lo = _mm_add_ps(lo, _mm_mul_ps(_mm_load_ps(at[k]), bk));
hi = _mm_add_ps(hi, _mm_mul_ps(_mm_load_ps(at[k] + 4), bk));
}
alignas(16) float out[8];
_mm_store_ps(out, lo);
_mm_store_ps(out + 4, hi);
emu_v8f d;
for (int e = 0; e < 8; ++e) d[e] = out[e];
return d;
}
namespace {
/* Every binary16 pattern's value: the baseline ISA has no F16C, so a conversion is a libgcc call. */
struct HalfTable {
std::unique_ptr<float[]> v{ new float[65536] };
HalfTable() {
for (uint32_t i = 0; i < 65536; ++i) {
const uint16_t u = (uint16_t)i;
_Float16 h;
std::memcpy(&h, &u, 2);
v[i] = (float)h;
}
}
};
const HalfTable g_half;
}
static short g_wa[64][2][32][8], g_wb[64][2][32][8];
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) {
return emu_wmma(g_wa, g_wb, a, b, c, [](short v) { return rad_bf16_to_f32((uint16_t)v); });
}
static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8];
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) {
return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) { return (float)v; });
return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) {
uint16_t u;
std::memcpy(&u, &v, 2);
return g_half.v[u];
});
}
namespace {
struct Bytes8 {
uint8_t v[8];
uint8_t operator[](int e) const { return v[e]; }
};
/* Every E4M3 code's value, from the ABI's own converter. */
struct Fp8Table {
float v[256];
Fp8Table() { for (int i = 0; i < 256; ++i) v[i] = rad_fp8e4m3_to_f32((uint8_t)i); }
};
const Fp8Table g_fp8;
}
static uint8_t g_qa[64][2][32][8], g_qb[64][2][32][8];
emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c) {
Bytes8 pa, pb;
std::memcpy(pa.v, &a, 8);
std::memcpy(pb.v, &b, 8);
return emu_wmma(g_qa, g_qb, pa, pb, c, [](uint8_t v) { return rad_fp8e4m3_to_f32(v); });
return emu_wmma(g_qa, g_qb, pa, pb, c, [](uint8_t v) { return g_fp8.v[v]; });
}
emu_v8i emu_wmma_iu8(bool, emu_v2i, bool, emu_v2i, emu_v8i, bool) {
std::fprintf(stderr, "emu: v_wmma_i32_16x16x16_iu8 is not emulated\n");
@@ -330,7 +393,12 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
std::memset(g_lds, 0xA5, dyn_lds);
S.arrive = 0; S.gen = 0;
for (int& a : S.or_acc) a = 0;
for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; g_wmma_pending[w] = 0; g_absent[w] = 0; }
for (int w = 0; w < 64; ++w) {
S.warrive[w] = 0; S.wgen[w] = 0; g_wmma_pending[w] = 0; g_absent[w] = 0;
S.walive[w] = std::max(0, std::min(32, n - 32 * w));
S.wdone[w] = 0;
S.xchecked[w][0] = S.xchecked[w][1] = ~0u;
}
for (int t = 0; t < n; ++t) {
Fiber& f = S.f[t];
f.done = false; f.waiting = 0; f.tid = EmuIdx{(unsigned)t, 0, 0};
@@ -344,18 +412,17 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
int live = n;
while (live > 0) {
const int live_before = live;
const unsigned g0 = S.gen; unsigned wg0[64]; for (int w = 0; w < 64; ++w) wg0[w] = S.wgen[w];
int arr0 = S.arrive; int warr0[64]; for (int w = 0; w < 64; ++w) warr0[w] = S.warrive[w];
const uint64_t p0 = S.progress;
/* One round: the first live fiber runs, each hands on to the next (yield), and the
* last hands back here. */
int first = 0;
while (S.f[first].done) ++first;
S.cur = first;
emu_switch(&S.main_sp, S.f[first].sp);
S.cur = -1;
live = 0;
for (int t = 0; t < n; ++t) {
if (S.f[t].done) continue;
S.cur = t;
emu_switch(&S.main_sp, S.f[t].sp);
S.cur = -1;
if (!S.f[t].done) ++live;
}
bool progressed = S.gen != g0 || S.arrive != arr0 || live != live_before;
for (int w = 0; w < 64; ++w) progressed |= (S.wgen[w] != wg0[w]) || (S.warrive[w] != warr0[w]);
for (int t = 0; t < n; ++t) live += !S.f[t].done;
const bool progressed = S.progress != p0 || live != live_before;
if (live > 0 && !progressed) {
int done = 0, wb = 0, bb = 0;
for (auto& f : S.f) { done += f.done; wb += f.waiting == 2; bb += f.waiting == 1; }
@@ -374,6 +441,8 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
* that replicates its operands across the halves (the documented form) sees no difference; one that
* leaves the lanes the part never reads holding something else is emulated as the part runs it. */
static uint16_t g11_a[64][2][32][16], g11_b[64][2][32][16];
/* As emu_wmma: the lane's operands converted once (A transposed to [k][e]), then the eight sums
* in two SSE2 registers, each in k order from c, multiply then add. */
template <class Cvt>
static emu_v8f emu_wmma11(const uint16_t (&a)[16], const uint16_t (&b)[16], emu_v8f c, Cvt cvt) {
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
@@ -382,14 +451,23 @@ static emu_v8f emu_wmma11(const uint16_t (&a)[16], const uint16_t (&b)[16], emu_
wmma_whole_wave(w);
wave_barrier(w);
const int N = l & 15, h = l >> 4;
emu_v8f d;
for (int e = 0; e < 8; ++e) {
const int M = 2 * e + h;
float acc = c[e];
for (int k = 0; k < 16; ++k)
acc += cvt(g11_a[w][par][M + 16 * h][k]) * cvt(g11_b[w][par][N + 16 * h][k]);
d[e] = acc;
alignas(16) float at[16][8];
float bt[16];
for (int k = 0; k < 16; ++k) {
bt[k] = cvt(g11_b[w][par][N + 16 * h][k]);
for (int e = 0; e < 8; ++e) at[k][e] = cvt(g11_a[w][par][2 * e + h + 16 * h][k]);
}
__m128 lo = _mm_setr_ps(c[0], c[1], c[2], c[3]), hi = _mm_setr_ps(c[4], c[5], c[6], c[7]);
for (int k = 0; k < 16; ++k) {
const __m128 bk = _mm_set1_ps(bt[k]);
lo = _mm_add_ps(lo, _mm_mul_ps(_mm_load_ps(at[k]), bk));
hi = _mm_add_ps(hi, _mm_mul_ps(_mm_load_ps(at[k] + 4), bk));
}
alignas(16) float out[8];
_mm_store_ps(out, lo);
_mm_store_ps(out + 4, hi);
emu_v8f d;
for (int e = 0; e < 8; ++e) d[e] = out[e];
return d;
}
emu_v8f emu_wmma11_bf16(emu_v16bf a, emu_v16bf b, emu_v8f c) {
@@ -402,7 +480,7 @@ emu_v8f emu_wmma11_f16(emu_v16h a, emu_v16h b, emu_v8f c) {
uint16_t ua[16], ub[16];
std::memcpy(ua, &a, 32);
std::memcpy(ub, &b, 32);
return emu_wmma11(ua, ub, c, [](uint16_t v) { _Float16 h; std::memcpy(&h, &v, 2); return (float)h; });
return emu_wmma11(ua, ub, c, [](uint16_t v) { return g_half.v[v]; });
}
emu_v2hf emu_cvt_pkrtz(float a, float b) {
auto rtz = [](float f) {
+1
View File
@@ -33,6 +33,7 @@ inline hipError_t hipGetLastError() { return 0; }
/* one device, with the R9700's 64 KiB of LDS a workgroup, which launchers size dynamic LDS by */
struct hipDeviceProp_t { size_t sharedMemPerBlock; int multiProcessorCount; };
inline hipError_t hipGetDevice(int* d) { *d = 0; return hipSuccess; }
inline hipError_t hipSetDevice(int) { return hipSuccess; }
/* no graphs: a stream never captures */
enum hipStreamCaptureStatus { hipStreamCaptureStatusNone = 0 };
inline hipError_t hipStreamIsCapturing(hipStream_t, hipStreamCaptureStatus* s) {
+28 -3
View File
@@ -67,7 +67,19 @@ static bool hgain(const RadTensor* w, int64_t n) {
return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n;
}
/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs */
/* The unnormalised Hadamard of 128 values in place, strides ascending: had_quant_act_i8g's. */
static void hfwht128(float* v) {
for (int h = 1; h < 128; h <<= 1)
for (int i = 0; i < 128; ++i)
if ((i & h) == 0) {
const float x = v[i], y = v[i + h];
v[i] = x + y;
v[i + h] = x - y;
}
}
/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs; an int8 `q` takes
* norm_add_norm_route_i8g's rotated int8 codes */
static int nan_host(const RadArgs* a, bool route) {
if (!a || a->n_t < (route ? 10 : 5)) return RAD_E_INVAL;
const int64_t n = rad_args_geti_or(a, "n", 0);
@@ -84,7 +96,8 @@ static int nan_host(const RadArgs* a, bool route) {
return RAD_E_DTYPE;
int64_t ra, la, rx, lx, ry, ly, rr = 0, lr = 0, rq = 0, lq = 0, rs = 0, ls = 0;
if (!hrows(A_, n, &ra, &la) || !hrows(X, n, &rx, &lx) || !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE;
if (route && (!hrows(R, n, &rr, &lr) || !hrows_as(Q, RAD_F8E4M3, n, &rq, &lq) ||
const bool i8 = route && Q->dtype == RAD_I8;
if (route && (!hrows(R, n, &rr, &lr) || !hrows_as(Q, i8 ? RAD_I8 : RAD_F8E4M3, n, &rq, &lq) ||
!hrows_as(S, RAD_F32, n / 128, &rs, &ls)))
return RAD_E_SHAPE;
if (ra < rx || ry < rx || (route && (rr < rx || rq < rx || rs < rx))) return RAD_E_SHAPE;
@@ -113,7 +126,19 @@ static int nan_host(const RadArgs* a, bool route) {
rrow[i] = f2b(((xv[(size_t)i] * sx) * wr[i]) * mult);
v[(size_t)i] = rb((xv[(size_t)i] * sx) * we[i]);
}
for (int64_t g = 0; g < n / 128; ++g) {
for (int64_t g = 0; i8 && g < n / 128; ++g) {
hfwht128(v.data() + g * 128);
float am = 0.0f;
for (int64_t i = g * 128; i < g * 128 + 128; ++i)
am = std::fmax(am, std::fabs(v[(size_t)i]));
const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f;
const float inv = 1.0f / sc;
srow[g] = sc;
for (int64_t i = g * 128; i < g * 128 + 128; ++i)
qrow[i] = (uint8_t)(int8_t)std::rint(
std::fmin(std::fmax(v[(size_t)i] * inv, -127.0f), 127.0f));
}
for (int64_t g = 0; !i8 && g < n / 128; ++g) {
float am = 0.0f;
for (int64_t i = g * 128; i < g * 128 + 128; ++i)
am = std::fmax(am, std::fabs(v[(size_t)i]));
+74 -32
View File
@@ -30,7 +30,7 @@ static RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
struct Case {
std::string name;
int hd, gqa, kvh;
bool fp8, causal, ragged, descale;
bool i8, causal, ragged, descale; /* i8: the int8 cache, codes and two f16 scales a slot */
int window;
std::vector<int> qlen, ctx; /* per sequence */
int missing_block = -1; /* sequence 0's block index to mark -1, or -1 */
@@ -43,24 +43,24 @@ struct Case {
};
using Fn = int (*)(const RadArgs*, RadStream);
static Fn pick(int hd, int gqa, bool fp8, bool ahead) {
static Fn pick(int hd, int gqa, bool i8, bool ahead) {
if (ahead) {
#define A(G) if (hd == 256 && gqa == G) return fp8 ? r4d_rad_attn_window_ahead_h256_gqa##G##_fp8 : r4d_rad_attn_window_ahead_h256_gqa##G##_bf16;
#define A(G) if (hd == 256 && gqa == G) return i8 ? r4d_rad_attn_window_ahead_h256_gqa##G##_i8 : r4d_rad_attn_window_ahead_h256_gqa##G##_bf16;
A(1) A(2) A(4) A(8)
#undef A
return nullptr;
}
#define P(H, G) if (hd == H && gqa == G) return fp8 ? r4d_rad_attn_window_h##H##_gqa##G##_fp8 : r4d_rad_attn_window_h##H##_gqa##G##_bf16;
#define P(H, G) if (hd == H && gqa == G) return i8 ? r4d_rad_attn_window_h##H##_gqa##G##_i8 : r4d_rad_attn_window_h##H##_gqa##G##_bf16;
P(128, 1) P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
P(512, 16)
#undef P
return nullptr;
}
static Fn pick_sink(int hd, int gqa, bool fp8) {
static Fn pick_sink(int hd, int gqa, bool i8) {
if (hd == 128 && gqa == 8)
return fp8 ? r4d_rad_attn_window_sink_h128_gqa8_fp8 : r4d_rad_attn_window_sink_h128_gqa8_bf16;
return i8 ? r4d_rad_attn_window_sink_h128_gqa8_i8 : r4d_rad_attn_window_sink_h128_gqa8_bf16;
if (hd == 128 && gqa == 16)
return fp8 ? r4d_rad_attn_window_sink_h128_gqa16_fp8 : r4d_rad_attn_window_sink_h128_gqa16_bf16;
return i8 ? r4d_rad_attn_window_sink_h128_gqa16_i8 : r4d_rad_attn_window_sink_h128_gqa16_bf16;
return nullptr;
}
@@ -81,17 +81,45 @@ static int run(const Case& c) {
* kernel that reads a masked key's V without guarding is caught */
const int64_t slot = 2 * HD, nel = (int64_t)nblocks * kvh * 16 * slot;
std::vector<float> kvf(nel);
std::vector<uint16_t> kvb(nel); std::vector<uint8_t> kv8(nel);
for (int64_t i = 0; i < nel; ++i) {
float v = nrm();
if (c.fp8) { kv8[i] = rad_f32_to_fp8e4m3(v * 4.f); kvf[i] = rad_fp8e4m3_to_f32(kv8[i]); }
else { kvb[i] = rad_f32_to_bf16(v); kvf[i] = rad_bf16_to_f32(kvb[i]); }
}
std::vector<uint16_t> kvb(nel);
for (int64_t i = 0; i < nel; ++i) { kvb[i] = rad_f32_to_bf16(nrm()); kvf[i] = rad_bf16_to_f32(kvb[i]); }
/* The int8 cache's bytes, as kv_store_i8 lays a slot out: K codes, V codes, K's f16 scale, V's.
* Each slot's two rows get their own magnitude, so a kernel that used one scale for another
* key's codes is caught; kvf holds code times scale, what the reference reads. */
const int64_t slot8 = 2 * HD + 4;
std::vector<uint8_t> kvi(c.i8 ? (size_t)((int64_t)nblocks * kvh * 16 * slot8) : 0);
if (c.i8)
for (int64_t r = 0; r < (int64_t)nblocks * kvh * 16; ++r)
for (int half = 0; half < 2; ++half) {
const float mag = 0.25f + (float)(rng() % 64) / 8.0f;
std::vector<float> v((size_t)HD);
float am = 0.0f;
for (int d = 0; d < HD; ++d) { v[(size_t)d] = nrm() * mag; am = std::max(am, std::fabs(v[(size_t)d])); }
const _Float16 s16 = (_Float16)(am / 127.0f);
const float sc = (float)s16;
for (int d = 0; d < HD; ++d) {
const float q = sc > 0.0f ? std::rint(v[(size_t)d] / sc) : 0.0f;
const int8_t code = (int8_t)std::fmin(std::fmax(q, -127.0f), 127.0f);
kvi[(size_t)(r * slot8 + half * HD + d)] = (uint8_t)code;
kvf[(size_t)(r * slot + half * HD + d)] = (float)code * sc;
}
std::memcpy(&kvi[(size_t)(r * slot8 + 2 * HD + 2 * half)], &s16, 2);
}
/* poison: every slot at or past a sequence's context in its last block, and every block no
* table names */
std::vector<char> named(nblocks, 0);
for (int s = 0; s < n_seq; ++s) for (int b = 0; b < maxb; ++b) if (bt[s * maxb + b] >= 0) named[bt[s * maxb + b]] = 1;
auto poison = [&](int64_t i) { if (c.fp8) { kv8[i] = 0x7f; } else { kvb[i] = 0x7fc0; } kvf[i] = NAN; };
/* An int8 slot is poisoned through its scales (an f16 NaN each), which every element of it is
* multiplied by. */
auto poison = [&](int64_t i) {
if (c.i8) {
const int64_t r = i / slot;
const uint16_t nan16 = 0x7e00;
std::memcpy(&kvi[(size_t)(r * slot8 + 2 * HD)], &nan16, 2);
std::memcpy(&kvi[(size_t)(r * slot8 + 2 * HD + 2)], &nan16, 2);
} else { kvb[i] = 0x7fc0; }
kvf[i] = NAN;
};
for (int blk = 0; blk < nblocks; ++blk) if (!named[blk]) for (int64_t i = 0; i < kvh * 16 * slot; ++i) poison((int64_t)blk * kvh * 16 * slot + i);
for (int s = 0; s < n_seq; ++s) {
const int last = (c.ctx[s] - 1) / 16, blk = bt[s * maxb + last];
@@ -116,7 +144,8 @@ static int run(const Case& c) {
for (int h = 0; h < qh; ++h) sinks[h] = h % 5 == 3 ? 6.f + nrm() : h % 7 == 6 ? -40.f : 1.5f * nrm();
RadTensor t[9];
t[0] = tens(qb.data(), RAD_BF16, {rows, qh * HD}); t[0].stride[0] = qcols;
t[1] = tens(c.fp8 ? (void*)kv8.data() : (void*)kvb.data(), c.fp8 ? RAD_F8E4M3 : RAD_BF16, {nblocks, kvh, 16, slot});
t[1] = c.i8 ? tens(kvi.data(), RAD_I8, {nblocks, kvh, 16, slot8})
: tens(kvb.data(), RAD_BF16, {nblocks, kvh, 16, slot});
t[2] = tens(bt.data(), RAD_I32, {n_seq, maxb});
t[3] = tens(su.data(), RAD_I32, {n_seq});
t[4] = c.descale ? tens(kd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{};
@@ -131,13 +160,13 @@ static int run(const Case& c) {
auto pf = [&](const char* k, double v) { RadParam x{}; x.key = k; x.kind = RAD_P_F64; x.dval = v; p.push_back(x); };
pi("q_len", qmax + 3); /* the band bound, above the step's max */
pi("head_dim", HD); pi("gqa", c.gqa); pi("block_size", 16); pi("causal", c.causal && !c.ahead); pi("window", c.window);
ps("q_dtype", "bf16"); ps("kv_dtype", c.fp8 ? "fp8_e4m3" : "bf16");
ps("q_dtype", "bf16"); ps("kv_dtype", c.i8 ? "i8" : "bf16");
const double scale = 1.0 / std::sqrt((double)HD) * 1.3; /* not the default: the param must be read */
pf("scale", scale); pi("n_head", qh); pi("max_seqs", n_seq);
if (c.max_ctx) pi("max_ctx", c.max_ctx);
RadArgs a{}; a.t = t; a.n_t = c.sink ? 9 : 8; a.p = p.data(); a.n_p = (int)p.size();
a.scratch = c.scratch ? sp : nullptr; a.scratch_bytes = c.scratch;
Fn fn = c.sink ? pick_sink(HD, c.gqa, c.fp8) : pick(HD, c.gqa, c.fp8, c.ahead);
Fn fn = c.sink ? pick_sink(HD, c.gqa, c.i8) : pick(HD, c.gqa, c.i8, c.ahead);
if (!fn) { std::printf("%-44s no entry point for this geometry\n", c.name.c_str()); return 1; }
const int g0 = emu_grids;
const int rc = fn(&a, nullptr);
@@ -210,14 +239,14 @@ int main(int argc, char** argv) {
{300, 70}, -1, 0, 0, 0, 1},
/* Gemma 4 sliding: h256 gqa2, causal, windowed; a ragged mixed step */
{"h256 gqa2 swa w64 ragged bf16", 256, 2, 2, false, true, true, false, 64, {1, 5, 40}, {200, 77, 140}},
{"h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}},
{"h256 gqa2 swa w64 ragged i8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}},
/* the real window, a context past it, a verify-sized query */
{"h256 gqa2 swa w1024 verify16", 256, 2, 1, false, true, false, false, 1024, {16}, {1100}},
/* split-KV decode: one row a sequence, long context, scratch present */
{"h256 gqa2 swa w1024 decode split", 256, 2, 2, false, true, true, false, 1024, {1, 1}, {1300, 40}, -1, 0, s256},
/* Gemma 4 full: h512, causal, no window, at the three TP ratios */
{"h512 gqa8 full ragged bf16", 512, 8, 1, false, true, true, false, 0, {2, 7}, {90, 33}},
{"h512 gqa8 full decode split fp8", 512, 8, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
{"h512 gqa8 full decode split i8", 512, 8, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
{"h512 gqa4 full verify16 split", 512, 4, 1, false, true, false, false, 0, {16}, {300}, -1, 1024, s512},
/* the serving case: max_ctx 262144 gives a decode step 64 splits, most of them empty */
{"h512 gqa4 full decode, 64 splits, short ctx", 512, 4, 1, false, true, false, false, 0, {4}, {37}, -1, 262144, s512},
@@ -226,7 +255,7 @@ int main(int argc, char** argv) {
/* Gemma 4 12B full at TP1: 16 q heads over its one kv head, one position a tile; the
* assistant's full layer is the same geometry at one row a sequence */
{"h512 gqa16 full ragged bf16", 512, 16, 1, false, true, true, false, 0, {3, 1, 9}, {50, 64, 9}},
{"h512 gqa16 full decode split fp8", 512, 16, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
{"h512 gqa16 full decode split i8", 512, 16, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
{"h512 gqa16 full verify16 split", 512, 16, 1, false, true, false, false, 0, {16}, {300}, -1, 1024, s512},
{"h512 gqa16 full decode, 3 seqs, 64 splits", 512, 16, 1, false, true, true, false, 0, {1, 1, 1}, {40, 90, 300}, -1, 262144, s512},
{"h512 gqa16 kvh2 noncausal missing-block", 512, 16, 2, false, false, true, false, 0, {4, 2}, {37, 20}, 1},
@@ -238,38 +267,51 @@ int main(int argc, char** argv) {
{"h256 gqa2 decode, split wanted, no scratch", 256, 2, 1, false, true, false, false, 0, {1}, {500}},
/* Prefill-shaped: the WMMA kernel (a 64-row query, or longer) */
{"wmma h512 gqa4 prefill 200 of 900", 512, 4, 1, false, true, false, false, 0, {200}, {900}, -1, 262144, s512, 0, 1},
{"wmma h512 gqa8 prefill fp8+descale", 512, 8, 1, true, true, false, true, 0, {130}, {130}, -1, 0, 0, 0, 1},
{"wmma h512 gqa8 prefill i8+descale", 512, 8, 1, true, true, false, true, 0, {130}, {130}, -1, 0, 0, 0, 1},
{"wmma h512 gqa2 kvh2 ragged + decode rows", 512, 2, 2, false, true, true, false, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
{"wmma h512 gqa1 noncausal", 512, 1, 1, false, false, false, false, 0, {64}, {100}, -1, 0, 0, 0, 1},
{"wmma h512 gqa16 prefill 200 of 900", 512, 16, 1, false, true, false, false, 0, {200}, {900}, -1, 262144, s512, 0, 1},
{"wmma h512 gqa16 ragged + decode rows fp8+descale", 512, 16, 1, true, true, true, true, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
{"wmma h512 gqa16 ragged + decode rows i8+descale", 512, 16, 1, true, true, true, true, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
{"wmma h256 gqa2 swa w1024 prefill 300 of 1500", 256, 2, 2, false, true, false, false, 1024, {300}, {1500}, -1, 0, 0, 0, 1},
{"wmma h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {100, 90}, {250, 90}, -1, 0, 0, 0, 1},
{"wmma h256 gqa2 swa w64 ragged i8+descale", 256, 2, 2, true, true, true, true, 64, {100, 90}, {250, 90}, -1, 0, 0, 0, 1},
{"wmma h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {80, 70}, {200, 70}, 3, 0, 0, 0, 1},
{"wmma h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {64}, {64}, -1, 0, 0, 512, 1},
{"wmma h256 gqa1 causal w5 fp8", 256, 1, 1, true, true, false, false, 5, {96}, {150}, -1, 0, 0, 0, 1},
{"wmma h256 gqa1 causal w5 i8", 256, 1, 1, true, true, false, false, 5, {96}, {150}, -1, 0, 0, 0, 1},
/* Gemma 4's picture runs, read again non-causally up to the run's end: 280 rows after a short
* prefix, after one the window cuts, q at the fused plane's pitch, a run's tail after a prefix hit */
{"wmma h256 gqa2 picture 280 of 300", 256, 2, 2, false, false, false, false, 1024, {280}, {300}, -1, 0, 0, 0, 1},
{"wmma h256 gqa2 picture 280 of 1500 fp8", 256, 2, 2, true, false, false, true, 1024, {280}, {1500}, -1, 0, 0, 0, 1},
{"wmma h256 gqa2 picture 280 of 1500 i8", 256, 2, 2, true, false, false, true, 1024, {280}, {1500}, -1, 0, 0, 0, 1},
{"wmma h256 gqa2 picture q-pitch slice", 256, 2, 2, false, false, false, false, 1024, {96}, {120}, -1, 0, 0, 512, 1},
{"h256 gqa2 picture tail split", 256, 2, 2, false, false, false, false, 1024, {10}, {1300}, -1, 0, s256, 0, 0},
/* a picture longer than the window, whose rows read every later key (attn_paged_ahead): the
* window is 20 here, the rows 70 to 100, and the scalar, split and WMMA kernels all take it */
{"h256 gqa2 ahead w20 verify-like", 256, 2, 2, false, false, false, false, 20, {6}, {70}, -1, 0, 0, 0, 0, true},
{"h256 gqa2 ahead w20 ragged fp8", 256, 2, 2, true, false, true, true, 20, {3, 1, 9}, {50, 64, 40}, -1, 0, 0, 0, 0, true},
{"h256 gqa2 ahead w20 ragged i8", 256, 2, 2, true, false, true, true, 20, {3, 1, 9}, {50, 64, 40}, -1, 0, 0, 0, 0, true},
{"h256 gqa1 ahead w5 missing-block", 256, 1, 1, false, false, true, false, 5, {4, 2}, {37, 20}, 1, 0, 0, 0, 0, true},
{"h256 gqa4 ahead w20 split", 256, 4, 1, false, false, false, false, 20, {5}, {300}, -1, 4096, s256, 0, 0, true},
{"wmma h256 gqa2 ahead w20 picture 100 of 100", 256, 2, 2, false, false, false, false, 20, {100}, {100}, -1, 0, 0, 0, 1, true},
{"wmma h256 gqa2 ahead w20 picture 90 of 300 fp8", 256, 2, 2, true, false, false, true, 20, {90}, {300}, -1, 0, 0, 0, 1, true},
{"wmma h256 gqa2 ahead w20 picture 90 of 300 i8", 256, 2, 2, true, false, false, true, 20, {90}, {300}, -1, 0, 0, 0, 1, true},
/* the int8 cache (kv_store_i8's slots) at Gemma 4 26B-A4B's two geometries: decode with the
* split, a ragged verify, prefill on the WMMA kernel with a missing block, the sliding
* window, a picture's non-causal rows and the open-ended window */
{"h512 gqa8 i8 decode split", 512, 8, 1, true, true, false, false, 0, {1}, {700}, -1, 4096, s512, 0, -1, false},
{"h512 gqa8 i8 verify ragged", 512, 8, 1, true, true, true, false, 0, {16, 3}, {300, 70}, -1, 0, 0, 0, 0, false},
{"wmma h512 gqa8 i8 prefill 130", 512, 8, 1, true, true, false, false, 0, {130}, {130}, -1, 0, 0, 0, 1, false},
{"wmma h512 gqa8 i8 ragged missing-block", 512, 8, 1, true, true, true, false, 0, {200, 70}, {900, 70}, 3, 0, 0, 0, 1, false},
{"h256 gqa2 i8 swa w64 ragged", 256, 2, 2, true, true, true, false, 64, {1, 5, 40}, {200, 77, 140}, -1, 0, 0, 0, -1, false},
{"h256 gqa2 i8 decode split", 256, 2, 2, true, true, false, false, 1024, {1}, {1300}, -1, 4096, s256, 0, -1, false},
{"wmma h256 gqa2 i8 swa w1024 prefill 300 of 1500", 256, 2, 2, true, true, false, false, 1024, {300}, {1500}, -1, 0, 0, 0, 1, false},
{"wmma h256 gqa2 i8 picture 280 of 1500", 256, 2, 2, true, false, false, false, 1024, {280}, {1500}, -1, 0, 0, 0, 1, false},
{"h256 gqa2 i8 ahead w20 ragged", 256, 2, 2, true, false, true, false, 20, {3, 1, 9}, {50, 64, 40}, -1, 0, 0, 0, 0, true},
{"wmma h256 gqa2 i8 ahead w20 picture 90 of 300", 256, 2, 2, true, false, false, false, 20, {90}, {300}, -1, 0, 0, 0, 1, true},
/* LiLiCorr's drafter (attn_paged_sink): 32 query heads over 2 KV heads at h128 (16 over 1 at
* TP 2), a block of 8 non-causal rows past the context, a 1024-token window; one sequence
* and a batch, unsplit and split, a bf16 and an fp8 cache */
* and a batch, unsplit and split, a bf16 and an int8 cache */
{"sink h128 gqa16 kvh2 block8 w1024", 128, 16, 2, false, false, false, false, 1024, {8}, {1500},
-1, 0, 0, 0, -1, false, true},
{"sink h128 gqa16 kvh1 block8 x3 split", 128, 16, 1, false, false, true, false, 1024, {8, 8, 8},
{900, 40, 2100}, -1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa16 kvh2 fp8+descale split", 128, 16, 2, true, false, false, true, 1024, {8}, {1300},
{"sink h128 gqa16 kvh2 i8+descale split", 128, 16, 2, true, false, false, true, 1024, {8}, {1300},
-1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa16 prefill-shaped stays scalar", 128, 16, 1, false, false, false, false, 1024, {96},
{400}, -1, 0, 0, 0, 0, false, true},
@@ -280,7 +322,7 @@ int main(int argc, char** argv) {
-1, 0, 0, 0, -1, false, true},
{"sink h128 gqa8 kvh1 block8 x3 split", 128, 8, 1, false, false, true, false, 1024, {8, 8, 8},
{900, 40, 2100}, -1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa8 kvh1 fp8+descale split", 128, 8, 1, true, false, false, true, 1024, {8}, {1300},
{"sink h128 gqa8 kvh1 i8+descale split", 128, 8, 1, true, false, false, true, 1024, {8}, {1300},
-1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa8 prefill-shaped stays scalar", 128, 8, 1, false, false, false, false, 1024, {96},
{400}, -1, 0, 0, 0, 0, false, true},
@@ -295,7 +337,7 @@ int main(int argc, char** argv) {
for (int it = 0; it < n; ++it) {
Case c;
c.hd = hds[rng() % 2]; c.gqa = gqas[rng() % 4]; c.kvh = 1 + rng() % 3;
c.fp8 = rng() % 2; c.causal = rng() % 4 != 0; c.ragged = rng() % 2; c.descale = rng() % 2;
c.i8 = rng() % 2; c.causal = rng() % 4 != 0; c.ragged = rng() % 2; c.descale = rng() % 2;
c.window = rng() % 3 == 0 ? 0 : 1 + rng() % 200;
const int ns = 1 + rng() % 4;
const bool pre = rng() % 3 == 0; /* prefill-shaped: the WMMA kernel */
@@ -311,7 +353,7 @@ int main(int argc, char** argv) {
if (rng() % 2) c.max_ctx = 512;
if (rng() % 5 == 0) c.missing_block = (int)(rng() % ((c.ctx[0] + 15) / 16));
c.name = "sweep " + std::to_string(it) + " h" + std::to_string(c.hd) + " g" + std::to_string(c.gqa) +
" kvh" + std::to_string(c.kvh) + (c.fp8 ? " fp8" : " bf16") + (c.causal ? " c" : " nc") +
" kvh" + std::to_string(c.kvh) + (c.i8 ? " i8" : " bf16") + (c.causal ? " c" : " nc") +
" w" + std::to_string(c.window) + (c.ragged ? " rag" : "");
const int g0 = emu_grids;
fails += run(c);
-320
View File
@@ -1,320 +0,0 @@
/* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT
* emulator. The form the rule picks at each shape (the decode form at one and two column tiles a
* wave and one to eight waves a block, the 16- and 32-row tiles) must match the legacy 16x64 tile,
* which serves an activation pitch off 16 bytes, bit for bit: the same fragments, the same mma
* chain per 128-K block and the same fold order. Ragged row counts, pitched rows and a K that
* leaves the decode form's last wave group partly idle are covered; the output's pitch padding
* stays untouched. The grouped row at GLM's MTP slices is held to a host restatement
* (grouped_cases). */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include "ref_host.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
extern const char* emu_last_kernel;
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = 2;
t.shape[0] = rows;
t.shape[1] = cols;
t.stride[0] = ld;
t.stride[1] = 1;
return t;
}
/* The grouped row at GLM's MTP slices (288 experts, top 8) below 384 routed rows -- the small-M
* form at gate_up, the expert-major form at down -- against a host restatement of the
* per-element sequence: per 128 of K in order, the
* 128-product sum of the emulated WMMA chain from zero, folded as raw * (activation scale *
* weight scale) and added. Dropped slots inside runs and past the routed rows, runs longer than an
* A tile, token and sorted rows, pointer tables over three slices a class. */
static int grouped_cases(int& cases) {
struct G {
const char* name;
int N, K;
bool sorted_a;
std::vector<int> live;
int tail;
const char* kernel;
};
const G all[] = {
{ "MTP gate_up, one token", 512, 4096, false, { 1, 1, 1, 1, 1, 1, 1, 1 }, 0,
"fp8_f32scale_small<512>" },
{ "MTP gate_up, runs past one tile", 512, 4096, false, { 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }, 2,
"fp8_f32scale_small<512>" },
{ "MTP down, six tokens", 4096, 256, true, { 3, 1, 10, 2, 1, 5, 1, 1, 17, 4 },
3, "(fp8_f32scale_experts<128, 4>)" },
};
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
int fails = 0;
std::mt19937 rng(77);
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_real_distribution<float> oct(-6.f, 6.f);
for (const G& g : all) {
const int E = 288, top = 8, N = g.N, K = g.K, kb = K / 128;
std::vector<int> runs(E, 0);
for (size_t i = 0; i < g.live.size(); ++i) runs[at[i]] = g.live[i];
int routed = 0;
for (int r : runs) routed += r;
const int T = (routed + g.tail + top - 1) / top * top;
const int Arows = g.sorted_a ? T : T / top, ap = K + 16, yp = N + 8;
std::vector<uint8_t> a((size_t)Arows * ap);
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
std::vector<float> as((size_t)Arows * kb);
for (auto& v : as) v = std::exp2(oct(rng));
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + runs[e];
for (int e = 0; e < E; ++e)
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
owner[r] = e;
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
}
std::vector<uint8_t> w[2];
std::vector<float> s[2];
std::vector<const void*> wt[2], st[2];
for (int q = 0; q < 2; ++q) {
w[q].resize((size_t)3 * N * K);
s[q].resize((size_t)3 * (N / 128) * kb);
for (auto& v : w[q]) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
for (auto& v : s[q]) v = std::exp2(oct(rng)) * 0.01f;
for (int x = 0; x < E / 2; ++x) {
wt[q].push_back(w[q].data() + (size_t)(x % 3) * N * K);
st[q].push_back(s[q].data() + (size_t)(x % 3) * (N / 128) * kb);
}
}
std::vector<uint16_t> ref((size_t)T * yp, 0x7777), got((size_t)T * yp, 0x7777);
for (int r = 0; r < T; ++r)
for (int n = 0; n < N; ++n) {
uint16_t& out = ref[(size_t)r * yp + n];
out = 0;
if (owner[r] < 0) continue;
const int e = owner[r], q = e & 1;
const bool rv = sorted[r] >= 0;
const int ar = !rv ? -1 : g.sorted_a ? r : sorted[r] / top;
const uint8_t* wr = (const uint8_t*)wt[q][(size_t)(e / 2)] + (size_t)n * K;
const float* sr = (const float*)st[q][(size_t)(e / 2)] + (size_t)(n / 128) * kb;
float acc = 0.f;
for (int b = 0; b < kb; ++b) {
float raw = 0.f;
if (rv)
for (int k = b * 128; k < b * 128 + 128; ++k)
raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + k]) *
rad_fp8e4m3_to_f32(wr[k]);
const float scale = rv ? as[(size_t)ar * kb + b] * sr[b] : 0.f;
const float t = raw * scale;
acc = acc + t;
}
uint32_t u;
std::memcpy(&u, &acc, 4);
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
auto ten3 = [](const void* const* tab, uint32_t dt, int64_t n0, int64_t n1, int64_t n2) {
RadTensor t{};
t.data = (void*)tab;
t.dtype = dt;
t.rank = 3;
t.shape[0] = n0;
t.shape[1] = n1;
t.shape[2] = n2;
t.stride[0] = 0;
t.stride[1] = n2;
t.stride[2] = 1;
return t;
};
RadTensor t[9] = { mat(a.data(), RAD_F8E4M3, Arows, K, ap),
mat(as.data(), RAD_F32, Arows, kb, kb),
ten3(wt[0].data(), RAD_F8E4M3, E / 2, N, K),
ten3(st[0].data(), RAD_F32, E / 2, N / 128, kb),
RadTensor{},
RadTensor{},
ten3(wt[1].data(), RAD_F8E4M3, E / 2, N, K),
ten3(st[1].data(), RAD_F32, E / 2, N / 128, kb),
mat(got.data(), RAD_BF16, T, N, yp) };
t[4].data = sorted.data();
t[4].dtype = RAD_I32;
t[4].rank = 1;
t[4].shape[0] = T;
t[4].stride[0] = 1;
t[5].data = offsets.data();
t[5].dtype = RAD_I32;
t[5].rank = 1;
t[5].shape[0] = E + 1;
t[5].stride[0] = 1;
RadParam p[10]{};
p[0] = { "M", RAD_P_INT, T / top };
p[1] = { "N", RAD_P_INT, N };
p[2] = { "K", RAD_P_INT, K };
p[3] = { "N_odd", RAD_P_INT, N };
p[4] = { "K_odd", RAD_P_INT, K };
p[5] = { "n_expert", RAD_P_INT, E };
p[6] = { "top_k", RAD_P_INT, top };
p[7] = { "group", RAD_P_INT, 128 };
p[8].key = "a_order";
p[8].kind = RAD_P_STR;
p[8].sval = g.sorted_a ? "sorted" : "token";
p[9].key = "dtype";
p[9].kind = RAD_P_STR;
p[9].sval = "fp8a8f32";
RadArgs ar{};
ar.t = t;
ar.n_t = 9;
ar.p = p;
ar.n_p = 10;
emu_last_kernel = "";
++cases;
const int rc = r4d_rad_moe_fp8_f32scale(&ar, nullptr);
size_t i = 0;
while (i < got.size() && got[i] == ref[i]) ++i;
int live = 0;
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
if (rc != RAD_OK || std::strcmp(emu_last_kernel, g.kernel) || i != got.size() ||
live < routed * N / 2) {
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu of %zu, %d live\n",
g.name, T, emu_last_kernel, g.kernel, rc, i, got.size(), live);
++fails;
}
}
return fails;
}
int main() {
std::mt19937 rng(31);
std::normal_distribution<float> nd(0.f, 1.f);
struct Shape {
int M, N, K;
const char* kernel;
};
const char* const dec1 = "(fp8_f32scale_decode<1, 1>)";
const char* const dec2 = "(fp8_f32scale_decode<1, 2>)";
const char* const rows = "fp8_f32scale_rows<R>";
// Decode at eight, four, two and one waves a block (K blocks 12/32, 4, 2, 1), at two column
// tiles a wave from 17 rows over N 1024 and 640; the 16-row tile, and the 32-row one at N 4096.
const Shape shapes[] = { { 1, 256, 512, dec1 }, { 6, 128, 1536, dec1 },
{ 17, 256, 512, dec1 }, { 48, 128, 512, dec1 },
{ 2, 128, 256, dec1 }, { 5, 256, 128, dec1 },
{ 3, 128, 4096, dec1 }, { 40, 1024, 512, dec2 },
{ 20, 640, 256, dec2 }, { 70, 128, 384, rows },
{ 130, 128, 256, rows }, { 33, 4096, 512, rows },
{ 70, 4096, 128, rows } };
int fails = 0, cases = 0;
for (const Shape& sh : shapes) {
const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, lp = K + 8, yp = N + 8;
std::vector<uint8_t> a((size_t)M * ap), al((size_t)M * lp), w((size_t)N * K);
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
for (int r = 0; r < M; ++r) std::memcpy(&al[(size_t)r * lp], &a[(size_t)r * ap], K);
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
// Scales over twelve octaves: K blocks of very different weight cancel, so a changed
// summation order shows through the bf16 output.
std::uniform_real_distribution<float> oct(-6.f, 6.f);
for (auto& v : as) v = std::exp2(oct(rng));
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
RadTensor t[7] = { mat(a.data(), RAD_F8E4M3, M, K, ap),
mat(as.data(), RAD_F32, M, kb, kb),
mat(w.data(), RAD_F8E4M3, N, K, K),
mat(ws.data(), RAD_F32, N / 128, kb, kb),
RadTensor{},
RadTensor{},
RadTensor{} };
RadParam p[5]{};
p[0] = { "M", RAD_P_INT, M };
p[1] = { "N", RAD_P_INT, N };
p[2] = { "K", RAD_P_INT, K };
p[3] = { "group", RAD_P_INT, 128 };
p[4].key = "dtype";
p[4].kind = RAD_P_STR;
p[4].sval = "fp8a8f32";
// The pitch off 16 bytes takes the legacy tile.
auto run = [&](bool legacy, std::vector<uint16_t>& y) {
y.assign((size_t)M * yp, 0x7777);
t[0] = legacy ? mat(al.data(), RAD_F8E4M3, M, K, lp)
: mat(a.data(), RAD_F8E4M3, M, K, ap);
t[4] = mat(y.data(), RAD_BF16, M, N, yp);
RadArgs ar{};
ar.t = t;
ar.n_t = 7;
ar.p = p;
ar.n_p = 5;
return r4d_rad_fp8_f32scale(&ar, nullptr);
};
std::vector<uint16_t> legacy, got;
++cases;
if (run(true, legacy) != RAD_OK || std::strcmp(emu_last_kernel, "fp8_f32scale")) {
std::printf("FAIL legacy M=%d N=%d K=%d ran %s\n", M, N, K, emu_last_kernel);
++fails;
continue;
}
int nonzero = 0;
for (int r = 0; r < M; ++r)
for (int c = 0; c < N; ++c) nonzero += legacy[(size_t)r * yp + c] != 0;
if (nonzero < M * N / 2) {
std::printf("FAIL legacy output mostly zero at M=%d\n", M);
++fails;
}
++cases;
const int rc = run(false, got);
if (rc != RAD_OK || std::strcmp(emu_last_kernel, sh.kernel) || got != legacy) {
size_t i = 0;
while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i;
std::printf("FAIL %s (want %s) at M=%d N=%d K=%d (rc %d, first word %zu)\n",
emu_last_kernel, sh.kernel, M, N, K, rc, i);
++fails;
}
}
fails += grouped_cases(cases);
{
/* A run of rows and a slice of columns give the bytes the whole product has there: GLM's
* MLA split by rows computes q_b and o over a rank's rows at full width, the head form
* over every row at a slice of the columns (or of K, as eight rank partials). */
const int M = 130, N = 1024, K = 512, kb = K / 128, r0 = 37, mr = 33, c0 = 256, nc = 256;
std::vector<uint8_t> a((size_t)M * K), w((size_t)N * K);
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
std::uniform_real_distribution<float> oct(-6.f, 6.f);
for (auto& v : as) v = std::exp2(oct(rng));
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
auto gemm = [&](int rows, int cols, int row0, int col0, std::vector<uint16_t>& y) {
y.assign((size_t)rows * cols, 0x7777);
RadTensor t[7] = { mat(a.data() + (size_t)row0 * K, RAD_F8E4M3, rows, K, K),
mat(as.data() + (size_t)row0 * kb, RAD_F32, rows, kb, kb),
mat(w.data() + (size_t)col0 * K, RAD_F8E4M3, cols, K, K),
mat(ws.data() + (size_t)(col0 / 128) * kb, RAD_F32, cols / 128, kb,
kb),
mat(y.data(), RAD_BF16, rows, cols, cols), RadTensor{}, RadTensor{} };
RadParam p[5]{};
p[0] = { "M", RAD_P_INT, rows };
p[1] = { "N", RAD_P_INT, cols };
p[2] = { "K", RAD_P_INT, K };
p[3] = { "group", RAD_P_INT, 128 };
p[4].key = "dtype";
p[4].kind = RAD_P_STR;
p[4].sval = "fp8a8f32";
RadArgs ar{};
ar.t = t;
ar.n_t = 7;
ar.p = p;
ar.n_p = 5;
return r4d_rad_fp8_f32scale(&ar, nullptr);
};
std::vector<uint16_t> whole, part;
++cases;
bool same = gemm(M, N, 0, 0, whole) == RAD_OK && gemm(mr, nc, r0, c0, part) == RAD_OK;
for (int r = 0; same && r < mr; ++r)
for (int c = 0; c < nc; ++c)
same = same && part[(size_t)r * nc + c] == whole[(size_t)(r0 + r) * N + c0 + c];
std::printf("%s rows %d..%d x columns %d..%d alone against the %dx%d product\n",
same ? "ok " : "FAIL", r0, r0 + mr, c0, c0 + nc, M, N);
fails += !same;
}
std::printf("%d case(s), %d failure(s)\n", cases, fails);
return fails ? 1 : 0;
}
-405
View File
@@ -1,405 +0,0 @@
/* tests/r4d_emu: the M2XFP4 x fp8 GEMMs (r4d_gemm_m2xfp4a8_decode.hip, r4d_gemm_m2xfp4a8_tiled.hip)
* on the host SIMT emulator. The container's m2xfp4 encoding (the paper's weight-side Sg-EM,
* arXiv 2601.19213 §4.4.2) is synthesised from random f32 weights by an in-test scalar quantiser
* implementing the spec: per group of 32 columns an E8M0 exponent with the adaptive bias (-1, 0, 1,
* drawn at random) folded into the stored byte, and a meta byte of four two-bit subgroup
* multipliers with k = 3 in heavy rotation; the codes are the e2m1 roundings of the exact
* dequantiser's inverse.
* The stored bytes are then built the way r4d_rad_relayout_m2xfp4 builds them (fragment-order
* codes, the meta plane appended in the exponents' [K/32][N] order), and both kernels run against
* an f64 CPU reference of the exact decode, at the FP8 WMMA's tolerance plus the table's accepted
* k = 3 rounding (rel_l2 < 4e-2, see run_cases). Cases cover both activation scale grids (per row,
* per (row, 128) with a zero block), M across the decode band's band edges (1, 8, 16, 40, 128) and
* the tiled row's, the one-fragment prefetch form (M <= 16), both K slabs (64 and 128), and a
* split-K launch on the decode kernel.
*
* The table itself is held to arithmetic first: every kM2xfp4Mag[d][k] cell must be the
* round-to-nearest-even e4m3 of e2m1mag * (1 + k/4) * 2^-d; the k = 0..2 rows must be exact while
* the product is a normal e4m3 value, and the k = 3 odd-mantissa entries must be the tie's even
* side (2.5, 5, 10 scaled by 2^-d). The unpack is held to the same arithmetic over every code at
* every (d, k).
*
* The declaration side (r4d_rows.cpp) is not in the emu build, so the two cfg readers it defines,
* which the units' plugin entries call, are stubbed in cfg_stub.cpp at their axis defaults (0 = the
* kernels' own rules), which is what an untuned call gets. This test calls the raw entries, so it
* runs no stub; everything it runs is the library's own code.
*/
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include "r4d.h"
#include "r4d_m2xfp4.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
extern const char* emu_last_kernel;
/* ------------------------------------------------------------------ arithmetic e4m3 / e2m1 */
/* Round-to-nearest-even e4m3 (OCP FP8, 1-4-3, bias 7, subnormals at 2^-9, 0x7F/0xFF NaN), the
* conversion the device tables and the WMMA's own converts use. */
static uint8_t rne_e4m3(double v) {
if (v == 0) return std::signbit(v) ? 0x80 : 0; /* the kernels keep a sign on zero */
const uint8_t sign = v < 0 ? 0x80 : 0;
double a = std::fabs(v);
if (a > 480) return (uint8_t)(sign | 0x7E);
int e = 0;
while (a >= 2.0) { a *= 0.5; ++e; }
while (a < 1.0) { a *= 2.0; --e; }
int m;
if (e < -6) { /* subnormal: 2^-9 steps of the value itself */
double q = std::fabs(v) * 512.0;
double fl = std::floor(q);
const double frac = q - fl;
int qi = (int)fl;
if (frac > 0.5 || (frac == 0.5 && (qi & 1))) ++qi;
if (qi >= 8) return (uint8_t)(sign | 0x08); /* up to min normal 2^-6 */
return (uint8_t)(sign | qi);
}
double q = (a - 1.0) * 8.0;
m = (int)q;
const double frac = q - m;
if (frac > 0.5 || (frac == 0.5 && (m & 1))) ++m;
if (m == 8) { m = 0; ++e; }
return (uint8_t)(sign | ((e + 7) << 3) | m);
}
static double e4m3_f64(uint8_t b) {
const double s = b & 0x80 ? -1.0 : 1.0;
const int e = (b >> 3) & 15, m = b & 7;
if (e == 0) return s * m * 0.001953125; /* 2^-9 steps */
return s * std::ldexp(1.0 + m / 8.0, e - 7);
}
/* The e2m1 magnitudes, and the quantiser's RNE code for a magnitude against them (ties to the even
* code, as the hardware's convert and the CPU reference agree). */
static const double kE2m1Mag[8] = { 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0 };
static uint8_t rne_e2m1(double v) {
double a = std::fabs(v);
int best = 0;
double bd = 1e300;
for (int i = 0; i < 8; ++i) {
const double d = std::fabs(a - kE2m1Mag[i]);
if (d < bd || (d == bd && !(best & 1))) { bd = d; best = i; }
}
return (uint8_t)(best | (v < 0 ? 8 : 0));
}
static double e2m1_f64(uint8_t code) {
return (code & 8 ? -1.0 : 1.0) * kE2m1Mag[code & 7];
}
/* ------------------------------------------------------------------ the table checks */
static int check_lut() {
int fails = 0;
for (int d = 0; d < 16; ++d)
for (int k = 0; k < 4; ++k)
for (int m = 0; m < 8; ++m) {
const uint8_t got = (uint8_t)((kM2xfp4Mag[d][k][m >> 2] >> (8 * (m & 3))) & 0xFF);
const double exact = kE2m1Mag[m] * (1.0 + k / 4.0) * std::ldexp(1.0, -d);
const uint8_t want = rne_e4m3(exact);
if (got != want) {
std::printf("FAIL lut d=%d k=%d mag=%d: %02x, want %02x (%.6g)\n", d, k, m,
got, want, exact);
++fails;
continue;
}
/* k = 0..2 exact wherever the product is a normal e4m3 value; k = 3 only the
* odd-mantissa magnitudes round, and to the tie's even side. */
if (e4m3_f64(got) != exact) {
const bool k3tie = k == 3 && (m == 3 || m == 5 || m == 7);
const double rounded = k3tie ? std::ldexp(m == 3 ? 2.5 : m == 5 ? 5.0 : 10.0, -d)
: exact;
if (k3tie && e4m3_f64(got) == rounded) continue;
/* the subnormal floor: like r4d_mxfp4.h's table one binade earlier, the 2^-9
* step rounds once the product falls in it; exactness is only claimed while
* the product is normal (>= 2^-6), and every k = 0..2 normal product is */
if (k <= 2 && exact >= 0.015625 && std::fabs(exact) > 0) {
std::printf("FAIL lut k=%d d=%d mag=%d: %02x decodes %.6g, want %.6g\n", k,
d, m, got, e4m3_f64(got), exact);
++fails;
}
}
}
/* and the k = 0 rows are r4d_mxfp4.h's, byte for byte (a memcmp would walk the [k] axis) */
static const unsigned kM0[16][2] = {
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u}, {0x2c282000u, 0x3c383430u},
{0x24201800u, 0x34302c28u}, {0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u}, {0x03020100u, 0x0c080604u},
{0x02010000u, 0x06040302u}, {0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u},
};
for (int d = 0; d < 16; ++d)
if (kM2xfp4Mag[d][0][0] != kM0[d][0] || kM2xfp4Mag[d][0][1] != kM0[d][1]) {
std::printf("FAIL lut: the k=0 row d=%d is not kMxfp4Mag\n", d);
++fails;
}
return fails;
}
/* The unpack against arithmetic, over every 16-bit pattern at both halves of a word and random
* words, at every (d, k). */
static int check_unpack() {
int fails = 0;
auto one = [&](uint32_t word, int d, int k) {
uint32_t lo = 0, hi = 0;
r4d_m2xfp4_unpack8(word, d, k, &lo, &hi);
for (int j = 0; j < 8; ++j) {
const uint8_t code = (uint8_t)((word >> (4 * j)) & 0xF);
const uint8_t got = (uint8_t)((j < 4 ? (lo >> (8 * j)) : (hi >> (8 * (j - 4)))) & 0xFF);
const double exact = e2m1_f64(code) * (1.0 + k / 4.0) * std::ldexp(1.0, -d);
const uint8_t want = rne_e4m3(exact);
if (got != want) {
if (fails < 12)
std::printf("FAIL unpack w=%08x d=%d k=%d j=%d: %02x, want %02x\n", word, d, k,
j, got, want);
++fails;
}
}
};
for (int d = 0; d < 16; ++d)
for (int k = 0; k < 4; ++k) {
for (uint32_t v = 0; v < 65536; ++v) {
one(v, d, k);
if (v < 256) { one(v << 24, d, k); one(v << 16, d, k); }
}
}
std::mt19937 rng(11);
for (int i = 0; i < 20000; ++i) one(rng(), (int)(rng() % 16), (int)(rng() % 4));
return fails;
}
/* ------------------------------------------------------------------ the GEMM cases */
struct Case {
const char* name;
const char* kernel; // the decode row's two forms, or the tiled row
int M, N, K;
bool ablk; // the activation scale per (row, 128 of K), with a zero block
int ks; // the decode launch's split (0 = the kernel's rule)
};
/* The in-test quantiser's planes for one weight [N][K]: codes (packed e2m1, element 2j in bits
* 0-3 of byte j), the per-(row, 32) exponents with the bias folded in, the meta bytes, and the
* f64 exact dequant the reference multiplies. */
struct M2Weight {
std::vector<uint8_t> codes; // [N][K/2]
std::vector<uint8_t> scale; // [N][K/32]
std::vector<uint8_t> meta; // [N][K/32]
std::vector<double> exact; // [N][K], the spec's decode
};
static M2Weight m2_quantise(const std::vector<float>& w, int N, int K, std::mt19937& rng) {
const int nblk = K / 32;
M2Weight m;
m.codes.assign((size_t)N * K / 2, 0);
m.scale.assign((size_t)N * nblk, 0);
m.meta.assign((size_t)N * nblk, 0);
m.exact.assign((size_t)N * K, 0.0);
std::uniform_int_distribution<int> bias(-1, 1);
for (int n = 0; n < N; ++n)
for (int b = 0; b < nblk; ++b) {
double absmax = 0.0;
for (int j = 0; j < 32; ++j) absmax = std::max(absmax, (double)std::fabs(w[(size_t)n * K + b * 32 + j]));
/* the exponent the six-magnitude grid needs, plus the adaptive bias, folded into the
* stored byte; a zero group keeps a small exponent, its codes all zero */
int e8 = absmax > 0 ? (int)std::ceil(std::log2(absmax / 6.0)) : -30;
e8 += bias(rng);
if (e8 < -30) e8 = -30;
if (e8 > 30) e8 = 30;
const uint8_t sbyte = (uint8_t)(e8 + 127);
uint8_t mbyte = 0;
for (int s = 0; s < 4; ++s) {
/* k = 3 in heavy rotation, the multiplier the rounding lives on */
const int k = (n + b + s * 3 + (int)(rng() % 2)) & 3;
mbyte |= k << (2 * s);
for (int j = 0; j < 8; ++j) {
const int col = b * 32 + s * 8 + j;
const double scale = std::ldexp(1.0 + k / 4.0, e8);
const uint8_t code = rne_e2m1(w[(size_t)n * K + col] / scale);
m.codes[(size_t)n * K / 2 + col / 2] |=
(uint8_t)(code << (4 * (col & 1)));
m.exact[(size_t)n * K + col] =
e2m1_f64(code) * std::ldexp(1.0, e8) * (1.0 + k / 4.0);
}
}
m.scale[(size_t)n * nblk + b] = sbyte;
m.meta[(size_t)n * nblk + b] = mbyte;
}
return m;
}
/* The stored weight, as r4d_rad_relayout_m2xfp4 writes it: codes in WMMA fragment order, then the
* meta plane in the exponents' [K/32][N] order, and the exponent plane and per-row reference
* beside them. */
static void m2_store(const M2Weight& m, int N, int K, std::vector<uint8_t>* wq,
std::vector<uint8_t>* ws, std::vector<uint8_t>* wm,
std::vector<uint8_t>* wref) {
const int nblk = K / 32;
wq->assign((size_t)N * K / 2 + (size_t)nblk * N, 0);
ws->assign((size_t)nblk * N, 0);
wm->assign((size_t)nblk * N, 0);
wref->assign(N, 0);
/* fragment order: slot = ((t * ks + ksi) * 32 + lh * 16 + r) * 4 + bin, element 2j in the low
* nibble of byte j (r4d_layout.cpp, mx_slot) */
const int ks16 = K / 16;
for (int n = 0; n < N; ++n) {
const int t = n / 16, r = n % 16;
uint8_t ref = 0;
for (int b = 0; b < nblk; ++b) {
const uint8_t s = m.scale[(size_t)n * nblk + b];
(*ws)[(size_t)b * N + n] = s;
(*wm)[(size_t)b * N + n] = m.meta[(size_t)n * nblk + b];
if (s > ref) ref = s;
}
(*wref)[n] = ref;
for (int k = 0; k < K; ++k) {
const uint8_t code = (uint8_t)((m.codes[(size_t)n * K / 2 + k / 2] >> (4 * (k & 1))) & 0xF);
const int ksi = k / 16, kin = k % 16;
const int lh = kin / 8, bin = (kin % 8) / 2;
const size_t idx = (size_t)((t * ks16 + ksi) * 32 + lh * 16 + r) * 4 + bin;
(*wq)[idx] |= (uint8_t)(code << (4 * (k & 1)));
}
}
}
static double bf16_f64(uint16_t h) {
const double s = h & 0x8000 ? -1.0 : 1.0;
const int e = (h >> 7) & 0xFF, m = h & 0x7F;
if (e == 0) return s * m * std::ldexp(1.0, -133); /* zero / bf16 subnormal */
return s * std::ldexp(1.0 + m / 128.0, e - 127);
}
static int run_cases() {
static const Case all[] = {
{ "decode1, K 128, rule split 16, per-row scales",
"(r4d_gemm_m2xfp4a8_decode1_kernel<128, 16, false, false>)", 1, 48, 128, false, 0 },
{ "decode1, K 64, split 4", "(r4d_gemm_m2xfp4a8_decode1_kernel<64, 4, false, false>)",
8, 16, 64, false, 4 },
{ "decode1, M 16, block scales", "(r4d_gemm_m2xfp4a8_decode1_kernel<128, 2, false, true>)",
16, 128, 256, true, 2 },
{ "decode, M 40 three fragments, odd K slab 192",
"(r4d_gemm_m2xfp4a8_decode_kernel<64, 1, 3, false, false>)", 40, 272, 192, false, 1 },
{ "decode, M 128 all fragments, block scales with a zero block",
"(r4d_gemm_m2xfp4a8_decode_kernel<128, 1, 8, false, true>)", 128, 128, 128, true, 1 },
{ "tiled, TN 2 just past the decode band, wide slab",
"(r4d_gemm_m2xfp4a8_tiled_kernel<2, 128, false>)", 129, 64, 128, false, 0 },
{ "tiled, TN 2, K 192 takes the 64 slab",
"(r4d_gemm_m2xfp4a8_tiled_kernel<2, 64, false>)", 300, 64, 192, false, 0 },
{ "tiled, TN 2, block scales", "(r4d_gemm_m2xfp4a8_tiled_kernel<2, 128, true>)",
256, 128, 128, true, 0 },
};
int fails = 0, cases = 0;
for (const Case& c : all) {
std::mt19937 rng(2000 + cases);
std::normal_distribution<double> nd(0.0, 1.0);
const int nkb = (c.K + 127) / 128;
/* random f32 weights -> the m2xfp4 planes */
std::vector<float> wf((size_t)c.N * c.K);
for (auto& v : wf) v = (float)(3.5 * nd(rng));
const M2Weight m = m2_quantise(wf, c.N, c.K, rng);
std::vector<uint8_t> wq, ws, wm, wref;
m2_store(m, c.N, c.K, &wq, &ws, &wm, &wref);
/* fp8 activations and their grid. The bytes are the quantised values; the grid's scale is
* applied once, where the kernel applies it: per row in the epilogue, per (row, 128) at
* each boundary -- the reference multiplies the same way. */
const int PA = c.ablk ? nkb : 1;
std::vector<uint8_t> a((size_t)c.M * c.K);
std::vector<float> as((size_t)c.M * PA);
for (int i = 0; i < c.M; ++i)
for (int q = 0; q < PA; ++q) {
/* block 1 of every fourth row is zero: the carried-scale path */
const float s = c.ablk && i % 4 == 1 && q == 1
? 0.0f
: std::ldexp(1.0f, (int)((rng() % 7) - 3)) * (1.0f + (rng() % 97) / 97.0f);
as[(size_t)i * PA + q] = s;
}
for (int i = 0; i < c.M; ++i)
for (int k = 0; k < c.K; ++k) {
const float block_scale = as[(size_t)i * PA + (c.ablk ? k / 128 : 0)];
const float v = (float)(nd(rng) * 2.0);
/* a zero-scale block's activation bytes are zero (the block-scaled quantisers
* produce nothing there), and the kernels carry the previous scale through */
a[(size_t)i * c.K + k] =
block_scale == 0.0f ? 0 : rne_e4m3(v / block_scale);
}
/* the f64 reference: the activation's bytes (times the block grid, when there is one) and
* the exact weight decode, which already carries its 2^(scale - 127) */
std::vector<double> reff((size_t)c.M * c.N);
for (int i = 0; i < c.M; ++i)
for (int n = 0; n < c.N; ++n) {
double acc = 0.0;
for (int k = 0; k < c.K; ++k)
acc += e4m3_f64(a[(size_t)i * c.K + k]) *
(c.ablk ? (double)as[(size_t)i * PA + k / 128] : 1.0) *
m.exact[(size_t)n * c.K + k];
if (!c.ablk) acc *= (double)as[(size_t)i];
reff[(size_t)i * c.N + n] = acc;
}
/* launch. The scratch is sized for the widest split the band's rule can pick (16), which
* the ABI's scratch hook bounds the same way; the arrival counters are the unit's own,
* one block per output buffer. */
std::vector<uint16_t> got((size_t)c.M * c.N, 0x7777);
const long wq_ptr = (long)(uintptr_t)wq.data();
const long scratch_bytes = 16l * c.M * c.N * (long)sizeof(float);
std::vector<float> scratch((size_t)(scratch_bytes / sizeof(float)), 0.0f);
emu_last_kernel = "";
++cases;
if (std::strstr(c.kernel, "tiled")) {
std::vector<uint8_t> at((size_t)r4d_m2xfp4a8_tile_a_bytes(c.M, c.K));
r4d_m2xfp4a8_tile_a((long)(uintptr_t)a.data(), (long)(uintptr_t)at.data(), c.M, c.K,
0, 0);
r4d_gemm_m2xfp4a8_tiled((long)(uintptr_t)at.data(), (long)(uintptr_t)as.data(),
wq_ptr, (long)(uintptr_t)ws.data(), (long)(uintptr_t)wm.data(),
(long)(uintptr_t)wref.data(), (long)(uintptr_t)got.data(),
c.M, c.K, c.N, 0, c.ablk ? 128 : 0, PA,
0, c.N, c.N);
} else {
r4d_gemm_m2xfp4a8_decode((long)(uintptr_t)a.data(), (long)(uintptr_t)as.data(),
wq_ptr, (long)(uintptr_t)ws.data(), (long)(uintptr_t)wm.data(),
(long)(uintptr_t)wref.data(), (long)(uintptr_t)got.data(),
c.M, c.K, c.N, c.ks, 0, 0, c.ablk ? 128 : 0, PA,
(long)(uintptr_t)scratch.data(), scratch_bytes, 0, 0, c.N,
c.N);
}
/* every launch lands on one form; a moved bound shows by name */
if (!std::strstr(emu_last_kernel, c.kernel)) {
std::printf("FAIL %s: ran %s, want %s\n", c.name,
emu_last_kernel ? emu_last_kernel : "(nothing)", c.kernel);
++fails;
continue;
}
double num = 0, den = 0, worst = 0;
for (size_t i = 0; i < reff.size(); ++i) {
const double d = bf16_f64(got[i]) - reff[i];
num += d * d;
den += reff[i] * reff[i];
worst = std::max(worst, std::fabs(d) / (std::fabs(reff[i]) + 1e-3));
}
const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num);
/* The FP8 WMMA's tolerance, plus the table's accepted k = 3 rounding: the mxfp4 row's
* 1e-2 with the ~1.2% whole-dot contribution a full rotation of k = 3 subgroups adds
* (a quarter of the weights at up to 2^-4.4 each). Cancellation can make a single
* element's relative error unbounded, so the aggregate is what is held. */
if (rel >= 4e-2) {
std::printf("FAIL %s: rel_l2 %.3e, worst %.3e\n", c.name, rel, worst);
++fails;
}
}
std::printf("%d gemm case(s), %d failure(s)\n", cases, fails);
return fails;
}
int main() {
int fails = check_lut();
fails += check_unpack();
fails += run_cases();
if (fails) std::printf("FAIL m2xfp4 (%d)\n", fails);
return fails ? 1 : 0;
}
-152
View File
@@ -8,11 +8,6 @@
* wrapping over the waves, the sort's bound and its refusal past it. Pitch padding, guards past
* every output and the gate's untouched rows show an overrun.
*
* swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 (both emulated): codes,
* scales and the optional bf16 product, at GLM's widths and ragged ones, with values far past the
* clamp, exactly on it and one bf16 step beyond, all-zero groups (scale 1), a gate so negative the
* sigmoid underflows, and NaN and infinite inputs.
*
* moe_scatter_inv and moe_gather_inv: the small sort's kernel with the inverse against itself
* without, and the inverse against the table the gather builds from `sorted`; then moe_gather's
* kernel reading that inverse against its self-scan (T <= 512) or the prepass's table (above), at
@@ -370,152 +365,6 @@ void router_scatter_cases(std::mt19937& rng, int& cases, int& fails) {
}
}
struct QuantShape {
int M, n;
float limit;
int mode; /* 0 random past the clamp, 1 clamp edges and zero groups, 2 NaN and inf */
bool y; /* the fused op also writes the bf16 product */
};
void swiglu_quant_cases(std::mt19937& rng, int& cases, int& fails) {
const QuantShape shapes[] = {
{ 1, 256, 10.f, 0, false }, { 8, 256, 10.f, 0, true }, { 48, 256, 10.f, 1, false },
{ 384, 256, 10.f, 0, false }, { 6, 1536, 10.f, 0, true }, { 3, 2048, 10.f, 1, true },
{ 5, 132, 7.f, 1, true }, { 7, 4, 10.f, 0, true }, { 9, 256, 10.f, 2, true },
{ 2, 260, 0.5f, 2, false },
};
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_int_distribution<int> ud(0, 15);
for (const QuantShape& sh : shapes) {
const int M = sh.M, n = sh.n, nkb = (n + 127) / 128;
const int gp = 2 * n + 6, yp = n + 5, qp = n + 8, sp = nkb + 3;
std::vector<uint16_t> gu((size_t)M * gp, f2b(-3.f));
const uint16_t lim = f2b(sh.limit), past = (uint16_t)(lim + 1);
for (int r = 0; r < M; ++r)
for (int c = 0; c < 2 * n; ++c) {
float v = nd(rng) * 6.f;
uint16_t h = f2b(v);
if (sh.mode == 1) {
const int pick = ud(rng);
if (pick == 0)
h = lim;
else if (pick == 1)
h = past;
else if (pick == 2)
h = (uint16_t)(lim | 0x8000u);
else if (pick == 3)
h = (uint16_t)(past | 0x8000u);
else if (pick == 4)
h = f2b(-200.f);
/* rows divisible by 3 hold an all-zero first group */
if (r % 3 == 0 && (c % n) < 128) h = (c < n && (c & 1)) ? f2b(-0.f) : 0;
} else if (sh.mode == 2) {
const int pick = ud(rng);
if (pick == 0)
h = 0x7fc0; /* NaN */
else if (pick == 1)
h = 0x7f80; /* +inf */
else if (pick == 2)
h = 0xff80; /* -inf */
}
gu[(size_t)r * gp + c] = h;
}
RadTensor t[4]{};
t[0].data = gu.data();
t[0].dtype = RAD_BF16;
t[0].rank = 2;
t[0].shape[0] = M;
t[0].shape[1] = 2 * n;
t[0].stride[0] = gp;
t[0].stride[1] = 1;
auto mat = [](RadTensor& x, uint32_t dt, int r, int c, int pitch) {
x.dtype = dt;
x.rank = 2;
x.shape[0] = r;
x.shape[1] = c;
x.stride[0] = pitch;
x.stride[1] = 1;
};
RadParam pc[4]{};
pc[0] = { "M", RAD_P_INT, M };
pc[1] = { "n", RAD_P_INT, n };
pc[2].key = "limit";
pc[2].kind = RAD_P_F64;
pc[2].dval = sh.limit;
pc[3].key = "dtype";
pc[3].kind = RAD_P_STR;
pc[3].sval = "bf16";
RadParam pq[4]{};
pq[0] = { "M", RAD_P_INT, M };
pq[1] = { "n", RAD_P_INT, n };
pq[2] = { "group", RAD_P_INT, 128 };
pq[3].key = "dtype";
pq[3].kind = RAD_P_STR;
pq[3].sval = "bf16";
RadParam pf[5]{};
pf[0] = pc[0];
pf[1] = pc[1];
pf[2] = pc[2];
pf[3] = pq[2];
pf[4] = pc[3];
std::vector<uint16_t> y_ref((size_t)M * yp, 0x7e57), y((size_t)M * yp, 0x7e57);
std::vector<uint8_t> q_ref((size_t)M * qp, 0xa5), q((size_t)M * qp, 0xa5);
std::vector<float> s_ref((size_t)M * sp, -7.25f), s((size_t)M * sp, -7.25f);
RadTensor tc[2] = { t[0], {} };
mat(tc[1], RAD_BF16, M, n, yp);
tc[1].data = y_ref.data();
RadArgs ac{};
ac.t = tc;
ac.n_t = 2;
ac.p = pc;
ac.n_p = 4;
RadTensor tq[3] = { tc[1], {}, {} };
mat(tq[1], RAD_F8E4M3, M, n, qp);
tq[1].data = q_ref.data();
mat(tq[2], RAD_F32, M, nkb, sp);
tq[2].data = s_ref.data();
RadArgs aq{};
aq.t = tq;
aq.n_t = 3;
aq.p = pq;
aq.n_p = 4;
++cases;
if (r4d_rad_swiglu_clamped(&ac, nullptr) != RAD_OK ||
r4d_rad_quant_act_fp8(&aq, nullptr) != RAD_OK) {
std::printf("FAIL swiglu_clamped + quant_act_fp8 launch M=%d n=%d\n", M, n);
++fails;
continue;
}
RadTensor tf[4] = { t[0], {}, {}, {} };
mat(tf[1], RAD_F8E4M3, M, n, qp);
tf[1].data = q.data();
mat(tf[2], RAD_F32, M, nkb, sp);
tf[2].data = s.data();
mat(tf[3], RAD_BF16, M, n, yp);
tf[3].data = sh.y ? y.data() : nullptr;
RadArgs af{};
af.t = tf;
af.n_t = 4;
af.p = pf;
af.n_p = 5;
const int rc = r4d_rad_swiglu_clamped_quant_fp8(&af, nullptr);
int bad = 0;
bad += q != q_ref;
bad += std::memcmp(s.data(), s_ref.data(), s.size() * 4) != 0;
if (sh.y)
bad += y != y_ref;
else
for (uint16_t v : y) bad += v != 0x7e57;
if (rc != RAD_OK || bad) {
std::printf("FAIL swiglu_clamped_quant_fp8 at M=%d n=%d limit %g mode %d%s (rc %d, %d "
"mismatching outputs)\n",
M, n, (double)sh.limit, sh.mode, sh.y ? " with bf16" : "", rc, bad);
++fails;
}
}
}
struct GatherShape {
int M, n, nl, base;
bool f32w; /* GLM's f32 routing weights, else bf16 */
@@ -607,7 +456,6 @@ int main() {
std::mt19937 rng(23);
int fails = 0, cases = 0;
router_scatter_cases(rng, cases, fails);
swiglu_quant_cases(rng, cases, fails);
gather_inverse_cases(rng, cases, fails);
std::printf("%d case(s), %d failure(s)\n", cases, fails);
return fails ? 1 : 0;
-422
View File
@@ -1,422 +0,0 @@
/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. The form the
* rule picks at each case (named per case, so a moved bound shows) must match a host restatement
* of the per-element sequence bit for bit: per 128 of K in order, per 32-wide group a fresh
* 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * E8M0
* scale with two roundings and an add. Away from GLM's slices the expert-major forms (K 256 and a
* longer K) and the row groups; at GLM's TP4 down slice the GLM prefill form, at its TP8 gate_up
* 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. 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"
#include "r4d_mxfp4.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
extern const char* emu_last_kernel;
/* The bytewise arithmetic decode, the reference of r4d_mxfp4_unpack8_exact: per byte, magnitudes
* from 2 map to (m + 12) * 4, 0 and 1 to 0 and 48, the sign to bit 7; then the low and high
* nibbles' bytes interleave in k order. */
static uint32_t fp4x4_ref(uint32_t n) {
const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u;
const uint32_t mask = (flag << 5) - (flag >> 3);
return (((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) |
((n & 0x08080808u) << 4);
}
static int check_decode() {
int fails = 0;
auto one = [&](uint32_t w) {
const uint32_t low = fp4x4_ref(w & 0x0f0f0f0fu), high = fp4x4_ref((w >> 4) & 0x0f0f0f0fu);
const uint32_t lo_ref = __byte_perm(low, high, 0x5140),
hi_ref = __byte_perm(low, high, 0x7362);
uint32_t lo, hi, tlo, thi;
r4d_mxfp4_unpack8_exact(w, &lo, &hi);
r4d_mxfp4_unpack8(w, 0, &tlo, &thi);
if (lo != lo_ref || hi != hi_ref || lo != tlo || hi != thi) {
if (fails < 4)
std::printf("FAIL decode of %08x: table %08x %08x, arithmetic %08x %08x\n", w, hi,
lo, hi_ref, lo_ref);
++fails;
}
/* each byte against the e2m1 value it encodes */
for (int e = 0; e < 8; ++e) {
const uint32_t c = (w >> (4 * e)) & 15u;
static const float mag[8] = { 0.f, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f };
const float want = (c & 8u ? -1.f : 1.f) * mag[c & 7u];
const uint8_t b = (uint8_t)(((e < 4 ? lo : hi) >> (8 * (e & 3))) & 0xffu);
if (rad_fp8e4m3_to_f32(b) != want || (b & 0x80u) != (c & 8u ? 0x80u : 0u)) {
if (fails < 4) std::printf("FAIL code %x at element %d -> byte %02x\n", c, e, b);
++fails;
}
}
};
/* the bytes decode independently: every pair of adjacent bytes exhaustively, at both halves
* of the word, and random words over all four */
for (uint32_t v = 0; v < 65536; ++v) {
one(v);
one(v << 16);
one(v << 8);
}
std::mt19937 rng(7);
for (int i = 0; i < 200000; ++i) one((uint32_t)rng());
return fails;
}
struct Case {
const char* name;
int N, K, N_odd, K_odd, parts, top;
bool sorted_a, tables, exceptional;
std::vector<int> runs;
int tail; // dropped slots past the routed rows
const char* kernel; // the form the rule picks
};
/* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative
* default NaN, and an add of two NaNs returns its first operand, whose side the compiler may swap;
* the card generates the positive quiet NaN, so a NaN's sign carries no information here. */
static bool nan16(uint16_t v) { return (v & 0x7f80u) == 0x7f80u && (v & 0x7fu); }
static size_t first_diff(const std::vector<uint16_t>& a, const std::vector<uint16_t>& b) {
for (size_t i = 0; i < a.size() && i < b.size(); ++i)
if (a[i] != b[i] && !(nan16(a[i]) && nan16(b[i]))) return i;
return a.size() == b.size() ? a.size() : std::min(a.size(), b.size());
}
static RadTensor ten(void* p, uint32_t dt, std::vector<int64_t> shape,
std::vector<int64_t> stride) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = (uint32_t)shape.size();
for (size_t i = 0; i < shape.size(); ++i) {
t.shape[i] = shape[i];
t.stride[i] = stride[i];
}
return t;
}
/* GLM's 288 experts: the given runs at experts spread over both classes, every other one empty. */
static std::vector<int> glm_runs(std::vector<int> live) {
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
std::vector<int> runs(288, 0);
for (size_t i = 0; i < live.size() && i < sizeof at / sizeof at[0]; ++i) runs[at[i]] = live[i];
return runs;
}
int main() {
int fails = check_decode(), cases = 1;
if (fails) std::printf("FAIL table decode: %d mismatches\n", fails);
const std::vector<int> runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 };
const char* const staged = "(moe_mxfp4_expert_staged_kernel<128, 4>)";
const char* const expert = "(moe_mxfp4_expert_kernel<4, 256>)";
const char* const groups = "moe_mxfp4_fp8_kernel";
const Case all[] = {
{ "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6,
groups },
{ "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9,
2, groups },
{ "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4, groups },
{ "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4, groups },
{ "expert-major, K 384",
64,
384,
64,
384,
2,
2,
false,
true,
false,
{ 0, 1, 15, 16, 17, 30 },
3,
expert },
{ "expert-major, K 256, exceptional codes",
64,
256,
32,
256,
1,
2,
true,
false,
true,
{ 1, 0, 3, 15, 1 },
2,
staged },
{ "expert-major, K 512:384, runs past 64 rows, N under a block",
96,
512,
96,
384,
1,
2,
false,
false,
false,
{ 32, 33, 31, 96, 128, 129, 0, 2 },
9,
expert },
{ "expert-major, K 256:128, column tiles cut",
192,
256,
128,
128,
2,
4,
true,
true,
true,
{ 64, 63, 65, 1, 0, 127, 17 },
5,
staged },
{ "GLM TP4 down, the GLM prefill form",
4096,
512,
4096,
512,
1,
8,
true,
true,
true,
glm_runs({ 63, 96, 1, 130, 32, 31, 33, 64, 65 }),
13,
"moe_mxfp4_prefill_kernel" },
{ "GLM TP8 gate_up, P64 BM32 BN64 K256",
512,
4096,
512,
4096,
2,
8,
false,
true,
false,
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,
4096,
256,
1,
8,
true,
true,
true,
glm_runs({ 900, 801, 779, 700, 700, 581, 600, 600, 63, 1 }),
40,
"(moe_mxfp4_p64_kernel<32, 64, 128, 4, true>)" },
};
for (const Case& c : all) {
const int E = (int)c.runs.size(), NK = std::max(c.K, c.K_odd), OUT = std::max(c.N, c.N_odd);
int routed = 0;
for (int r : c.runs) routed += r;
const int T = (routed + c.tail + c.top - 1) / c.top * c.top;
// An odd pitch on every other case: the LDS output's 16-byte stores need an aligned row.
const int Arows = c.sorted_a ? T : T / c.top, ap = NK + 16, asp = NK / 128 + 1,
yp = OUT + ((&c - all) % 2 ? 5 : 8);
std::mt19937 rng(1000 + cases);
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_real_distribution<float> oct(-6.f, 6.f);
std::vector<uint8_t> a((size_t)Arows * ap);
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng) * 2.f);
std::vector<float> as((size_t)Arows * asp);
for (auto& v : as) v = std::exp2(oct(rng));
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + c.runs[e];
for (int e = 0; e < E; ++e)
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
owner[r] = e;
// A dropped slot about every eleventh row, the first rows of some runs included.
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
}
/* Stacked planes hold every expert; a pointer table names one of at most three slices a
* class, so GLM's 288 experts stay small. */
const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd },
nexp[2] = { (E + 1) / 2, E / 2 };
std::vector<uint8_t> w[2], s[2];
std::vector<const void*> wt[2], st[2];
std::vector<std::vector<float>> wf[2];
int slices[2];
for (int q = 0; q < 2; ++q) {
slices[q] = c.tables ? std::min(nexp[q], 3) : nexp[q];
w[q].resize((size_t)slices[q] * n[q] * k[q] / 2);
s[q].resize((size_t)slices[q] * n[q] * k[q] / 32);
for (auto& v : w[q]) v = (uint8_t)rng();
static const uint8_t special[] = { 0, 255, 1, 254, 127 };
for (size_t i = 0; i < s[q].size(); ++i)
s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5]
: (uint8_t)(118 + rng() % 16);
for (int x = 0; x < nexp[q]; ++x) {
wt[q].push_back(w[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 2);
st[q].push_back(s[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 32);
}
/* each slice's codes as the E4M3 values the table decode gives */
for (int x = 0; x < slices[q]; ++x) {
std::vector<float> f((size_t)n[q] * k[q]);
const uint8_t* src = w[q].data() + (size_t)x * n[q] * k[q] / 2;
for (size_t i = 0; i < f.size(); ++i) {
uint32_t lo, hi;
r4d_mxfp4_unpack8_exact((src[i / 2] >> (4 * (i & 1))) & 15u, &lo, &hi);
f[i] = rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu));
}
wf[q].push_back(std::move(f));
}
}
auto plane = [&](int q, bool scale) {
const int64_t cols = scale ? k[q] / 32 : k[q];
void* p = c.tables ? (void*)(scale ? st[q].data() : wt[q].data())
: (void*)(scale ? s[q].data() : w[q].data());
RadTensor t = ten(p, scale ? RAD_E8M0 : RAD_FP4E2M1, { nexp[q], n[q], cols },
{ c.tables ? 0 : (int64_t)n[q] * cols, cols, 1 });
return t;
};
/* the per-element sequence, on the host */
std::vector<float> af(a.size());
for (size_t i = 0; i < a.size(); ++i) af[i] = rad_fp8e4m3_to_f32(a[i]);
std::vector<uint16_t> ref((size_t)T * yp, 0x7777);
for (int r = 0; r < T; ++r)
for (int col = 0; col < OUT; ++col) {
uint16_t& out = ref[(size_t)r * yp + col];
out = 0;
if (owner[r] < 0 || sorted[r] < 0) continue;
const int e = owner[r], q = e & 1, ar = c.sorted_a ? r : sorted[r] / c.top;
const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw;
const bool valid = within < cw;
const int wn = (col / pw) * cw + within;
const float* wr = wf[q][(size_t)((e / 2) % slices[q])].data() + (size_t)wn * k[q];
const uint8_t* sr = (const uint8_t*)st[q][(size_t)(e / 2)] + (size_t)wn * k[q] / 32;
const float* arow = af.data() + (size_t)ar * ap;
float total = 0.f;
for (int kb = 0; kb < k[q]; kb += 128)
for (int g = 0; g < 4; ++g) {
float raw = 0.f;
for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk)
raw += arow[kk] * (valid ? wr[kk] : 0.f);
const uint32_t x = valid ? sr[kb / 32 + g] : 127u;
uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u;
float scale;
std::memcpy(&scale, &bits, 4);
float t = raw * as[(size_t)ar * asp + kb / 128];
t = t * scale;
total = total + t;
}
uint32_t u;
std::memcpy(&u, &total, 4);
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >>
16); // f32_to_bf16, r4d_common.h
}
int live = 0;
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
if (live < T * OUT / 3) {
std::printf("FAIL %s: output mostly zero\n", c.name);
++fails;
}
RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }),
ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }),
plane(0, false),
plane(0, true),
ten(sorted.data(), RAD_I32, { T }, { 1 }),
ten(offsets.data(), RAD_I32, { E + 1 }, { 1 }),
plane(1, false),
plane(1, true),
RadTensor{} };
RadParam p[11]{};
auto pi = [](const char* key, long long v) {
RadParam x{};
x.key = key;
x.kind = RAD_P_INT;
x.ival = v;
return x;
};
auto ps = [](const char* key, const char* v) {
RadParam x{};
x.key = key;
x.kind = RAD_P_STR;
x.sval = v;
return x;
};
p[0] = pi("M", T / c.top);
p[1] = pi("N", c.N);
p[2] = pi("K", c.K);
p[3] = pi("N_odd", c.N_odd);
p[4] = pi("K_odd", c.K_odd);
p[5] = pi("n_expert", E);
p[6] = pi("top_k", c.top);
p[7] = pi("parts", c.parts);
p[8] = pi("group", 128);
p[9] = ps("a_order", c.sorted_a ? "sorted" : "token");
p[10] = ps("dtype", "mxfp4a8");
std::vector<uint16_t> got((size_t)T * yp, 0x7777);
t[8] = ten(got.data(), RAD_BF16, { T, OUT }, { yp, 1 });
RadArgs ar{};
ar.t = t;
ar.n_t = 9;
ar.p = p;
ar.n_p = 11;
emu_last_kernel = "";
++cases;
const int rc = r4d_rad_moe_mxfp4(&ar, nullptr);
const size_t i = first_diff(got, ref);
if (rc != RAD_OK || std::strcmp(emu_last_kernel, c.kernel) || i != got.size()) {
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu (row %zu col %zu: "
"%04x, want %04x)\n",
c.name, T, emu_last_kernel, c.kernel, rc, i, i / yp, i % yp,
i < got.size() ? got[i] : 0, i < ref.size() ? ref[i] : 0);
++fails;
}
}
std::printf("%d case(s), %d failure(s)\n", cases, fails);
return fails ? 1 : 0;
}
+27 -8
View File
@@ -131,8 +131,9 @@ static int case_nan(int M, int n, int pad, int extra_rows) {
/* norm_add_norm_route: norm_add_norm, then the router's row r = norm(x) * w_r * mult and the experts'
* E4M3 codes q and scales qs of norm(x) * w_e. `zero_group`: w_e zero over the second 128 columns,
* so that group's amax is 0 and its scale the quantiser's 1. */
static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = false) {
* so that group's amax is 0 and its scale the quantiser's 1. `i8` is norm_add_norm_route_i8g: q is
* the int8 codes of each group rotated by the 128-wide Hadamard (rmsnorm_had_quant_i8g's). */
static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = false, bool i8 = false) {
const int ld = n + pad, R = M + extra_rows, G = n / 128, ldq = n + pad, lds = G + 3;
const float eps = 1e-6f, mult = 1.0f / std::sqrt((float)n);
auto a = randb((size_t)R * ld, 3.f), x = randb((size_t)R * ld, 1.f), y0 = randb((size_t)R * ld, 1.f);
@@ -150,12 +151,12 @@ static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = f
rows(xd.data(), RAD_BF16, M, n, ld), vec(wy.data(), RAD_F32, n),
rows(yd.data(), RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n),
rows(rd.data(), RAD_BF16, M, n, ld), vec(we.data(), RAD_F32, n),
rows(qd.data(), RAD_F8E4M3, M, n, ldq), rows(sd.data(), RAD_F32, M, G, lds) };
rows(qd.data(), i8 ? RAD_I8 : RAD_F8E4M3, M, n, ldq), rows(sd.data(), RAD_F32, M, G, lds) };
RadParam p[6]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n};
p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
p[4].key = "mult"; p[4].kind = RAD_P_F64; p[4].dval = mult; p[5] = {"group", RAD_P_INT, 128};
RadArgs ar{}; ar.t = t; ar.n_t = 10; ar.p = p; ar.n_p = 6;
if (r4d_rad_norm_add_norm_route_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm_route: device launch failed"); return 1; }
if ((i8 ? r4d_rad_norm_add_norm_route_i8g_bf16(&ar, nullptr) : r4d_rad_norm_add_norm_route_bf16(&ar, nullptr)) != RAD_OK) { std::puts("norm_add_norm_route: device launch failed"); return 1; }
t[2].data = xh.data(); t[4].data = yh.data(); t[6].data = rh.data(); t[8].data = qh.data(); t[9].data = sh.data();
if (host_norm_add_norm_route(&ar) != RAD_OK) { std::puts("norm_add_norm_route: host launch failed"); return 1; }
Tally tx, ty, tr;
@@ -186,12 +187,26 @@ static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = f
cmp(&rd[o], cr.data(), &rh[o], n, tr);
for (int g = 0; g < G; ++g) { /* rmsnorm_quant_fp8 */
float h[128], am = 0.0f;
for (int j = 0; j < 128; ++j) { h[j] = rb((xv[(size_t)(g * 128 + j)] * f) * we[(size_t)(g * 128 + j)]); am = std::fmax(am, std::fabs(h[j])); }
const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f, inv = 1.0f / sc;
for (int j = 0; j < 128; ++j) h[j] = rb((xv[(size_t)(g * 128 + j)] * f) * we[(size_t)(g * 128 + j)]);
if (i8) /* had_quant_act_i8g's rotation */
for (int st = 1; st < 128; st <<= 1)
for (int j = 0; j < 128; ++j)
if ((j & st) == 0) { const float u = h[j], w = h[j + st]; h[j] = u + w; h[j + st] = u - w; }
for (int j = 0; j < 128; ++j) am = std::fmax(am, std::fabs(h[j]));
const float top = i8 ? 127.0f : 448.0f;
const float sc = am > 0.0f ? am * (1.0f / top) : 1.0f, inv = 1.0f / sc;
s_chain += sd[os + g] != sc;
if (zero_group && g == 1 && sd[os + g] != 1.0f) ++s_chain;
for (int j = 0; j < 128; ++j) {
const int i = g * 128 + j;
if (i8) {
/* vs the host arm: a norm factor an ulp apart moves a few bf16 inputs by one, which
* moves a rotated value and the group's amax each by less than a code step */
q_chain += (int8_t)qd[oq + i] != (int8_t)std::rint(std::fmin(std::fmax(h[j] * inv, -127.0f), 127.0f));
const double dv = std::fabs((double)(int8_t)qd[oq + i] * sd[os + g] - (double)(int8_t)qh[oq + i] * sh[os + g]);
if (dv > 2.0 * (double)sc + 1e-30) ++q_host_bad;
continue;
}
q_chain += qd[oq + i] != rad_f32_to_fp8e4m3(std::fmin(std::fmax(h[j] * inv, -448.0f), 448.0f));
/* vs the host arm: one code step is at most an eighth of its value, so at most an
* eighth of the group's amax; a scale an ulp off moves less */
@@ -203,8 +218,8 @@ static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = f
}
const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tr.chain_bad == 0 && q_chain == 0 && s_chain == 0 &&
tx.host_bad == 0 && ty.host_bad == 0 && tr.host_bad == 0 && q_host_bad == 0 && touched == 0;
std::printf("norm_add_norm_route M %3d n %4d pitch %4d%s: vs chain x %ld y %ld r %ld q %ld scale %ld differ; vs host "
"arm %ld/%ld/%ld differ, %ld codes past a step; padding touched %ld -> %s\n", M, n, ld,
std::printf("norm_add_norm_route%s M %3d n %4d pitch %4d%s: vs chain x %ld y %ld r %ld q %ld scale %ld differ; vs host "
"arm %ld/%ld/%ld differ, %ld codes past a step; padding touched %ld -> %s\n", i8 ? "_i8g" : "", M, n, ld,
zero_group ? " (a zero group)" : "", tx.chain_bad, ty.chain_bad, tr.chain_bad, q_chain, s_chain,
tx.host_diff, ty.host_diff, tr.host_diff, q_host_bad, touched, ok ? "PASS" : "FAIL");
return ok ? 0 : 1;
@@ -280,6 +295,10 @@ int main() {
for (int M : Ms) fails += case_route(M, 2816, M % 2 ? 64 : 0, 2);
fails += case_route(2, 3072, 0, 1) + case_route(2, 3200, 16, 1) + case_route(3, 128, 8, 1);
fails += case_route(2, 6144, 0, 0) + case_route(4, 2816, 0, 1, true);
/* the rotated int8 form at the same widths */
for (int M : { 1, 5 }) fails += case_route(M, 2816, M % 2 ? 64 : 0, 2, false, true);
fails += case_route(2, 3200, 16, 1, false, true) + case_route(3, 128, 8, 1, false, true);
fails += case_route(2, 6144, 0, 0, false, true) + case_route(4, 2816, 0, 1, true, true);
std::printf("norm joins: %d failure(s)\n", fails);
return fails ? 1 : 0;
}
+4 -2
View File
@@ -267,8 +267,10 @@ int run(Fix& f, Form form) {
: "qsa_select_kernel";
const char* fn = kFormName[form];
if (rc != RAD_OK) { std::printf("FAIL %-48s %-6s launch returned %d\n", f.name.c_str(), fn, rc); return 1; }
/* The launch site names the template, `kernel<Signed>`: the name is what precedes it. */
const std::string ran(emu_last_kernel, std::strcspn(emu_last_kernel, "<"));
/* The launch site names the template in parentheses, `(kernel<Signed, form>)`: the name is
* what stands between the parenthesis and the arguments. */
const char* const kname = emu_last_kernel + (emu_last_kernel[0] == '(' ? 1 : 0);
const std::string ran(kname, std::strcspn(kname, "<"));
if (ran != expect || grids != (split ? 2 : 1)) {
std::printf("FAIL %-48s %-6s ran %s in %d grid(s), expected %s in %d\n", f.name.c_str(), fn,
emu_last_kernel, grids, expect, split ? 2 : 1);