Merge hugypufy/radiance m2xfp: M2XFP4 weights (upstream PR #203)

The M2XFP4 encoding (e2m1 codes, e8m0 per-32 scales, a u8 per-subgroup metadata plane, learned
Givens rotations): libref and libavx kernels, libr4d HIP kernels, the packer and the tests, as on
the branch (8 commits on 9eaf10d, radiance 1.11.0). Taken for Qwen3.8-27B-DFLASH2-PARO-M2XFP4,
the container used for testing and optimisation from now on; merged without conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-10-23 23:09:18 +02:00
commit d3609e585d
68 files changed
+4847 -193

No files matched your search

+27 -4
View File
@@ -429,8 +429,11 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_
${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip
${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip
${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip
${R4D_DIR}/r4d_dsa.hip)
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa)
${R4D_DIR}/r4d_dsa.hip
# The M2XFP4 GEMMs: their cfg readers are inline in r4d_args.h, so the units link
# without the declaration side and the test runs what an untuned install runs.
${R4D_DIR}/r4d_gemm_m2xfp4a8_decode.hip ${R4D_DIR}/r4d_gemm_m2xfp4a8_tiled.hip)
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa m2xfp4)
set(R4D_EMU_BUILT OFF)
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
# No fiber switch for this ISA.
@@ -469,7 +472,7 @@ else()
${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp
${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp
${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp)
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp)
get_filename_component(stem ${src} NAME_WE)
set(lang "")
if(src MATCHES "\\.hip$")
@@ -506,7 +509,7 @@ else()
endif()
endif()
if(R4D_EMU_BUILT)
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa)
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa m2xfp4)
add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t})
endforeach()
# The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel,
@@ -518,6 +521,7 @@ if(R4D_EMU_BUILT)
set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick
r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse
r4d_emu_dsa
r4d_emu_m2xfp4
PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT})
# The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can
# load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within
@@ -640,6 +644,25 @@ if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_moe.rkb)
ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};OMP_WAIT_POLICY=passive")
endif()
# The M2XFP4 rows over the 27B-trunk fixture set (see the root CMakeLists): the four max-tok
# passes replayed together, covering the m2xfp4a8 decode row's whole M ladder. Scoped to
# libref:libr4d: the m2 arm of the other host library is that library's own to bring up.
if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_m2xfp4_m128.rkb)
add_test(NAME kbench_m2xfp4
COMMAND rad-kbench --home ${RAD_PLUGIN_OUT} --kernels libref:libr4d --max-cases 1
--no-ref --strict --coverage ${RAD_KBENCH_ROWS}
--fixture ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m1.rkb
--fixture ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m8.rkb
--fixture ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m16.rkb
--fixture ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m128.rkb)
set_tests_properties(kbench_m2xfp4 PROPERTIES
LABELS "${RAD_KBENCH_LABELS}"
TIMEOUT 1800
RESOURCE_LOCK kbench_memory
PROCESSORS 4
ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};OMP_WAIT_POLICY=passive")
endif()
# libref against its own recordings, both fixtures, at tolerance zero: it is deterministic and
# machine-independent by construction, so any difference is a change in libref (or in the draw)
# that would otherwise become the next recording's target. This is the oracle's regression test.
+336
View File
@@ -0,0 +1,336 @@
/* quant_m2xfp_test.cpp -- the `m2xfp4` quantiser: the metadata plane's pack, the scheme's own
* decode, and the search's quality against plain OCP MXFP4.
*
* Every case quantises through the quantiser's hooks as rad-convert does and reads the weight
* back through enc_decode_rows, which asks libquant's decode hook for the scheme -- so the
* round-trip checks the planes a reader that never saw the quantiser would unpack, against a
* scalar decode of the spec's equation written out here by hand: the nibble stream, the E8M0
* bytes and the metadata's low-bits-first subgroups are each unpacked independently. The quality
* cases compare weight MSE against `rtn codes=fp4_e2m1 group=32 scale=e8m0`, the OCP MXFP4 the
* scheme refines: the search's candidate set contains that quantiser's choice for every group,
* so it can only tie or win, and the wins are where the format earns its half bit. The wide case
* holds the same property one bias wider: wide=1 sweeps b in {-2, ..., 2} and can only tie or
* beat adaptive, its planes decoding bit for bit as the equation does.
*/
#include "quant_fixture.h"
#include <dlfcn.h>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
using namespace rad;
using namespace qfix;
namespace {
constexpr const char* kName = "blk.2.attn_q.weight";
/* The thread count of the OpenMP runtime the plugin loaded, so a run can be repeated at another. */
void threads(int n) {
using Fn = void (*)(int);
if (Fn f = (Fn)dlsym(RTLD_DEFAULT, "omp_set_num_threads")) f(n);
}
bool same_planes(const Quantised& a, const Quantised& b) {
if (a.enc.n_planes != b.enc.n_planes) return false;
for (int i = 0; i < a.enc.n_planes; ++i)
if (a.planes[(size_t)i] != b.planes[(size_t)i]) return false;
return true;
}
/* The spec's decode, by hand: element j's nibble (element 2j in the low bits of byte j/2), its
* group's E8M0 byte and metadata byte, subgroup s = (j%32)/8 in bits [2s, 2s+2). */
std::vector<float> ref_decode(const Quantised& q, int64_t rows, int64_t cols) {
const int64_t ng = (cols + 31) / 32;
const int64_t crow = (4 * cols + 7) / 8;
const uint8_t* codes = q.planes[0].data();
const uint8_t* scale = q.planes[1].data();
const uint8_t* meta = q.planes[2].data();
static const float mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
std::vector<float> out((size_t)(rows * cols));
for (int64_t r = 0; r < rows; ++r)
for (int64_t j = 0; j < cols; ++j) {
const uint8_t nib = (codes[(size_t)(r * crow + (j >> 1))] >> ((j & 1) * 4)) & 15;
const uint8_t sb = scale[(size_t)(r * ng + (j >> 5))];
const uint8_t mb = meta[(size_t)(r * ng + (j >> 5))];
const int k = (mb >> (2 * ((j & 31) >> 3))) & 3;
const float s = std::ldexp(1.0f, (int)sb - 127);
out[(size_t)(r * cols + j)] =
(nib & 8 ? -mag[nib & 7] : mag[nib & 7]) * s * (1.0f + 0.25f * (float)k);
}
return out;
}
double mse(const std::vector<float>& w, const std::vector<float>& d) {
double e = 0.0;
for (size_t i = 0; i < w.size(); ++i) {
const double x = (double)w[i] - d[i];
e += x * x;
}
return e / (double)w.size();
}
/* Lognormal magnitudes, exp(sigma z) with z standard normal from a splitmix draw: the heavy tail
* that makes one shared exponent a group a poor fit. */
std::vector<float> lognormal(int64_t n, uint64_t seed, double sigma) {
uint64_t z = seed;
auto next = [&]() {
z += 0x9E3779B97F4A7C15ull;
uint64_t x = z;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
return (double)((x ^ (x >> 31)) >> 11) / 9007199254740992.0;
};
std::vector<float> w((size_t)n);
for (int64_t i = 0; i < n; i += 2) {
const double u1 = next(), u2 = next();
const double r = std::sqrt(-2.0 * std::log(u1 + 1e-12));
const double a = sigma * r * std::cos(6.283185307179586 * u2);
const double b = sigma * r * std::sin(6.283185307179586 * u2);
w[(size_t)i] = (float)std::exp(a);
if (i + 1 < n) w[(size_t)i + 1] = (float)std::exp(b);
}
return w;
}
/* Every group's amax on a different fraction of an octave, 2^u with u uniform in [0, 1): the
* amax / 2^E0 quotient swept over [4, 8), where the OCP floor's choice of exponent is worst and
* the bias search has most to say. */
std::vector<float> octave_groups(int64_t rows, int64_t cols, uint64_t seed) {
const std::vector<float> z = draw(rows * cols, seed, 4.0f);
std::vector<float> w(z);
const int64_t ng = (cols + 31) / 32;
for (int64_t r = 0; r < rows; ++r)
for (int64_t g = 0; g < ng; ++g) {
uint64_t h = seed ^ ((uint64_t)r * 0x9E3779B97F4A7C15ull) ^ (uint64_t)g;
h = (h ^ (h >> 30)) * 0xBF58476D1CE4E5B9ull;
h = (h ^ (h >> 27)) * 0x94D049BB133111EBull;
const double u = (double)(h >> 11) / 9007199254740992.0;
const float lift = (float)std::exp2(u); /* an octave, [1, 2) */
for (int64_t c = g * 32; c < (g + 1) * 32 && c < cols; ++c)
w[(size_t)(r * cols + c)] = z[(size_t)(r * cols + c)] * lift;
}
return w;
}
/* The fixture's quantise takes its options by reference, so each case builds its own. */
void m2xfp_opts(Opts& o, int adaptive, int wide = 0) {
o.i("adaptive", adaptive);
if (wide) o.i("wide", wide);
}
void mxfp4_opts(Opts& o) { o.s("codes", "fp4_e2m1").i("group", 32).s("scale", "e8m0"); }
} // namespace
TEST(m2xfp4_is_three_planes_and_round_trips_through_its_own_decode) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
const RadQuantWeight w0 = weight_of("x", 8, 64);
RadEncoding e{};
REQUIRE_EQ(q->encoding(nullptr, 0, &w0, &e), RAD_OK);
CHECK_EQ(std::string(e.scheme), std::string("m2xfp4"));
CHECK_EQ(e.transform[0], 0);
REQUIRE_EQ(e.n_planes, 3);
CHECK_EQ(std::string(e.plane[0].role), std::string("codes"));
CHECK_EQ((int)e.plane[0].dtype, (int)RAD_FP4E2M1);
CHECK_EQ(e.plane[0].block[0], 1);
CHECK_EQ(e.plane[0].block[1], 1);
CHECK_EQ(std::string(e.plane[1].role), std::string("scale"));
CHECK_EQ((int)e.plane[1].dtype, (int)RAD_E8M0);
CHECK_EQ(e.plane[1].block[1], 32);
CHECK_EQ(std::string(e.plane[2].role), std::string("meta"));
CHECK_EQ((int)e.plane[2].dtype, (int)RAD_U8);
CHECK_EQ(e.plane[2].block[1], 32);
CHECK_EQ(q->row_block(nullptr, 0, &w0), (int64_t)1);
/* a rank-1 norm is declined, like every quantiser's, not an error */
RadQuantWeight v{};
v.name = "x";
v.rank = 1;
v.shape[0] = 64;
v.rows = 1;
v.cols = 64;
CHECK_EQ(q->encoding(nullptr, 0, &v, &e), RAD_E_UNSUPPORTED);
/* whole groups, a short final group, and an odd column count's nibble tail: the decode the
* core reaches through the hook must equal the equation by hand, bit for bit. */
for (int64_t C : { 256, 112, 101 }) {
const int64_t R = 8;
const std::vector<float> w = draw(R * C, 41, 8.0f);
Opts o_adapt;
m2xfp_opts(o_adapt, 1);
Quantised a = quantise(q, o_adapt, kName, R, C, w);
REQUIRE_EQ(a.status, RAD_OK);
const std::vector<float> d = decode(a, R, C);
REQUIRE_EQ(d.size(), w.size());
const std::vector<float> r = ref_decode(a, R, C);
for (size_t i = 0; i < d.size(); ++i) CHECK_EQ(d[(size_t)i], r[(size_t)i]);
/* rows from the middle, as the oracle and rad-convert ask for them */
std::vector<const void*> pd;
for (auto& p : a.planes) pd.push_back(p.data());
EncodedView v;
std::string why;
enc_view(a.enc, R, C, pd.data(), &v);
std::vector<float> part((size_t)(3 * C));
REQUIRE_EQ(enc_decode_rows(v, 3, 3, part.data(), &why), RAD_OK);
for (int64_t i = 0; i < 3 * C; ++i) CHECK_EQ(part[(size_t)i], d[(size_t)(3 * C + i)]);
}
}
TEST(m2xfp4_packs_the_metadata_low_bits_first_and_zero_groups_like_mxfp4) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
/* One row, one group, its subgroups built to choose k = 0, 0, 1, 3 (the zeros keep k 0, the
* 1.9s want 5/4 of the scale, the 5.5s want 7/4 of it). The group is built so the bias tie
* is exact: every subgroup's best dequantised value is the same under b = -1 and b = 0
* (0, 1.0, 1.875 and 5.25 -- the e2m1 grid is scale-invariant until a candidate saturates),
* so the biases tie at 0.5082 and the search keeps the first of {-1, 0, 1}, the paper's
* argmin. The exponent byte is 126, and the same codes under it decode to what b = 0's 127
* would: the tie moves the byte, never the weight. */
std::vector<float> w(32);
for (int j = 0; j < 8; ++j) w[(size_t)j] = 0.02f;
for (int j = 8; j < 16; ++j) w[(size_t)j] = 1.0f;
for (int j = 16; j < 24; ++j) w[(size_t)j] = 1.9f;
for (int j = 24; j < 32; ++j) w[(size_t)j] = 5.5f;
Opts o_adapt;
m2xfp_opts(o_adapt, 1);
Quantised a = quantise(q, o_adapt, kName, 1, 32, w);
REQUIRE_EQ(a.status, RAD_OK);
REQUIRE_EQ(a.planes[1].size(), (size_t)1);
REQUIRE_EQ(a.planes[2].size(), (size_t)1);
CHECK_EQ((int)a.planes[1][0], 126);
CHECK_EQ((int)a.planes[2][0], (0 << 0) | (0 << 2) | (1 << 4) | (3 << 6));
const std::vector<float> d = decode(a, 1, 32);
REQUIRE_EQ(d.size(), w.size());
const std::vector<float> r = ref_decode(a, 1, 32);
for (int j = 0; j < 32; ++j) CHECK_EQ(d[(size_t)j], r[(size_t)j]);
/* A zero group: byte 0 and zero codes, the MXFP4 grid's exponent-floor clamp, not the
* reference's clamped-amax exponent -- the same decode either way, radiance's bytes win. */
const std::vector<float> z(2 * 64, 0.0f);
Opts o_zero, o_mx;
m2xfp_opts(o_zero, 1);
mxfp4_opts(o_mx);
Quantised m = quantise(q, o_zero, kName, 2, 64, z);
Quantised g = quantise(quantizer("rtn"), o_mx, kName, 2, 64, z);
REQUIRE_EQ(m.status, RAD_OK);
REQUIRE_EQ(g.status, RAD_OK);
CHECK(m.planes[1] == g.planes[1]);
int bad = 0;
for (uint8_t c : m.planes[0]) bad += c != 0;
for (uint8_t b : m.planes[2]) bad += b != 0;
CHECK_EQ(bad, 0);
}
TEST(m2xfp4_stores_the_same_bytes_one_band_or_four_threads_at_a_time) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
const int64_t R = 32, C = 256;
const std::vector<float> w = draw(R * C, 43, 6.0f);
Opts o_adapt;
m2xfp_opts(o_adapt, 1);
Quantised whole = quantise(q, o_adapt, kName, R, C, w);
threads(1);
Quantised one = quantise(q, o_adapt, kName, R, C, w, nullptr, 4);
threads(4);
Quantised four = quantise(q, o_adapt, kName, R, C, w, nullptr, 4);
REQUIRE_EQ(whole.status, RAD_OK);
REQUIRE_EQ(one.status, RAD_OK);
REQUIRE_EQ(four.status, RAD_OK);
/* its output is a file: the bands and the thread count may not move a byte */
CHECK(same_planes(whole, one));
CHECK(same_planes(whole, four));
}
TEST(m2xfp4_beats_ocp_mxfp4_on_heavy_tails_and_its_search_never_hurts) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
const int64_t R = 64, C = 256;
struct Case { const char* what; std::vector<float> w; };
std::vector<Case> cases;
cases.push_back({ "lognormal", lognormal(R * C, 51, 1.5) });
cases.push_back({ "octave", octave_groups(R, C, 52) });
Opts o_mx, o_pin, o_adapt;
mxfp4_opts(o_mx);
m2xfp_opts(o_pin, 0);
m2xfp_opts(o_adapt, 1);
for (const Case& c : cases) {
Quantised base = quantise(quantizer("rtn"), o_mx, kName, R, C, c.w);
Quantised off = quantise(q, o_pin, kName, R, C, c.w);
Quantised on = quantise(q, o_adapt, kName, R, C, c.w);
REQUIRE_EQ(base.status, RAD_OK);
REQUIRE_EQ(off.status, RAD_OK);
REQUIRE_EQ(on.status, RAD_OK);
const double eb = mse(c.w, decode(base, R, C));
const double e0 = mse(c.w, decode(off, R, C));
const double e1 = mse(c.w, decode(on, R, C));
std::fprintf(stderr, " %s: MXFP4 %.5f, m2xfp4 bias-pinned %.5f, adaptive %.5f "
"(%.1f%% of MXFP4)\n", c.what, eb, e0, e1, 100.0 * e1 / eb);
/* every group's candidates contain plain MXFP4's choice, and the adaptive set contains
* the pinned one, so each stage can only tie or improve */
CHECK(e0 <= eb);
CHECK(e1 <= e0);
CHECK(e1 < eb * 0.98);
}
}
TEST(m2xfp4_wide_bias_sweep_contains_the_narrow_one_and_round_trips_bit_exact) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
const int64_t R = 64, C = 256;
struct Case { const char* what; std::vector<float> w; };
std::vector<Case> cases;
cases.push_back({ "lognormal", lognormal(R * C, 61, 2.0) });
cases.push_back({ "octave", octave_groups(R, C, 62) });
Opts o_pin, o_adapt, o_wide;
m2xfp_opts(o_pin, 0);
m2xfp_opts(o_adapt, 1);
m2xfp_opts(o_wide, 1, 1);
for (const Case& c : cases) {
Quantised off = quantise(q, o_pin, kName, R, C, c.w);
Quantised on = quantise(q, o_adapt, kName, R, C, c.w);
Quantised wide = quantise(q, o_wide, kName, R, C, c.w);
REQUIRE_EQ(off.status, RAD_OK);
REQUIRE_EQ(on.status, RAD_OK);
REQUIRE_EQ(wide.status, RAD_OK);
const double e0 = mse(c.w, decode(off, R, C));
const double e1 = mse(c.w, decode(on, R, C));
const double e2 = mse(c.w, decode(wide, R, C));
std::fprintf(stderr, " %s: pinned %.5f, adaptive %.5f, wide %.5f (%.1f%% of "
"pinned)\n", c.what, e0, e1, e2, 100.0 * e2 / e0);
/* wide's candidates {-2, ..., 2} contain adaptive's {-1, 0, 1}, which contain the
* pinned b = 0, so each stage can only tie or improve */
CHECK(e1 <= e0);
CHECK(e2 <= e1);
/* the wide path's planes decode bit for bit as the equation unpacked by hand */
const std::vector<float> d = decode(wide, R, C);
const std::vector<float> r = ref_decode(wide, R, C);
REQUIRE_EQ(d.size(), c.w.size());
for (size_t i = 0; i < d.size(); ++i) CHECK_EQ(d[i], r[i]);
}
/* wide=1 at adaptive=0 is the pinned quantiser, plane for plane: there is no bias to widen,
* so the option may not move a byte */
const std::vector<float> w = draw(R * C, 55, 8.0f);
Opts o_pin_wide;
m2xfp_opts(o_pin_wide, 0, 1);
Quantised off = quantise(q, o_pin, kName, R, C, w);
Quantised both = quantise(q, o_pin_wide, kName, R, C, w);
REQUIRE_EQ(off.status, RAD_OK);
REQUIRE_EQ(both.status, RAD_OK);
CHECK(same_planes(off, both));
}
RAD_TEST_MAIN()
+2
View File
@@ -169,7 +169,9 @@ inline void __threadfence() {}
template <typename T> inline T emu_atomic_fetch_add(T* p, T v) { const T o = *p; *p = o + v; return o; }
/* The device allocations a unit makes for itself (counter blocks): host memory here. */
inline hipError_t hipMalloc(void** p, size_t n) { *p = std::calloc(n ? n : 1, 1); return *p ? 0 : 2; }
inline hipError_t hipMemset(void* p, int v, size_t n) { std::memset(p, v, n); return 0; }
inline hipError_t hipMemsetAsync(void* p, int v, size_t n, hipStream_t) { std::memset(p, v, n); return 0; }
inline hipError_t hipFree(void* p) { std::free(p); return 0; }
struct alignas(8) uint2 { unsigned x, y; };
struct alignas(16) uint4 { unsigned x, y, z, w; };
+415
View File
@@ -0,0 +1,415 @@
/* 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,
* cycling) 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 (rel_l2 < 1e-2). 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
* are stubbed here at their axis defaults (0 = the kernels' own rules), which is what an untuned
* call gets. Everything else 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;
/* The cfg readers the entry points call are inline in r4d_args.h, beside their tables, so this
* test links the units without the declaration side and runs what an untuned install runs. */
/* ------------------------------------------------------------------ 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)));
}
}
}
/* A bf16 as the kernels round it (f32_to_bf16, r4d_common.h's RNE). */
static uint16_t bf16_rne(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
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 nblk = c.K / 32, 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<uint16_t> ref((size_t)c.M * c.N);
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;
ref[(size_t)i * c.N + n] = bf16_rne((float)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. */
std::vector<uint16_t> got((size_t)c.M * c.N, 0x7777);
const long wq_ptr = (long)(uintptr_t)wq.data();
/* launch. The scratch is the widest split the band's rule can pick (16) plus the arrival
* counters, which ride its tail: R4D_M2D_MAX_N / (DWN*16) unsigned = 1152 B. */
const long scratch_bytes = 16l * c.M * c.N * (long)sizeof(float) + 1152;
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;
}
/* the FP8 WMMA's tolerance */
double num = 0, den = 0, worst = 0;
for (size_t i = 0; i < ref.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;
}