oracle: a four-bit expert's E4M3 scale view decodes, on the grid its dtype names

The scale view of a w4nl64a8h, w4nl32a8h or w5nl64a8h expert is the E4M3 scale
plus its fixed second level, which enc_selection_logical could not read, and
libref described the weight scale on block fp8's grid for every dtype. So
RADIANCE_OP_ORACLE left every moe_gemm_q and moe_gemm_q_mod4 issue at those
formats NOT CHECKED. Both fixed; libref's arithmetic and serving unchanged.
This commit is contained in:
keptn42 authored and StillDeadcode committed 2026-10-05 12:52:44 +02:00
1 parent fe899bf60c
commit 4252353bc2
8 files changed
+391 -15

No files matched your search

+50
View File
@@ -346,6 +346,56 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
}
return RAD_OK;
}
/* A SCALE AND THE LEVELS ABOVE IT, without the codes: each first-level scale times every level
* that covers it. It is what a kernel that takes its scales as an operand of their own reads
* where the encoding states them in two levels -- the scale view of a w4nl64a8h expert, an
* E4M3 scale a (row, 64 of K) under one fixed f32 -- and the product is the scale the
* reference multiplies, where the first level on its own is that scale off by the second. One
* element a first-level scale, in that plane's extents. A level has to cover whole
* first-level blocks -- the whole weight, or a block a multiple of the first's -- or a scale
* would straddle two of its elements and have no one product. */
if (n_sel >= 2 && !std::strcmp(e.plane[sel[0]].role, "scale")) {
bool chain = true;
for (int k = 0; k < n_sel && chain; ++k) {
const RadEncPlane& p = e.plane[sel[k]];
chain = p.kind == RAD_PLANE_TILED && rad_enc_role_in_chain(p.role, "scale") &&
(k == 0 || std::strcmp(p.role, "scale") != 0);
}
if (chain) {
const RadEncPlane& p0 = e.plane[sel[0]];
const int64_t r = rows[0], c = cols[0];
if (r * c != n)
return refuse("its scales hold " + std::to_string(r * c) + " elements and the "
"reader wants " + std::to_string(n));
auto covers = [](int64_t b0, int64_t b) { return b <= 0 || (b0 > 0 && b % b0 == 0); };
for (int k = 1; k < n_sel; ++k) {
const RadEncPlane& p = e.plane[sel[k]];
if (!covers(p0.block[0], p.block[0]) || !covers(p0.block[1], p.block[1]))
return refuse(std::string("its '") + p.role + "' level does not cover whole '" +
p0.role + "' blocks");
}
const int64_t rb0 = rad_enc_row_bytes(p0.dtype, c);
for (int64_t i = 0; i < r; ++i)
for (int64_t j = 0; j < c; ++j) {
float v = rad_load_f32((const uint8_t*)data[0] + i * rb0, p0.dtype, j);
for (int k = 1; k < n_sel; ++k) {
const RadEncPlane& p = e.plane[sel[k]];
const int64_t li = p.block[0] > 0 ? i * p0.block[0] / p.block[0] : 0;
const int64_t lj = p.block[1] > 0 ? j * p0.block[1] / p.block[1] : 0;
if (li >= rows[k] || lj >= cols[k])
return refuse(std::string("its '") + p.role + "' level is " +
std::to_string(rows[k]) + "x" +
std::to_string(cols[k]) + " and does not reach scale " +
std::to_string(i) + "," + std::to_string(j));
v *= rad_load_f32((const uint8_t*)data[k] +
li * rad_enc_row_bytes(p.dtype, cols[k]),
p.dtype, lj);
}
rad_store_f32(out, dt, i * c + j, v);
}
return RAD_OK;
}
}
if (n_sel != e.n_planes)
return refuse("it takes " + std::to_string(n_sel) + " of its encoding's " +
std::to_string(e.n_planes) + " planes, which decode to nothing on their own");
+5 -4
View File
@@ -62,10 +62,11 @@ std::string enc_name(const RadEncoding& e);
* `data[k]`, dense [rows[k], cols[k]] in its own elements -- as `n` elements of dtype `dt` at
* `out`: the tensor a reference implementation reads where a kernel reads the stored form. One
* plane is converted element by element (a bf16 scale plane into an f32 reference, codes as their
* values); codes with the scalar codebook they index, each code as its table entry; the whole
* encoding is decoded. RAD_OK, or RAD_E_SHAPE with `why` when the planes do not
* make that tensor -- part of an encoding, which decodes to nothing on its own, or extents that
* disagree with `n`; or the decoder's own refusal. */
* values); codes with the scalar codebook they index, each code as its table entry; a scale with
* the levels of its chain above it, each scale as their product; the whole encoding is decoded.
* RAD_OK, or RAD_E_SHAPE with `why` when the planes do not make that tensor -- part of an
* encoding, which decodes to nothing on its own, or extents that disagree with `n`; or the
* decoder's own refusal. */
int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const int64_t* rows,
const int64_t* cols, const void* const* data, uint32_t dt, int64_t n,
void* out, std::string* why);
+4 -1
View File
@@ -381,7 +381,10 @@ typo'd directory is a message, not a silent quality regression.
relayout; the same for `w4nl64a8h`, `w4nl32a8h` and `w5nl64a8h`, with a second level other than
2^-13 refused, a 32-entry table other than `w5nl` refused, and each refusing the others'
encodings. `r4d_selftest --case moe_gemm_w4a8` also checks `w5nl64a8h`'s arranged row bit for
bit against the statement in r4d_layout.cpp, and its inverse.
bit against the statement in r4d_layout.cpp, and its inverse. `moe_gemm_q_mod4`'s four classes
are held to `moe_gemm_q`'s stored bytes in every format, and for both ops what the op oracle
reads through the inverse -- codes as their levels, an E4M3 scale times its second level -- is
held to the quantiser's planes.
- `r4d_selftest --case gram_accum` -- the accumulator against an f64 host Gram, **launched twice
over a seeded buffer**, because a kernel that stored instead of adding would agree with any
single-call oracle.
+36 -8
View File
@@ -1110,12 +1110,36 @@ int ref_moe_gemm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("moe_gemm", operand, out);
}
/* THE WEIGHT SCALE GRID IS THE ONE `dtype` NAMES, and the grouped GEMM serves more than one. The
* block-fp8 experts carry the checkpoint's: a scale a 128x128 tile, `group` holding the 128. The
* four-bit ones (docs/MOE-W4.md) carry one a ROW per group of K -- all of `group` at w4a8, w4a8h
* and w4nla8h, half of it at w4nl64a8h and w5nl64a8h, a quarter at w4nl32a8h. Those strings are
* the served formats' own names (arch/common/rad_block_moe_fp8.h, kServed), so this states a
* format and guesses at no kernel's stream; anything else is the block grid.
*
* It matters past the extents. A weight its kernel stores re-laid goes back through that
* kernel's inverse into the tensor THIS describes before the oracle hands it over
* (core/runtime/oracle.cpp), and the E4M3 scale views are re-laid -- their two levels are one
* operand -- so tiles here leave every such expert's scales with nothing to be inverted into.
* The arithmetic reads whichever grid it is handed (ref_gemm.h derives the group from the
* extents) and is unchanged. Weight rows and K elements a scale covers, or 0 when `group` is too
* small to divide. */
struct MoeScaleGrid { int64_t rows, k; };
static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) {
const char* d = gs(p, n_p, "dtype");
auto is = [&](const char* s) { return d && std::strcmp(d, s) == 0; };
if (is("w4a8") || is("w4a8h") || is("w4nla8h")) return { 1, g };
if (is("w4nl64a8h") || is("w5nl64a8h")) return { 1, g / 2 };
if (is("w4nl32a8h")) return { 1, g / 4 };
return { g, g };
}
/* The quantised arm. Same planes, plus the two scale streams: the activation's is per row per
* group of K (rblk 1) and the weight's is one [ceil(N/g), ceil(K/g)] plane per expert, which is
* the DeepSeek block grid the checkpoint ships. `w` is described as the STACKED [ne, N, K] plane
* even though the engine issues a pointer table against it, because a fixture has nowhere to put
* a pointer array -- ref_gemm.h's expert_entry() reads both forms and rad-kbench therefore checks
* the arithmetic against the same bytes the engine would. */
* group of K (rblk 1) and the weight's is one plane per expert on the grid above -- for block fp8
* [ceil(N/g), ceil(K/g)], the DeepSeek block grid the checkpoint ships. `w` is described as the
* STACKED [ne, N, K] plane even though the engine issues a pointer table against it, because a
* fixture has nowhere to put a pointer array -- ref_gemm.h's expert_entry() reads both forms and
* rad-kbench therefore checks the arithmetic against the same bytes the engine would. */
int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0);
@@ -1130,17 +1154,19 @@ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1;
const int64_t ne0 = (ne + 1) / 2, ne1 = ne / 2;
if (g <= 0) g = K;
const MoeScaleGrid sg = moe_scale_grid(p, n_p, g);
if (sg.rows <= 0 || sg.k <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */
o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */
o.t((uint32_t)RAD_F8E4M3, { ne0, N0, K0 }); /* w -- the even experts */
o.t(D, { ne0, (N0 + g - 1) / g, (K0 + g - 1) / g }); /* w_scale */
o.t(D, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k }); /* w_scale */
o.t_idx({ M * k }, M * k, -1, 0); /* sorted_tok */
o.t_idx({ ne + 1 }, M * k + 1, -1, 0); /* expert_offset -- see moe_gemm's note */
o.t((uint32_t)RAD_F8E4M3, { ne1, N1, K1 }); /* w_odd -- the odd experts */
o.t(D, { ne1, (N1 + g - 1) / g, (K1 + g - 1) / g }); /* w_odd_scale */
o.t(D, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k }); /* w_odd_scale */
o.t(D, { M * k, N }); /* y -- in SORTED order */
return o.finish("moe_gemm_q", operand, out);
}
@@ -1163,13 +1189,15 @@ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDes
if (Kq[q] > K) K = Kq[q];
}
if (g <= 0) g = K;
const MoeScaleGrid sg = moe_scale_grid(p, n_p, g);
if (sg.rows <= 0 || sg.k <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
auto cls = [&](int q) {
const int64_t nq = (ne + 3 - q) / 4;
o.t((uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] });
o.t(D, { nq, (Nq[q] + g - 1) / g, (Kq[q] + g - 1) / g });
o.t(D, { nq, (Nq[q] + sg.rows - 1) / sg.rows, (Kq[q] + sg.k - 1) / sg.k });
};
o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */
o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */
+3 -2
View File
@@ -26,8 +26,9 @@
# permuted. The oracle puts those back through the device row's own RadUnrelayoutFn to the planes
# and decodes them before it compares; a row that relayouts a weight and publishes no inverse is
# NOT CHECKED and says so by name. Read those lines: they are coverage this instrument does not
# have. The fp8 rows, the int8 (i8a8) block rows, the MoE 4-bit expert plane and the dense w4
# rows answer; the w8a16, w8a8, w2a8 and mxfp4 rows do not.
# have. The fp8 rows, the int8 (i8a8) block rows, the MoE 4-bit expert plane and its E4M3 scale
# views (both grouped GEMMs, every class) and the dense w4 rows answer; the w8a16, w8a8, w2a8 and
# mxfp4 rows do not.
#
# NOT EVERY GAP IS AN INVERSE SOMEBODY HAS NOT WRITTEN, AND THIS ONE IS A MISSING ZERO POINT.
# `gemm_w2a8_nt` -- the 2-bit draft head, live on EVERY speculating container, and the same gap
+59
View File
@@ -849,6 +849,65 @@ TEST(the_reference_reads_what_the_planes_decode_to) {
CHECK_EQ(((const float*)out.data())[i], rad_load_f32(sp[0].data(), RAD_BF16, i));
}
/* A SCALE WITH THE LEVEL ABOVE IT, selected without the codes -- the scale view of a w4nl64a8h
* expert, an E4M3 scale a (row, 64 of K) under one f32 for the weight. The reference reads each
* scale times the level, in the scale plane's own extents. Part of a chain that does not start at
* its first level, a level finer than the scale it would multiply, and a reader wanting another
* count are refused rather than read as something. */
TEST(the_reference_reads_a_scale_times_the_level_above_it) {
const int64_t R = 32, C = 256;
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_copy_str(e.transform, "fwht128");
rad_enc_add_plane(&e, "codes", RAD_U4, 1, 1);
rad_enc_add_plane(&e, "scale", RAD_F8E4M3, 1, 64);
rad_enc_add_plane(&e, "scale.1", RAD_F32, 0, 0);
rad_enc_add_table(&e, "table", RAD_F32, 1, 16);
REQUIRE(rad_enc_valid(&e));
auto view = [&](const RadEncoding& enc, std::vector<const char*> roles) {
KfOperand d;
d.role = RAD_OPD_WEIGHT;
d.has_enc = true;
d.enc = enc;
d.dtype = RAD_F32;
for (const char* r : roles) {
const int i = rad_enc_find(&enc, r);
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&enc.plane[i], R, C, &pr, &pc);
d.sel.push_back(i);
d.sel_rows.push_back(pr);
d.sel_cols.push_back(pc);
}
d.shape = { d.sel_rows[0], d.sel_cols[0] };
return d;
};
const KfOperand d = view(e, { "scale", "scale.1" });
REQUIRE_EQ(numel(d), R * C / 64);
std::vector<std::vector<uint8_t>> pl;
kf_draw_planes(d, 9, &pl);
REQUIRE_EQ(pl.size(), (size_t)2);
std::vector<uint8_t> out;
std::string why;
REQUIRE_EQ(kf_planes_logical(d, pl, &out, &why), RAD_OK);
const float level = rad_load_f32(pl[1].data(), RAD_F32, 0);
const float* f = (const float*)out.data();
for (int64_t i = 0; i < R * C / 64; ++i)
CHECK_EQ(f[i], rad_load_f32(pl[0].data(), RAD_F8E4M3, i) * level);
CHECK_EQ(kf_planes_logical(view(e, { "scale.1", "scale" }), pl, &out, &why), RAD_E_SHAPE);
KfOperand more = d;
more.shape = { R, C / 32 };
CHECK_EQ(kf_planes_logical(more, pl, &out, &why), RAD_E_SHAPE);
RadEncoding fine = e;
fine.plane[rad_enc_find(&e, "scale.1")].block[1] = 32;
const KfOperand df = view(fine, { "scale", "scale.1" });
std::vector<std::vector<uint8_t>> pf;
kf_draw_planes(df, 9, &pf);
CHECK_EQ(kf_planes_logical(df, pf, &out, &why), RAD_E_SHAPE);
CHECK(why.find("does not cover") != std::string::npos);
}
namespace {
int lay_identity(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int,
+95
View File
@@ -1979,6 +1979,101 @@ TEST(op_moe_gemm_q_mod4) {
}
}
/* THE WEIGHT SCALE GRID IS THE ONE THE DTYPE NAMES, in both grouped GEMMs: the checkpoint's
* 128x128 tiles for block fp8, one scale a row per group of K for the four-bit experts -- a 128 at
* w4a8/w4a8h/w4nla8h, a 64 at w4nl64a8h/w5nl64a8h, a 32 at w4nl32a8h. The oracle inverts a re-laid
* weight into exactly this description (core/runtime/oracle.cpp), and the E4M3 scale views are
* re-laid, so tiles here leave their scales nowhere to go. Then a case built from the description
* itself: one expert of the last class at K = 128, whose two 64-wide halves scale by 2 and 3 under
* one activation scale of 0.5 over the whole 128 -- a reading at any other grid gives another
* number. */
TEST(op_moe_gemm_q_scale_grid_by_dtype) {
struct Want { const char* dt; int64_t rows, cols; };
/* N 256, K 512, group 128; the last class at N 128, K 256. */
const Want wants[] = { { "fp8a8", 2, 4 }, { "w4a8", 256, 4 }, { "w4a8h", 256, 4 },
{ "w4nla8h", 256, 4 }, { "w4nl64a8h", 256, 8 }, { "w5nl64a8h", 256, 8 },
{ "w4nl32a8h", 256, 16 } };
for (const char* op : { "moe_gemm_q", "moe_gemm_q_mod4" }) {
const RadKernelInfo* k = kern(op);
REQUIRE(k != nullptr && k->opd_shape != nullptr);
const bool four = std::strcmp(op, "moe_gemm_q_mod4") == 0;
const int last = four ? 11 : 7;
for (const Want& w : wants) {
A a;
a.i("M", 2).i("N", 256).i("K", 512).i("n_expert", 8).i("top_k", 2).i("group", 128)
.s("a_order", "token").s("dtype", w.dt);
if (four) a.i("N_3", 128).i("K_3", 256);
else a.i("N_odd", 128).i("K_odd", 256);
const RadArgs* r = a.get();
RadOpdDesc d{}, dl{};
REQUIRE_EQ(k->opd_shape(r->p, r->n_p, 3, &d), RAD_OK);
REQUIRE_EQ(k->opd_shape(r->p, r->n_p, last, &dl), RAD_OK);
CHECK_EQ(d.dtype, (uint32_t)RAD_BF16);
CHECK_EQ(d.rank, 3u);
CHECK_EQ(d.shape[0], four ? 2LL : 4LL);
if (d.shape[1] != w.rows || d.shape[2] != w.cols)
std::fprintf(stderr, " %s at %s: w_scale [%lld, %lld], want [%lld, %lld]\n", op,
w.dt, (long long)d.shape[1], (long long)d.shape[2],
(long long)w.rows, (long long)w.cols);
CHECK_EQ(d.shape[1], w.rows);
CHECK_EQ(d.shape[2], w.cols);
/* the last class at its own geometry, on the same grid */
CHECK_EQ(dl.shape[1], w.rows == 2 ? 1LL : 128LL);
CHECK_EQ(dl.shape[2], w.cols / 2);
}
}
for (const char* op : { "moe_gemm_q", "moe_gemm_q_mod4" }) {
const RadKernelInfo* k = kern(op);
REQUIRE(k != nullptr && k->opd_shape != nullptr);
const bool four = std::strcmp(op, "moe_gemm_q_mod4") == 0;
const int ncls = four ? 4 : 2, ne = ncls, n_opd = four ? 13 : 9;
auto params = [&](A& x) {
x.i("M", 1).i("N", 2).i("K", 128).i("n_expert", ne).i("top_k", 1).i("group", 128)
.s("a_order", "token").s("dtype", "w4nl64a8h");
};
A p;
params(p);
const RadArgs* pr = p.get();
std::deque<T> opd;
for (int i = 0; i < n_opd; ++i) {
RadOpdDesc d{};
REQUIRE_EQ(k->opd_shape(pr->p, pr->n_p, i, &d), RAD_OK);
opd.emplace_back(d.dtype, std::vector<int64_t>(d.shape, d.shape + d.rank));
}
/* the classes' (codes, scale) operand pairs, class 0 first */
std::vector<std::pair<int, int>> cls = { { 2, 3 }, { 6, 7 } };
if (four) cls.insert(cls.end(), { { 8, 9 }, { 10, 11 } });
for (int q = 0; q < ncls; ++q) {
T& w = opd[(size_t)cls[(size_t)q].first];
T& s = opd[(size_t)cls[(size_t)q].second];
REQUIRE_EQ(s.t.shape[1], 2LL);
REQUIRE_EQ(s.t.shape[2], 2LL);
const bool hit = q == ncls - 1;
std::vector<float> wv(256);
for (int64_t n = 0; n < 2; ++n)
for (int64_t kk = 0; kk < 128; ++kk)
wv[(size_t)(n * 128 + kk)] = hit ? (float)(n + 1) : 7.0f;
w.f(wv);
s.f(hit ? std::vector<float>{ 2, 3, 2, 3 } : std::vector<float>{ 1, 1, 1, 1 });
}
opd[0].f(std::vector<float>(128, 1.0f));
opd[1].f({ 0.5f });
opd[4].n({ 0 });
/* every expert empty but the last one, which owns the one row */
std::vector<int64_t> off((size_t)ne + 1, 0);
off[(size_t)ne] = 1;
opd[5].n(off);
A a;
for (int i = 0; i < n_opd; ++i) a.t(opd[(size_t)i]);
params(a);
CHECK_OK(run(op, a));
const T& y = opd[(size_t)n_opd - 1];
CHECK_EQ(y.at(0), 160.0f); /* 0.5 * (64*1*2 + 64*1*3) */
CHECK_EQ(y.at(1), 320.0f); /* 0.5 * (64*2*2 + 64*2*3) */
}
}
TEST(op_moe_chain) {
/* Two tokens, two experts, top_k 2 -- every token visits every expert, so the whole chain is
* checkable without any routing subtlety. */
+139
View File
@@ -172,6 +172,8 @@ const Hooks nW2 { r4d_rad_layout_w2a8, r4d_rad_relayout_w2a8, r4d_rad_unr
const Hooks nMx { r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4, nullptr };
const Hooks nMoeW4 { r4d_rad_layout_moe_w4, r4d_rad_relayout_moe_w4,
r4d_rad_unrelayout_moe_w4 };
const Hooks nMoeW4Mod4 { r4d_rad_layout_moe_w4_mod4, r4d_rad_relayout_moe_w4_mod4,
r4d_rad_unrelayout_moe_w4_mod4 };
/* gemm_nt_q's operands and the other ops' weight slots, as the kernels number them */
enum { B = 2, BSCALE = 3, BREF = 6, LM_W = 1, HC_DOWN = 2, HC_UP = 3, MTP_FCH = 4, MTP_FCE = 5 };
@@ -479,6 +481,143 @@ TEST(moe_codebook_experts_at_five_bits) {
(int)s4.t.size(), &L), RAD_E_DTYPE);
}
namespace {
/* WHAT THE OP ORACLE READS FOR A RE-LAID WEIGHT, got the way Ctx::oracle_unrelayout gets it: the
* stored bytes back through the kernel's own inverse into the selected planes, and those through
* the core's enc_selection_logical into the values a dense reference multiplies -- f32 here, held
* to the same values read straight off the quantiser's planes: a code as itself or as its table
* entry, a scale times the levels above it. A selection the core cannot read on its own is a
* weight the oracle has to decline, and the E4M3 scale views were one. A view stored as it is has
* nothing to invert and is handed over unchanged. */
void oracle_reads(const char* label, const Hooks& nf, Opts kp, int operand, const Quantised& q,
int64_t R, int64_t C, const std::vector<const char*>& roles) {
Selection s = select(q, R, C, roles);
RadLayout L{};
const int lrc = nf.layout(kp.data(), kp.n(), operand, &q.enc, s.sel.data(), s.t.data(),
(int)s.t.size(), &L);
if (lrc == RAD_E_UNSUPPORTED) return;
REQUIRE_EQ(lrc, RAD_OK);
std::vector<uint8_t> laid((size_t)L.bytes);
REQUIRE_EQ(nf.relayout(kp.data(), kp.n(), operand, &q.enc, s.sel.data(), s.t.data(),
(int)s.t.size(), laid.data(), L.bytes), RAD_OK);
std::vector<std::vector<uint8_t>> bufs;
Selection back = select(q, R, C, roles, &bufs);
REQUIRE_EQ(nf.unrelayout(kp.data(), kp.n(), operand, &q.enc, back.sel.data(), laid.data(),
L.bytes, back.t.data(), (int)back.t.size()), RAD_OK);
std::vector<int64_t> rows, cols;
std::vector<const void*> pd;
for (size_t k = 0; k < back.t.size(); ++k) {
rows.push_back(back.t[k].shape[0]);
cols.push_back(back.t[k].shape[1]);
pd.push_back(bufs[k].data());
}
const int64_t n = rows[0] * cols[0];
std::vector<float> got((size_t)n);
std::string why;
const int rc = rad::enc_selection_logical(q.enc, back.sel.data(), (int)back.sel.size(),
rows.data(), cols.data(), pd.data(), RAD_F32, n,
got.data(), &why);
if (rc != RAD_OK)
std::fprintf(stderr, " %s operand %d: %s\n", label, operand, why.c_str());
REQUIRE_EQ(rc, RAD_OK);
const RadEncPlane& p0 = q.enc.plane[s.sel[0]];
const uint8_t* src = q.planes[(size_t)s.sel[0]].data();
const int64_t rb = rad_enc_row_bytes(p0.dtype, cols[0]);
const float* table = nullptr;
float level = 1.0f;
for (size_t k = 1; k < roles.size(); ++k) {
const std::vector<uint8_t>& pk = q.planes[(size_t)s.sel[k]];
if (!std::strcmp(roles[k], "table")) table = (const float*)pk.data();
else level *= rad_load_f32(pk.data(), q.enc.plane[s.sel[k]].dtype, 0);
}
int64_t bad = 0;
for (int64_t i = 0; i < rows[0]; ++i)
for (int64_t j = 0; j < cols[0]; ++j) {
float v = rad_load_f32(src + i * rb, p0.dtype, j);
if (table) v = table[(int64_t)v];
if (got[(size_t)(i * cols[0] + j)] != v * level) ++bad;
}
if (bad) std::fprintf(stderr, " %s operand %d: %lld of %lld read wrong\n", label, operand,
(long long)bad, (long long)n);
CHECK_EQ(bad, (int64_t)0);
}
/* A four-bit expert format as the quantiser is asked for it, and its two views. */
struct MoeFmt {
const char* dtype;
Opts quant;
std::vector<const char*> codes, scales;
};
std::vector<MoeFmt> moe_formats() {
auto nl = [](const char* table, long long group) {
Opts g;
g.s("table", table).i("group", group).s("scale", "fp8_e4m3").s("scale2", "f32")
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128")
.s("rule", "search");
return g;
};
Opts i4, nla;
i4.s("codes", "i4").i("group", 128).s("scale", "bf16").s("transform", "fwht128");
nla.s("table", "w4nl").i("group", 128).s("scale", "bf16").s("transform", "fwht128")
.s("rule", "search");
return {
{ "w4a8h", i4, { "codes" }, { "scale" } },
{ "w4nla8h", nla, { "codes", "table" }, { "scale" } },
{ "w4nl64a8h", nl("w4nl", 64), { "codes", "table" }, { "scale", "scale.1" } },
{ "w4nl32a8h", nl("w4nl", 32), { "codes", "table" }, { "scale", "scale.1" } },
{ "w5nl64a8h", nl("w5nl", 64), { "codes", "table" }, { "scale", "scale.1" } },
};
}
} /* namespace */
/* THE FOUR CLASSES ARE THE TWO-CLASS HOOKS ONE CLASS FURTHER ALONG. moe_gemm_q_mod4's class q is
* operands 2/3 at N/K for q = 0 and 2q+4/2q+5 at N_q/K_q after it, and each is stored, and read
* back, exactly as moe_gemm_q's hooks store an expert of that geometry -- codes and scales, in
* every four-bit format, at four class geometries. Then what the op oracle reads through each
* class's inverse, codes and E4M3 scale views alike, and through the two-class op's own. */
TEST(moe_four_classes_store_and_read_back_as_two_classes_do) {
NEED_LIBQUANT();
const int64_t Nq[4] = { 64, 128, 64, 48 }, Kq[4] = { 256, 256, 128, 128 };
for (MoeFmt& f : moe_formats()) {
Opts kp4;
kp4.i("N", Nq[0]).i("K", Kq[0]).i("N_1", Nq[1]).i("K_1", Kq[1]).i("N_2", Nq[2])
.i("K_2", Kq[2]).i("N_3", Nq[3]).i("K_3", Kq[3]).s("dtype", f.dtype).i("group", 128);
for (int q = 0; q < 4; ++q) {
const std::vector<float> w = weight(Nq[q], Kq[q], 30 + q, 1, 128);
const int cop = q == 0 ? B : 2 * q + 4, sop = cop + 1;
Opts kp2;
kp2.i("N", Nq[q]).i("K", Kq[q]).s("dtype", f.dtype).i("group", 128);
const std::string label = std::string(f.dtype) + " class " + std::to_string(q);
Quantised kept;
const uint64_t h4 = stored(label.c_str(), nMoeW4Mod4, kp4, "rtn", f.quant,
"blk.0.ffn_down_exps.0.weight", Nq[q], Kq[q], w,
{ { cop, f.codes }, { sop, f.scales } }, &kept);
const uint64_t h2 = stored(label.c_str(), nMoeW4, kp2, "rtn", f.quant,
"blk.0.ffn_down_exps.0.weight", Nq[q], Kq[q], w,
{ { B, f.codes }, { BSCALE, f.scales } });
if (h4 != h2)
std::fprintf(stderr, " %s: four-class hash 0x%016llx, two-class 0x%016llx\n",
label.c_str(), (unsigned long long)h4, (unsigned long long)h2);
CHECK_EQ(h4, h2);
REQUIRE_EQ(kept.status, RAD_OK);
oracle_reads(label.c_str(), nMoeW4Mod4, kp4, cop, kept, Nq[q], Kq[q], f.codes);
oracle_reads(label.c_str(), nMoeW4Mod4, kp4, sop, kept, Nq[q], Kq[q], f.scales);
oracle_reads(label.c_str(), nMoeW4, kp2, B, kept, Nq[q], Kq[q], f.codes);
oracle_reads(label.c_str(), nMoeW4, kp2, BSCALE, kept, Nq[q], Kq[q], f.scales);
/* A class reads its own geometry and nobody else's: class 1 is 128 wide, so an
* expert of any other class's width is refused there. */
if (q != 1) {
Selection s = select(kept, Nq[q], Kq[q], f.codes);
RadLayout L{};
CHECK_EQ(nMoeW4Mod4.layout(kp4.data(), kp4.n(), 6, &kept.enc, s.sel.data(),
s.t.data(), (int)s.t.size(), &L), RAD_E_SHAPE);
}
}
}
}
TEST(moe_int4_gptq_against_a_calibration_hessian) {
NEED_LIBQUANT();
/* Correlated activations, so the Hessian is far from diagonal and the error feedback moves