From a323b76bca342c40fd28f1cfe306ca55b44b27e3 Mon Sep 17 00:00:00 2001 From: hugypufy Date: Sun, 25 Oct 2026 11:40:57 +0000 Subject: [PATCH] libquant: the m2xfp4 quantiser -- M2XFP's metadata-augmented MXFP4, weights only, with its own decode M2XFP (arXiv 2601.19213) keeps OCP MXFP4's codes and E8M0 exponent and adds one metadata byte a group of 32: four 2-bit extra mantissas, each refining the shared scale of a subgroup of 8 to (1 + k/4) . 2^E. The quantiser searches each subgroup's k and the exponent's bias by least squared error (the paper's Sg-EM), stores codes, scale and meta as three planes of scheme "m2xfp4" and supplies the decode hook the core needs for a scheme it cannot follow. spec.md gains the encoding and quantiser rows; quant_m2xfp_test covers the planes, determinism and quality. Co-Authored-By: Claude Opus 5.5 --- libquant/lq_m2xfp.cpp | 253 ++++++++++++++++++++++++++++ libquant/lq_quant.h | 1 + libquant/lq_registry.cpp | 1 + spec.md | 22 +++ tests/quant_m2xfp_test.cpp | 336 +++++++++++++++++++++++++++++++++++++ 5 files changed, 613 insertions(+) create mode 100644 libquant/lq_m2xfp.cpp create mode 100644 tests/quant_m2xfp_test.cpp diff --git a/libquant/lq_m2xfp.cpp b/libquant/lq_m2xfp.cpp new file mode 100644 index 00000000..8a2ef172 --- /dev/null +++ b/libquant/lq_m2xfp.cpp @@ -0,0 +1,253 @@ +/* lq_m2xfp.cpp -- the `m2xfp4` quantiser: M2XFP, a metadata-augmented Microscaling format + * (Weiming Hu et al., "M2XFP: A Metadata-Augmented Microscaling Data Format for Efficient + * Low-bit Quantization", ASPLOS '26, arXiv 2601.19213), weight side only -- the paper's + * Sg-EM scheme, subgroup-level extra mantissa with an adaptive shared scale. + * + * An OCP MXFP4 group of 32 columns carries, beside its E8M0 exponent, one metadata byte: four + * 2-bit extra mantissas, one a subgroup of 8 columns. Subgroup s (columns [8s, 8s+8)) refines the + * group's shared scale to (1 + k/4) . 2^E with k its two bits, so a group decodes as + * + * w[j] = e2m1(codes[j]) . 2^(scale[g] - 127) . (1 + k_s/4), g = j/32, s = (j%32)/8, + * + * 4.5 bits an element. The three planes sit apart, as the paper's memory organisation keeps them + * (its §5.2): codes fp4_e2m1 [1 x 1] as a bit stream along the row (abi/rad_encoding.h), the scale + * e8m0 [1 x 32] and the metadata u8 [1 x 32] one byte a group, the metadata packed little-endian, + * subgroup s in bits [2s, 2s+2). The scheme is "m2xfp4", which the core does not decode; the + * quantiser's own decode hook reads it back (abi/rad_quant.h). + * + * The search is the paper's §4.4.2, Eqs. 3-4, hierarchical because a subgroup's k is chosen + * independently once the bias is fixed and only the bias couples the subgroups. E0 is the OCP + * rule floor(log2(amax / 4)); the group's scale candidates are 2^(E0+b), b in {-1, 0, 1}, and + * each subgroup's are (1 + k/4) times the group's, k in {0, 1, 2, 3}. For a bias, every + * subgroup takes the k of least squared error against its own 8 columns; the group takes the + * bias of least squared error over the four. adaptive=0 pins the bias at 0 and searches the + * subgroups only, which is where a container that wants the plain exponent still wants the + * refinement; wide=1 widens adaptive's sweep to b in {-2, ..., 2}, still lowest-first so a tie + * keeps the lowest bias. The bias costs nothing stored: it is absorbed into the exponent byte. + * + * Conventions shared with the MXFP4 grid (`rtn codes=fp4_e2m1 group=32 scale=e8m0`, + * lq_grid.cpp's rule=mx), whose containers this format is a superset of: + * - E0 is taken as the f32 exponent field of amax less 129, exactly as rule=mx takes it (for + * every normal amax that is floor(log2(amax)) - 2); the paper's reference takes floor(log2 + * of an amax clamped to 1e-8, which differs only below the f32 normals; + * - a zero group stores scale byte 0 and zero codes, rule=mx's exponent-floor clamp; the + * reference's clamp gives a different byte whose codes and decode are the same zeros; + * - codes round to nearest, ties to the even code -- f32_to_e2m1, the same rounding the grid + * quantises with (and the reference's nudged midpoints); + * - the exponent byte is clamped to [0, 254]; 255 is E8M0's NaN; + * - a final group shorter than 32 columns is its own group over the columns it has, the way + * the grid quantises a row's tail (the reference requires a whole number of groups). + * + * Under the (b=0, k=0) candidate every group reproduces rule=mx's scale and codes exactly, so + * an adaptive weight's error is that plain MXFP4's or better, group by group. + * + * The error summed is in double; the per-candidate dequantised value is computed exactly as the + * decode computes it (the code through rad_fp4e2m1_to_f32, times the candidate's scale), so what + * the search minimises is what a reader gets. Rows are independent, so the stored bytes do not + * depend on the thread count. + */ +#include "lq_common.h" +#include "lq_quant.h" + +#include +#include +#include + +namespace lq { + +namespace { + +const char kScheme[] = "m2xfp4"; + +const RadQuantOption kM2xfpOptions[] = { + { "adaptive", RAD_P_INT, "1", + "1: search the group's exponent bias b in {-1, 0, 1} beside the subgroups (the paper's " + "Eq. 4); 0: the bias pinned at 0, the subgroup search still on" }, + { "wide", RAD_P_INT, "0", + "1: widen adaptive's bias search to b in {-2, -1, 0, 1, 2}; 0: {-1, 0, 1}. Ignored at " + "adaptive=0, which pins the bias at 0 whatever the sweep width" }, +}; + +/* One subgroup's least squared error over k, with k itself through `best` when asked: the + * subgroups of one bias are independent (the paper's Eq. 4 inner argmin). The dequantised value + * is the code through the same table the decode reads, times the candidate's scale. */ +double subgroup_sse(const float* w, int64_t b0, int64_t b1, float s, int* best) { + double best_sse = -1.0; + int best_k = 0; + for (int k = 0; k < 4; ++k) { + const float sm = s * (1.0f + 0.25f * (float)k); + double sse = 0.0; + for (int64_t i = b0; i < b1; ++i) { + const float dq = rad_fp4e2m1_to_f32(f32_to_e2m1(w[i] / sm)) * sm; + const double d = (double)dq - (double)w[i]; + sse += d * d; + } + if (best_sse < 0.0 || sse < best_sse) { + best_sse = sse; + best_k = k; + } + } + if (best) *best = best_k; + return best_sse; +} + +/* One row's group of [c0, c1): the OCP exponent of its amax, the bias of least subgroup error, + * then the winning bias's subgroups, whose k go into the metadata byte and whose codes and + * exponent byte go into the planes. Ties keep the first candidate, the k and then the b of + * lowest index, as the paper's argmin does. */ +void quant_group(const float* w, int64_t c0, int64_t c1, int adaptive, int wide, uint8_t* codes, + uint8_t* scale, uint8_t* meta, uint32_t codes_dt) { + float amax = 0.0f; + for (int64_t c = c0; c < c1; ++c) { + const float a = w[c] < 0.0f ? -w[c] : w[c]; + if (a > amax) amax = a; + } + /* E0 = floor(log2(amax / 4)), as rule=mx takes it: the exponent field less emax + 127. A + * zero group keeps -127, the field's underflow, whose byte clamps to 0 like rule=mx's. */ + int e0 = -127; + if (amax > 0.0f) { + uint32_t u; + std::memcpy(&u, &amax, 4); + e0 = (int)((u >> 23) & 0xFFu) - 127 - 2; + } + + /* The bias: every subgroup's best k given it, summed over the group (the paper averages the + * four, the same argmin). adaptive=0 sees only b = 0; wide sweeps b over {-2, ..., 2} + * instead of {-1, 0, 1}, lowest first either way, so a tie keeps the lowest bias as the + * paper's argmin does. */ + const int lo = adaptive ? (wide ? -2 : -1) : 0; + const int hi = adaptive ? (wide ? 2 : 1) : 0; + int best_b = 0; + double best_err = -1.0; + for (int b = lo; b <= hi; ++b) { + const float s = rad_e8m0_to_f32((uint8_t)clampi(e0 + b + 127, 0, 254)); + double err = 0.0; + for (int64_t c = c0; c < c1; c += 8) + err += subgroup_sse(w, c, c + 8 < c1 ? c + 8 : c1, s, nullptr); + if (best_err < 0.0 || err < best_err) { + best_err = err; + best_b = b; + } + } + + /* The winning bias's scale, its subgroups' k, and the codes those k were chosen against. */ + const int e8 = clampi(e0 + best_b + 127, 0, 254); + const float s = rad_e8m0_to_f32((uint8_t)e8); + uint8_t mb = 0; + for (int sl = 0; sl < 4; ++sl) { + const int64_t c = c0 + 8 * sl; + if (c >= c1) break; /* a short final group's absent subgroups */ + int k = 0; + subgroup_sse(w, c, c + 8 < c1 ? c + 8 : c1, s, &k); + mb |= (uint8_t)k << (2 * sl); + const float sm = s * (1.0f + 0.25f * (float)k); + for (int64_t j = c; j < c + 8 && j < c1; ++j) + rad_store_code(codes, codes_dt, j, (int)f32_to_e2m1(w[j] / sm)); + } + *scale = (uint8_t)e8; + *meta = mb; +} + +int m2xfp_encoding(const RadParam*, int, const RadQuantWeight* w, RadEncoding* out) { + if (declines(w)) return RAD_E_UNSUPPORTED; + if (!w || w->cols <= 0 || w->rows <= 0) return RAD_E_SHAPE; + rad_enc_clear(out); + rad_enc_copy_str(out->scheme, kScheme); + /* The three streams of the paper's §5.2: the codes, the group's exponent, the group's + * metadata -- a final group shorter than 32 columns covers the columns it has. The codes and + * the scale carry the MXFP4 grid's dtypes, whose bytes these are; the exponent byte is an + * E8M0 biased exponent, never the integer a bare u8 would read as. */ + rad_enc_add_plane(out, "codes", RAD_FP4E2M1, 1, 1); + rad_enc_add_plane(out, "scale", RAD_E8M0, 1, 32); + rad_enc_add_plane(out, "meta", RAD_U8, 1, 32); + return RAD_OK; +} + +/* Groups are column-local and rows independent, so a call may take any rows: one, as the MXFP4 + * grid's row block is, and the converter streams by its band, not by the format. */ +int64_t m2xfp_row_block(const RadParam*, int, const RadQuantWeight*) { return 1; } + +int m2xfp_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0, + int64_t rows, void* const* planes) { + if (!w || w->cols <= 0 || w->rows <= 0) return RAD_E_SHAPE; + if (row0 < 0 || rows < 0 || row0 + rows > w->rows) return RAD_E_SHAPE; + const int adaptive = (int)rad_param_geti(o, n_o, "adaptive", 1); + const int wide = (int)rad_param_geti(o, n_o, "wide", 0); + const int64_t C = w->cols; + const int64_t ng = (C + 31) / 32; /* groups a row, the last one maybe short */ + uint8_t* codes = (uint8_t*)planes[0]; + uint8_t* scale = (uint8_t*)planes[1]; + uint8_t* meta = (uint8_t*)planes[2]; + const int64_t codes_row = rad_enc_row_bytes(RAD_FP4E2M1, C); + const uint32_t codes_dt = RAD_FP4E2M1; /* the plane's dtype: same four bits as u4 */ +#ifdef _OPENMP +#pragma omp parallel for schedule(static) +#endif + for (int64_t r = 0; r < rows; ++r) { + const float* wr = src + r * C; + uint8_t* cr = codes + r * codes_row; + uint8_t* sr = scale + r * ng; + uint8_t* mr = meta + r * ng; + for (int64_t g = 0; g < ng; ++g) + quant_group(wr, g * 32, std::min(g * 32 + 32, C), adaptive, wide, cr, sr + g, mr + g, + codes_dt); + } + return RAD_OK; +} + +/* The encoding's own decode (abi/rad_quant.h): the equation of the scheme, the only place the + * core cannot follow it. RAD_E_UNSUPPORTED for an encoding this quantiser did not write. */ +int m2xfp_decode(const RadEncoding* e, const RadQuantWeight* w, const void* const* planes, + int64_t row0, int64_t rows, float* out) { + if (!rad_enc_is(e, kScheme) || e->n_planes != 3) return RAD_E_UNSUPPORTED; + const RadEncPlane* p = e->plane; + if (p[0].dtype != RAD_FP4E2M1 || p[0].kind != RAD_PLANE_TILED || p[0].block[0] != 1 || + p[0].block[1] != 1 || std::strcmp(p[0].role, "codes") != 0) + return RAD_E_UNSUPPORTED; + for (int i = 1; i < 3; ++i) + if (p[i].dtype != (i == 1 ? RAD_E8M0 : RAD_U8) || p[i].kind != RAD_PLANE_TILED || + p[i].block[0] != 1 || p[i].block[1] != 32 || + (i == 1 ? std::strcmp(p[i].role, "scale") != 0 + : std::strcmp(p[i].role, "meta") != 0)) + return RAD_E_UNSUPPORTED; + if (!w || w->cols <= 0) return RAD_E_SHAPE; + + const int64_t C = w->cols; + const int64_t ng = (C + 31) / 32; + const uint8_t* codes = (const uint8_t*)planes[0]; + const uint8_t* scale = (const uint8_t*)planes[1]; + const uint8_t* meta = (const uint8_t*)planes[2]; + const int64_t codes_row = rad_enc_row_bytes(RAD_FP4E2M1, C); + for (int64_t r = 0; r < rows; ++r) { + const uint8_t* cr = codes + (row0 + r) * codes_row; + const uint8_t* sr = scale + (row0 + r) * ng; + const uint8_t* mr = meta + (row0 + r) * ng; + float* orow = out + r * C; + for (int64_t j = 0; j < C; ++j) { + const uint8_t c = (uint8_t)rad_load_bits(cr, 4, j); + const uint8_t mb = mr[j >> 5]; + const int k = (mb >> (2 * ((j & 31) >> 3))) & 3; + orow[j] = rad_fp4e2m1_to_f32(c) * rad_e8m0_to_f32(sr[j >> 5]) * + (1.0f + 0.25f * (float)k); + } + } + return RAD_OK; +} + +} // namespace + +const RadQuantizerInfo& m2xfp_info() { + static const RadQuantizerInfo q = { + "m2xfp4", + "M2XFP: OCP MXFP4 whose group of 32 also carries one metadata byte of four 2-bit " + "subgroup extra mantissas, each a subgroup of 8 columns refining the shared exponent to " + "(1 + k/4) . 2^E, the exponent itself searched over a bias {-1, 0, 1}, widened to " + "{-2, ..., 2} by wide=1, and absorbed into its byte (adaptive=0 pins the bias at 0); " + "4.5 bits an element, weights only, adapted from arXiv 2601.19213", + kM2xfpOptions, (int)(sizeof kM2xfpOptions / sizeof kM2xfpOptions[0]), + m2xfp_encoding, m2xfp_row_block, m2xfp_quantize, m2xfp_decode, + }; + return q; +} + +} // namespace lq diff --git a/libquant/lq_quant.h b/libquant/lq_quant.h index f2a881f8..ca24e96c 100644 --- a/libquant/lq_quant.h +++ b/libquant/lq_quant.h @@ -81,5 +81,6 @@ inline int64_t gather_units(const float* w, int64_t N, int64_t K, int64_t unit, const RadQuantizerInfo& awq_info(); const RadQuantizerInfo& autoround_info(); const RadQuantizerInfo& paroquant_info(); +const RadQuantizerInfo& m2xfp_info(); } /* namespace lq */ diff --git a/libquant/lq_registry.cpp b/libquant/lq_registry.cpp index 8dc0dc0a..63b29edb 100644 --- a/libquant/lq_registry.cpp +++ b/libquant/lq_registry.cpp @@ -244,6 +244,7 @@ const std::vector& table() { v.push_back(&autoround_info()); v.push_back(&paroquant_info()); v.push_back(&ggml_quantizer); + v.push_back(&m2xfp_info()); return v; }(); return t; diff --git a/spec.md b/spec.md index 1c716a5f..24c94965 100644 --- a/spec.md +++ b/spec.md @@ -552,6 +552,7 @@ which people, logs and `rad-info` read; kernels read the struct: | `u2*f16[1x128]-u8[1x128]` | a 2-bit draft head, asymmetric | | `fp4_e2m1*e8m0[1x32]` | MXFP4 | | `fp4_e2m1*fp8_e4m3[1x16]*f32[*x*]` | NVFP4: two scale levels | +| `m2xfp4:codes=fp4_e2m1[1x1],scale=e8m0[1x32],meta=u8[1x32]` | M2XFP: MXFP4 with a metadata byte a group | | codes `u4`, `scale u6[1x32] . f16[1x256]`, `min u6[1x32] . f16[1x256]` | llama.cpp's Q4_K | | codes `u4`, `table i8{1x16}`, two scale levels | IQ4_XS | | codes `u8[1x8]` into `grid u8{256x8}`, `signs`, two scale levels | IQ2_XXS | @@ -562,6 +563,26 @@ which people, logs and `rad-info` read; kernels read the struct: A GGUF file's K- and I-quants are therefore a lossless rearrangement into planes; serving one needs only a kernel that reads it. +A scheme the core does not decode is `m2xfp4`: M2XFP (adapted from "M2XFP: +A Metadata-Augmented Microscaling Data Format for Efficient Low-bit Quantization", arXiv +2601.19213, the paper's weight-side Sg-EM only -- its element-side activation scheme is not +encoded here). An OCP MXFP4 group of 32 columns carries, beside its E8M0 exponent, one metadata +byte: four 2-bit extra mantissas, one a subgroup of 8 columns. Subgroup s (columns [8s, 8s+8)) +refines the group's shared scale to (1 + k/4) . 2^E with k its two bits, little-endian in bits +[2s, 2s+2), so a group decodes as + +``` +w[j] = e2m1(codes[j]) . 2^(scale[g] - 127) . (1 + k_s/4), g = j/32, s = (j%32)/8 +``` + +4.5 bits an element. The three planes sit apart -- codes fp4_e2m1 [1 x 1] as a bit stream along +the row (the MXFP4 codes' bytes), the scale e8m0 [1 x 32] and the metadata u8 [1 x 32] one byte a +group -- as the paper's memory organisation keeps them (its §5.2). The exponent byte follows the +MXFP4 grid's OCP rule and its conventions, zeros and short final groups included +(`libquant/lq_m2xfp.cpp`); the quantiser's search chooses the bias of the shared exponent and each +subgroup's k by least squared error (§4.5). The core cannot follow the equation, so the quantiser +supplies the decoder, as below. + The core decodes every `plain` and `affine` encoding to f32 (for the oracle, `rad-convert`'s error report, and requantising). A quantiser whose scheme the core cannot decode supplies the decoder (§4.5). @@ -739,6 +760,7 @@ Each algorithm pairs with any grid it makes sense for, and a recipe names all th | `autoround` | sign-gradient descent on rounding offsets and block ranges against H | integer codes, row blocks, one level | the grid | | `paroquant` | Givens pair rotations and channel scales fitted against H, then AutoRound | every untransformed one | the grid and a `givens` transform | | `ggml` | llama.cpp's own searches, imatrix-weighted | its legacy, K- and I-quant types | each type's affine form | +| `m2xfp4` | M2XFP's weight-side Sg-EM: per group of 32, each subgroup of 8's extra mantissa k in {0..3} and the shared exponent's bias in {-1, 0, 1} (`adaptive=0` pins the bias, `wide=1` widens it to {-2..2}) chosen by least squared error, the OCP exponent and its rounding otherwise the MXFP4 grid's | none of the grid options | its own scheme `m2xfp4`, which it decodes: MXFP4's codes and E8M0 exponent plus a u8 metadata byte a group (arXiv 2601.19213) | | `cast` | a float in another float dtype | none | `plain` | The grid is `codes` (integers to 32 bits, fp8/6/4) or `table` (a codebook: NF4, IQ4_NL's values, diff --git a/tests/quant_m2xfp_test.cpp b/tests/quant_m2xfp_test.cpp new file mode 100644 index 00000000..d9f55246 --- /dev/null +++ b/tests/quant_m2xfp_test.cpp @@ -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 + +#include +#include +#include +#include + +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 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 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& w, const std::vector& 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 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 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 octave_groups(int64_t rows, int64_t cols, uint64_t seed) { + const std::vector z = draw(rows * cols, seed, 4.0f); + std::vector 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 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 d = decode(a, R, C); + REQUIRE_EQ(d.size(), w.size()); + const std::vector 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 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 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 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 d = decode(a, 1, 32); + REQUIRE_EQ(d.size(), w.size()); + const std::vector 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 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 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 w; }; + std::vector 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 w; }; + std::vector 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 d = decode(wide, R, C); + const std::vector 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 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()