core/format, arch/common, libr4d: the ParoQuant M2XFP4 import -- Import::ParoM2 reads a paroquant_m2xfp4 checkpoint's planes and rotations, served as rotated MXFP4 is

A paroquant_m2xfp4 checkpoint (format m2xfp4, groups of 32, subgroups of 8, rotation groups of
128) is imported as ParoQuant's MXFP4 is: the codes, exponents and weight_meta bytes become the
m2xfp4 scheme's three planes byte for byte, joined row by row, with the learned rotations beside
them as the givens tables. LinearFP8 declares the rotated form like the rotated MXFP4 one, through
givens_dense_quant into its own E4M3 pair, and libr4d's layout hook and both m2xfp4 rows accept
it, the rows running a fused projection's parts (pb1/pb2) one launch a part as the mxfp4a8 rows
do. libref accepts the rotated planes and runs the parts as its mxfp4a8 arm does; libavx serves
no M2XFP4. checkpoint_test covers the import, quant_m2xfp_test libref's parts and r4d_selftest
libr4d's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugypufyandClaude Opus 5.5 authored and StillDeadcode committed 2026-10-26 15:22:39 +01:00
1 parent b6ad757bfa
commit 2c645333a1
11 files changed
+469 -102

No files matched your search

+65 -9
View File
@@ -929,6 +929,24 @@ inline bool linear_is_paro_mxfp4(const RadEncoding& e) {
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
}
/* A rotated weight with M2XFP4 planes (ParoQuant's `m2xfp4` grid): the scheme's three planes in
* the basis of a "givens" transform, whose tables are views of the weight's planes. Read like the
* plain M2XFP4 weight -- the meta plane rides the weight operand's stored blob -- over an
* activation the rotation makes, as linear_is_paro_mxfp4's is. */
inline bool linear_is_paro_m2xfp4(const RadEncoding& e) {
if (!rad_enc_is(&e, "m2xfp4") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0 ||
!rad_enc_valid(&e) || e.n_planes < 6)
return false;
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *mt = rad_enc_plane(&e, "meta"),
*pr = rad_enc_plane(&e, "t.pairs"), *an = rad_enc_plane(&e, "t.angle"),
*rs = rad_enc_plane(&e, "t.scale");
return pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32 &&
e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[0] == 1 &&
e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_E8M0 && sc->block[0] == 1 &&
sc->block[1] == RAD_MX_GROUP && mt && mt->dtype == RAD_U8 && mt->block[0] == 1 &&
mt->block[1] == RAD_MX_GROUP;
}
/* A 4-bit weight with a zero point and no transform: u4 codes, an f16 scale and a u4 or u8 zero
* point per 128 of K (libquant `codes=u4 zero=u4 group=128 scale=f16`, or rad-convert's import rule
* over an int4 release). Read by gemm_nt_q at w4a16_asym over an f16 activation, or w4a8i8_asym
@@ -965,7 +983,8 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc));
/* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or
* quantises it. */
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc));
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc) ||
linear_is_paro_m2xfp4(enc));
reads_x = g.w_bf16 || plain || probed_i8 || rotated || (known && linear_is_w4(enc));
return RAD_OK;
}
@@ -1425,15 +1444,34 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
* which rides the weight operand -- the declared view takes codes and meta together, and the
* stored blob carries the meta in its tail (libr4d's m2xfp4 layout). The exponent plane is
* `b_scale` and `b_ref` as MXFP4's is; the row parts, the shape bounds and the column-shard
* rule are the MXFP4 ones. */
m2x = known && linear_is_m2xfp4(enc);
* rule are the MXFP4 ones.
*
* A rotated weight (ParoQuant) carries the same planes in the basis its "givens" tables name
* and is declared like the rotated MXFP4 one: `givens_dense_quant` makes the E4M3 pair from
* the input's bf16 plane, once per rotated part, and the GEMM meets copy p with part p's rows
* (`pb1`/`pb2`). `paro` makes step() issue that rotation first. */
const bool m2rot = known && linear_is_paro_m2xfp4(enc);
m2x = known && (linear_is_m2xfp4(enc) || m2rot);
if (m2x) {
paro = m2rot;
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
"may\n", wn, stored);
return RAD_E_INVAL;
}
if (!a.q || !a.s) {
if (m2rot) {
if (!a.x) {
fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 weight, rotated and quantised "
"from its input's bf16 plane, and its input has none\n", wn);
return RAD_E_DTYPE;
}
if (g.world > 1 || span_hi > 0) {
fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 weight; its rotation is per "
"projection and is not cut by a tensor-parallel shard (world %d)\n",
wn, g.world);
return RAD_E_UNSUPPORTED;
}
} else if (!a.q || !a.s) {
fprintf(stderr, "radiance: '%s' is an M2XFP4 weight read against its input's E4M3 "
"pair, and its input has none\n", wn);
return RAD_E_DTYPE;
@@ -1446,6 +1484,22 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles"));
int64_t pb1 = 0, pb2 = 0;
if (m2rot) {
std::vector<int64_t> cut;
for (int64_t p : rot_part_rows) cut.push_back(p);
if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p);
RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2));
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, rot_parts * K });
rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32,
{ rows, rot_parts * (K / RAD_FP8_BLOCK) });
if (!rot_q || !rot_s) return RAD_E_INVAL;
rot_dense = decl_dense(b, nm, base, wn, enc, K, grp);
if (!rot_dense) return RAD_E_INVAL;
op_rot = decl_dense_op(b, g, a, "fp8", 1, rows, { rot_q, rot_s });
if (!op_rot) return RAD_E_INVAL;
}
const char* sn = nm.f("%s.scale", base);
const char* rn = nm.f("%s.ref", base);
w = decl_view(b, wn, nullptr, "codes,meta", RAD_FP4E2M1, { N, K }, access, shard, grp,
@@ -1469,8 +1523,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
}
op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP, "m2xfp4", 0, 0,
{ w, ws, wref }, { a.q, a.s }, y);
/* One GEMM: a rotated weight reads its own rotated pair, a plain one the producer's. */
op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP, "m2xfp4", pb1,
pb2, { w, ws, wref }, { m2rot ? rot_q : a.q, m2rot ? rot_s : a.s }, y);
return op ? RAD_OK : RAD_E_INVAL;
}
@@ -1597,16 +1652,17 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (m2x) {
if (m2x && !paro) {
/* The MXFP4 operands over the producer's pair; the meta rides the weight's stored blob. */
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref));
return;
}
if (mx) {
if (mx || m2x) {
/* A rotated weight first rotates its input into its own codes, `rot_parts` copies side by
* side; a plain weight reads the producer's. */
* side; a plain weight reads the producer's. A rotated M2XFP4 weight is issued here as the
* rotated MXFP4 one is, its meta riding the weight operand's stored blob. */
const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s;
const int64_t ak = rot_parts * K;
if (paro)
+84 -4
View File
@@ -1221,6 +1221,18 @@ void Checkpoint::detect_import() {
else
import_why_ = "ParoQuant's MXFP4 here is not format mxfp4 with 32-element blocks and "
"rotation groups of 128, which is the one this reads";
} else if (qm == "paroquant_m2xfp4") {
/* The same rotated planes on libquant's `m2xfp4` grid: e2m1 codes, an e8m0 exponent per 32
* of K, and one metadata byte a group whose four 2-bit subgroup multipliers refine that
* exponent to (1 + k/4) . 2^E. `mx_block` states the group the planes are cut in and
* `subgroup` the columns one multiplier covers. */
if (qc("format") == "m2xfp4" && qc("mx_block") == "32" && qc("subgroup") == "8" &&
qc("group_size") == "128")
import_ = Import::ParoM2;
else
import_why_ = "ParoQuant's M2XFP4 here is not format m2xfp4 with 32-element groups, "
"8-element subgroups and rotation groups of 128, which is the one this "
"reads";
}
/* Rename the tool's quantization_config: plugins read that key as the served format
* (qwen35_fp8 checks quant_method is "fp8"), while an imported checkpoint states each weight's
@@ -1285,10 +1297,13 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK;
}
if (import_ == Import::QuarkMx || import_ == Import::ParoMx) {
if (import_ == Import::QuarkMx || import_ == Import::ParoMx || import_ == Import::ParoM2) {
/* Quark's MXFP4 is `fp4_e2m1*e8m0[1x32]` as stored: two codes per byte (element 2j in the
* low nibble), one biased exponent per 32 of K. The view only renames dtypes and the
* logical width. Excluded layers are plain tensors. */
* logical width. Excluded layers are plain tensors. ParoQuant's M2XFP4 grid carries one
* more plane (`weight_meta`, [N, K/32] u8) that is handed to the weight through
* import_meta: its bytes are the encoding's third plane as they ship. */
const bool m2 = import_ == Import::ParoM2;
const SrcTensor* w = find(name);
const SrcTensor* e = w ? find(name + "_scale") : nullptr;
if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND;
@@ -1296,6 +1311,11 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
e->shape[0] != w->shape[0] || e->shape[1] * 32 != w->shape[1] * 2)
return refuse(RAD_E_SHAPE, "'" + e->name + "' is not the [N, K/32] exponent plane of '" +
w->name + "'");
const SrcTensor* mt = m2 ? find(name + "_meta") : nullptr;
if (m2 && (!mt || mt->rad_dtype != RAD_U8 || mt->shape != e->shape))
return refuse(RAD_E_FORMAT, "'" + w->name + "' has no [N, K/32] u8 '" + name +
"_meta' beside its exponent plane, which the checkpoint's "
"m2xfp4 grid stores the subgroup multipliers in");
SrcTensor c = *w;
c.rad_dtype = RAD_FP4E2M1;
c.shape = { w->shape[0], w->shape[1] * 2 };
@@ -1306,6 +1326,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
sliced_.push_back(std::move(x));
*scale = &sliced_.back();
imported_[name] = { *codes, *scale };
if (mt) imported_meta_[name] = mt;
return RAD_OK;
}
@@ -1582,6 +1603,11 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK;
}
const SrcTensor* Checkpoint::import_meta(const std::string& name) const {
auto it = imported_meta_.find(name);
return it == imported_meta_.end() ? nullptr : it->second;
}
int Checkpoint::open(const std::string& path) {
path_ = path;
const bool gguf = path.size() > 5 && path.compare(path.size() - 5, 5, ".gguf") == 0;
@@ -1704,7 +1730,8 @@ std::string ckpt_tensor_of(const SrcTensor& t) {
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
std::unordered_set<std::string>* hit) {
bool any = false;
for (const auto* list : { &w.pieces, &w.scales, &w.pq_pairs, &w.pq_theta, &w.pq_scale })
for (const auto* list : { &w.pieces, &w.scales, &w.pq_pairs, &w.pq_theta, &w.pq_scale,
&w.pq_meta })
for (const SrcTensor* t : *list) {
if (!t) continue;
const std::string n = ckpt_tensor_of(*t);
@@ -1777,7 +1804,7 @@ int paro_attach(Checkpoint& ck, CkptWeight* out, std::string* why) {
const SrcTensor* th = ck.find(base + ".theta");
const SrcTensor* cs = ck.find(base + ".channel_scales");
if (!pr || !th || !cs)
return refuse("'" + piece->name + "' is a ParoQuant MXFP4 weight and '" + base +
return refuse("'" + piece->name + "' is a ParoQuant weight and '" + base +
"' lacks its pairs, theta or channel_scales");
if (pr->rad_dtype != RAD_I16 || th->rad_dtype != RAD_F16 || cs->rad_dtype != RAD_F16 ||
pr->shape.size() != 2 || th->shape.size() != 2 || cs->shape.size() != 2 ||
@@ -2225,6 +2252,34 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&out->enc, "scale", RAD_F32, 1, 16);
}
} else if (dt == RAD_FP4E2M1 && scaled && ck.imports() == Checkpoint::Import::ParoM2) {
/* ParoQuant's M2XFP4: the MXFP4 planes byte for byte -- e2m1 codes, an e8m0 exponent per
* 32 of K -- plus the scheme's metadata byte a group (one per 32, four 2-bit subgroup
* multipliers), in the rotated basis the checkpoint trained, with the rotation beside them
* (paro_attach). Joined only along rows: every plane follows the pieces row by row. */
bool fits = d == 0 || out->pieces.size() == 1;
for (size_t k = 0; k < out->pieces.size() && fits; ++k) {
const SrcTensor* mt = ck.import_meta(out->pieces[k]->name);
fits = mt && out->scales[k] && out->scales[k]->rad_dtype == RAD_E8M0;
if (fits) out->pq_meta.push_back(mt);
}
if (!fits) {
out->pq_meta.clear();
out->why = "its M2XFP4 pieces are joined along a column, or a piece has no metadata "
"plane beside its exponents";
} else {
out->imported = true;
out->trivial = false;
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "m2xfp4");
rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&out->enc, "scale", RAD_E8M0, 1, 32);
rad_enc_add_plane(&out->enc, "meta", RAD_U8, 1, 32);
const int rc = paro_attach(ck, out, why);
if (rc != RAD_OK) return rc;
out->why = "it is ParoQuant M2XFP4, which rad-convert imports with its rotation tables "
"-- serve the container it writes";
}
} else if (dt == RAD_FP4E2M1 && scaled) {
/* Quark's MXFP4 byte for byte: codes and exponents are the planes of
* `fp4_e2m1*e8m0[1x32]`. Joined only along rows (gate and up). */
@@ -2890,6 +2945,31 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
}
return RAD_OK;
}
if (w.paro && std::strncmp(w.enc.plane[k].role, "meta", RAD_ENC_STR) == 0) {
/* The M2XFP4 grid's metadata byte a group, as stored: [N][K/32], one byte a group, the
* subgroup multipliers packed in it (subgroup s in bits [2s, 2s+2)). The checkpoint packs
* along N the way the plane does, so a row is a memcpy. */
int64_t base = 0;
for (size_t p = 0; p < w.pieces.size() && p < w.pq_meta.size(); ++p) {
const SrcTensor& m = *w.pq_meta[p];
const int64_t Np = w.pieces[p]->shape[0];
/* The pieces view is the logical [N, K] codes; one metadata byte covers 32 of K. */
const int64_t ng = w.pieces[p]->shape[1] / 32;
if (m.shape.size() != 2 || m.shape[0] != Np || m.shape[1] != ng)
return refuse(RAD_E_SHAPE, "'" + m.name + "' is not the [" + std::to_string(Np) +
", " + std::to_string(ng) + "] metadata plane of '" +
w.pieces[p]->name + "'; a stacked form it cannot be "
"sliced out of is refused rather than packed");
const int64_t lo = std::max(r0, base), hi = std::min(r0 + nr, base + Np);
if (hi > lo) {
std::memcpy(o, (const uint8_t*)m.data + (lo - base) * ng,
(size_t)((hi - lo) * ng));
o += (hi - lo) * ng;
}
base += Np;
}
return RAD_OK;
}
if (w.paro && std::strncmp(w.enc.plane[k].role, "t.", 2) == 0) {
/* A rotation table, built a row at a time: pairs converted from group-local to whole-row
* columns, angles widened, the channel scale inverted (the checkpoint multiplies the
+13 -4
View File
@@ -157,7 +157,8 @@ public:
* quantization_config at open. Gptq: AutoRound's `auto_round:auto_gptq` export and GPTQ v1
* (zero point stored less one). QuarkMx: Quark's MXFP4 (fp4 weights, per_group 32, e8m0
* scales, no per-layer overrides). ParoMx: ParoQuant's `paroquant_mxfp4` (Quark's codes and
* exponents in a rotated basis, rotations beside them). CtInt4, Nvfp4, CtFp8:
* exponents in a rotated basis, rotations beside them). ParoM2: ParoQuant's
* `paroquant_m2xfp4` (the same plus the m2xfp4 metadata byte a group). CtInt4, Nvfp4, CtFp8:
* compressed-tensors' pack-quantized int4 (symmetric, or asymmetric with a zero point), a
* release with an nvfp4-pack-quantized group, and one whose groups are all float-quantized FP8
* (detect_import). ModelOpt: NVIDIA ModelOpt's NVFP4, FP8, or both per layer
@@ -166,7 +167,7 @@ public:
* An unreadable form of these stays None, with the reason in import_refusal(). The
* quantization_config keys are then renamed `imported_quantization_config.*`, since they
* describe the tool, not a served format. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8,
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoM2, ParoI5, ParoI4, Nvfp4, CtFp8,
ModelOpt };
Import imports() const { return import_; }
const std::string& import_refusal() const { return import_why_; }
@@ -179,6 +180,10 @@ public:
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
std::string* why);
/* The metadata plane an imported `name` carries, when its form has one (ParoM2): [N, K/32] u8,
* one byte a group, as `weight_meta` ships it. Null for every other form. */
const SrcTensor* import_meta(const std::string& name) const;
private:
/* `owner` is the index's weight_map, if any: a tensor it places in another shard is skipped
* here. */
@@ -212,6 +217,8 @@ private:
bool ct_asym_ = false; /* CtInt4: the config states asymmetric weights */
/* import_piece's answers by name, so a weight resolved twice reuses its views. */
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
/* The metadata plane of an imported form that has one (ParoM2), by name. */
std::unordered_map<std::string, const SrcTensor*> imported_meta_;
};
/* ================================================================== logical weights */
@@ -253,9 +260,11 @@ struct CkptWeight {
/* ParoQuant MXFP4 (Import::ParoMx), also `imported`: written plane by plane through
* ckpt_plane_rows. Planes 0 and 1 are Quark's codes and exponents byte for byte; the rest are
* the "givens" transform's tables, built from `pq_pairs`/`pq_theta`/`pq_scale`, one set per
* piece (a row part: gate and up, or q, k and v, each rotated separately). */
* piece (a row part: gate and up, or q, k and v, each rotated separately). Import::ParoM2 is
* the same with a third plane before the tables, the m2xfp4 scheme's metadata byte a group,
* from `pq_meta`. */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale, pq_meta;
/* A weight-normalised tensor (RAD_MAP_WNORM): `pieces` is its direction v alone, and every
* element of v with first index i reads times wnorm_scale[i] = g_i / ||v_i||. Not trivial
* (the values change), so a recipe rule stores it. */
+5 -4
View File
@@ -635,7 +635,8 @@ so the activation takes the same rotation once a token.
of `a' = a cos t + b sin t, b' = b cos t - a sin t`. Each pair lies inside one scale group, so the
matrices belong to the weight: rad-convert composes them once in f64 and stores them as the
weight's `t.dense` table, which the layout hook (`r4d_rad_layout_gdense`) only moves. Consumers
are `gemm_nt_q` at `mxfp4a8` (`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out` i8).
are `gemm_nt_q` at `mxfp4a8` and `m2xfp4` (`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out`
i8).
- **`givens_rotate`** is the same rotation stage by stage with no quantiser, `y` in its own dtype
(f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`, whose GEMM serves any `M`
(rows past 64 run as chunks of 64).
@@ -645,9 +646,9 @@ A fused projection (gate|up, qkv|z) was rotated per checkpoint tensor, so the ac
`pairs` and `angle` stack each part's `stages` rows and `rscale` has one row per part. `gemm_nt_q`'s
`pb1` and `pb2` are the row bounds of the weight's parts: rows `[0, pb1)`, `[pb1, pb2)` and
`[pb2, N)` meet copies 0, 1 and 2 of the wide `a`/`a_scale`. `pb1` absent is one part; `pb2` absent
ends the second part at `N`. The `mxfp4a8` rows and the asymmetric 4- and 5-bit rows read them;
host rows that do not (libavx) refuse a call that names one rather than contract against the wrong
copy.
ends the second part at `N`. The `mxfp4a8` and `m2xfp4` rows and the asymmetric 4- and 5-bit rows
read them; host rows that do not (libavx) refuse a call that names one rather than contract against
the wrong copy.
### Int8 and gated fp8 fusions (device-only)
+38 -16
View File
@@ -608,40 +608,62 @@ extern "C" void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws,
// ============================================================== the plugin ABI entry point
extern "C" int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs* a, RadStream s) {
GemmOps g;
/* No parts: the m2xfp4 declare makes none, so gemm_ops refuses pb1/pb2, as libref does. */
int rc = gemm_ops(a, &g, 1);
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
if (g.M > r4d_gemm_m2xfp4a8_decode_max_m() || g.N > R4D_M2D_MAX_N) return R4D_NO(RAD_E_SHAPE);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
if (rc != RAD_OK) return rc;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order.
const long meta = r4d_addr(g.b) + (long)g.N * g.K / 2;
R4D_TRY("gemm_m2xfp4a8_decode",
m2d_launch(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), meta,
r4d_addr(g.bref), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, t.ks, t.bk, t.nt,
as_group, as_rs, (long)(uintptr_t)s, (long)(uintptr_t)a->scratch,
(long)a->scratch_bytes, (int)g.K, (int)g.N, (int)g.N));
const long long kb = (g.K + 127) / 128;
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order: a part of
// a partitioned weight (mx_parts) windows it at n0 as it does the exponent plane, and the codes
// at n0 * K / 2.
const long meta0 = (long)g.N * g.K / 2;
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
R4D_TRY("gemm_m2xfp4a8_decode",
m2d_launch(r4d_addr(g.a) + p * g.K, r4d_addr(g.ascale) + (long)(p * kb * 4),
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
r4d_addr(g.b) + meta0 + n0, r4d_addr(g.bref) + n0,
r4d_addr(g.y) + n0 * 2,
(int)g.M, (int)g.K, (int)np, t.ks, t.bk, t.nt, as_group, as_rs,
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes,
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N));
}
return RAD_OK;
}
/* The op's scratch size. A narrower M can split wider than the band's widest M, so the size is the
* widest split over the band times the widest M, an upper bound for every launch. */
* widest split over the band times the widest M, an upper bound for every launch. Parts of a
* partitioned weight split at their own N and run in turn sharing the scratch, so the bound is the
* largest part's. */
extern "C" int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
const long long K = r4d_geti_or(a, "K", 0);
if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_m2xfp4a8_decode_max_m()) return 0;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
int ks = 1;
for (int m = 1; m <= (int)M; ++m) {
const int k = m2d_plan(m, (int)K, (int)N, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
long long bound[4];
mx_part_bounds(N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound);
int64_t worst = 0;
for (int i = 0; i < 3; ++i) {
const long long np = bound[i + 1] - bound[i];
if (np < 16) continue;
int ks = 1;
for (int m = 1; m <= (int)M; ++m) {
const int k = m2d_plan(m, (int)K, (int)np, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
}
const int64_t b = (int64_t)m2d_partial_bytes((int)M, (int)np, ks);
if (b > worst) worst = b;
}
return (int64_t)m2d_partial_bytes((int)M, (int)N, ks);
return worst;
}
+24 -12
View File
@@ -325,37 +325,49 @@ extern "C" void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws,
}
// ============================================================== the plugin ABI entry point
// The row-major activation is re-tiled into the op's scratch and the GEMM reads it there.
// The row-major activation is re-tiled into the op's scratch and the GEMM reads it there. For a
// partitioned weight (mx_parts), each part's activation copy is re-tiled and multiplied in turn.
extern "C" int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs* a, RadStream s) {
GemmOps g;
/* No parts: the m2xfp4 declare makes none, so gemm_ops refuses pb1/pb2, as libref does. */
int rc = gemm_ops(a, &g, 1);
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
/* The per-row reference exponent is required, as in r4d_rad_gemm_mxfp4a8_m64. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
if (g.K % R4D_M2T_KUNIT) return R4D_NO(RAD_E_SHAPE);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
if (rc != RAD_OK) return rc;
const long long slab = r4d_m2xfp4a8_tile_a_bytes((int)g.M, (int)g.K);
if (!a->scratch || a->scratch_bytes < slab) return R4D_NO(RAD_E_INVAL);
R4dMxTileCfg t;
r4d_cfg_mxfp4_tiled(a, &t);
const long kb = (long)((g.K + 127) / 128);
const long at = (long)(uintptr_t)a->scratch;
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order.
const long meta = r4d_addr(g.b) + (long)g.N * g.K / 2;
R4D_TRY("gemm_m2xfp4a8_tiled",
r4d_m2xfp4a8_tile_a(r4d_addr(g.a), at, (int)g.M, (int)g.K, (long)(uintptr_t)s, (int)g.K);
r4d_gemm_m2xfp4a8_tiled(at, r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), meta,
r4d_addr(g.bref), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N,
t.tn, as_group, as_rs, (long)(uintptr_t)s, (int)g.N, (int)g.N));
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order; a part
// windows it at n0, as it does the exponent plane.
const long meta0 = (long)g.N * g.K / 2;
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
R4D_TRY("gemm_m2xfp4a8_tiled",
r4d_m2xfp4a8_tile_a(r4d_addr(g.a) + p * g.K, at, (int)g.M, (int)g.K,
(long)(uintptr_t)s, (int)(mp.lda ? mp.lda : g.K));
r4d_gemm_m2xfp4a8_tiled(at, r4d_addr(g.ascale) + p * kb * 4,
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
r4d_addr(g.b) + meta0 + n0, r4d_addr(g.bref) + n0,
r4d_addr(g.y) + n0 * 2, (int)g.M, (int)g.K, (int)np, t.tn,
as_group, as_rs, (long)(uintptr_t)s, (int)g.N, (int)g.N));
}
return RAD_OK;
}
/* The op's scratch, sized at the band's widest M: the fragment-tiled activation in whole 16-row
* fragments. */
* fragments. One copy serves every part: parts run in order on the op's stream, so a re-tile
* cannot overtake the previous part's GEMM. */
extern "C" int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0);
return (int64_t)r4d_m2xfp4a8_tile_a_bytes((int)M, (int)K);
+27 -3
View File
@@ -977,12 +977,17 @@ extern "C" int r4d_rad_relayout_mxfp4_gated(const RadParam* p, int n_p, int oper
* bounds the fold: d >= 0 for every block, so the largest e4m3 a table cell holds is the x1.75
* magnitude 10.5 scaled by 2^-d, a normal at every d >= 0.
*
* Anything else is refused, a transform included: this kernel library decodes one scheme, and a
* weight whose meta plane said something else would decode to other numbers. */
* Anything else is refused: this kernel library decodes one scheme, and a weight whose meta plane
* said something else would decode to other numbers.
*
* A rotated weight (ParoQuant's M2XFP4) carries the same three planes in the basis its "givens"
* transform names, with the rotation's tables beside them -- the rotated MXFP4 weight's shape plus
* the meta plane. The GEMM reads the planes as for an unrotated weight; the rotation is applied to
* the activation (givens_dense_quant), whose tables are separate weight operands. */
namespace {
/* The scheme's three planes, whichever kind of weight carries them. */
bool m2_planes(const RadEncoding* enc) {
if (!enc || !rad_enc_is(enc, "m2xfp4")) return false;
if (enc->transform[0] || enc->n_planes != 3) return false;
if (enc->plane[0].dtype != RAD_FP4E2M1 || enc->plane[0].block[0] != 1 ||
enc->plane[0].block[1] != 1)
return false;
@@ -997,6 +1002,23 @@ bool m2_planes(const RadEncoding* enc) {
return true;
}
/* A rotated one: the three planes in the basis of a "givens" transform, whose tables are views of
* the weight's planes. Only the presence and the dtype of the tables is checked here (the arch
* declares them as operands the rotation op reads); any other transform would decode to other
* numbers, so it is refused. */
bool m2_paro_enc(const RadEncoding* enc, long long K) {
if (!enc || std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
if (enc->n_planes < 6 || !rad_enc_valid(enc) || !m2_planes(enc)) return false;
const int p = rad_enc_find(enc, "t.pairs"), an = rad_enc_find(enc, "t.angle"),
sc = rad_enc_find(enc, "t.scale");
if (p < 0 || an < 0 || sc < 0) return false;
if (enc->plane[p].dtype != RAD_I32 || enc->plane[an].dtype != RAD_F32 ||
enc->plane[sc].dtype != RAD_F32)
return false;
/* The quantiser rotates whole groups of 128 columns, one scale per group. */
return K % 128 == 0 && enc->plane[p].extent[1] == K;
}
int m2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out, WGeom* gout) {
if (!out || !pl) return RAD_E_INVAL;
@@ -1005,6 +1027,8 @@ int m2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
if (rc != RAD_OK) return rc;
if (g.group != R4D_MXFP4_GROUP || g.K % 16) return RAD_E_SHAPE;
if (!m2_planes(enc)) return RAD_E_DTYPE;
const bool plain = !enc->transform[0] && enc->n_planes == 3;
if (!plain && !m2_paro_enc(enc, g.K)) return RAD_E_DTYPE;
if (gout) *gout = g;
const long long nblk = g.K / R4D_MXFP4_GROUP;
if (operand == Q_BSCALE || operand == Q_BREF) {
+31 -16
View File
@@ -4867,13 +4867,19 @@ static void mxfp4a8_m_invariant(const Plugin& pl, const char* row, int64_t N, in
* mxfp4 row's plus the table's accepted k = 3 rounding: a quarter of the weights at up to 2^-4.4
* each is about 1.2% of a whole dot, so 4e-2 holds the same margin the 1e-2 does there. The
* relayout is exercised for real: the weight operand takes codes and meta, and the stored blob the
* launch reads is this hook's output. The output starts as NaN, as there. */
* launch reads is this hook's output. The output starts as NaN, as there. Parts (ParoQuant's
* rotated M2XFP4): weight rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy of the
* activation, as at mxfp4a8. */
static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K,
int tn, bool ablk = false, std::vector<RadParam> extra = {}) {
int tn, bool ablk = false, std::vector<RadParam> extra = {},
int64_t pb1 = 0, int64_t pb2 = 0) {
if (!sel(row)) return;
const PartCut cut(N, pb1, pb2);
const int parts = cut.parts;
char nm[160];
std::string ex;
for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival);
if (parts > 1) ex += " parts=" + std::to_string(parts);
std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld tn=%d%s%s", row, (long long)M,
(long long)N, (long long)K, tn, ablk ? " ascale=row x 128" : "", ex.c_str());
const RadKernelInfo* r = find(pl, row);
@@ -4906,20 +4912,21 @@ static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64
}
const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1;
std::vector<uint8_t> ha((size_t)(M * K));
std::vector<float> av((size_t)(M * K)), as((size_t)(M * asc));
const int64_t PK = parts * K, PA = parts * asc; /* a row of `a`, and of its scale */
std::vector<uint8_t> ha((size_t)(M * PK));
std::vector<float> av((size_t)(M * PK)), as((size_t)(M * PA));
for (int64_t i = 0; i < M; ++i) {
for (int64_t c = 0; c < asc; ++c) {
const uint32_t h = st_mix32((uint32_t)(i * asc + c) ^ 0xa5u);
as[(size_t)(i * asc + c)] =
for (int64_t c = 0; c < PA; ++c) {
const uint32_t h = st_mix32((uint32_t)(i * PA + c) ^ 0xa5u);
as[(size_t)(i * PA + c)] =
ablk ? ((i + c) % 11 == 5 ? 0.0f : 0.002f * (float)(1 + h % 97))
: 0.0125f * (float)(1 + h % 5);
}
for (int64_t k = 0; k < K; ++k) {
const bool zero = ablk && as[(size_t)(i * asc + k / 128)] == 0.0f;
for (int64_t k = 0; k < PK; ++k) {
const bool zero = ablk && as[(size_t)(i * PA + (k / K) * asc + (k % K) / 128)] == 0.0f;
const float v = zero ? 0.0f : mxfp4_act(i, k, 0x3cu);
rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, v);
av[(size_t)(i * K + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * K + k);
rad_store_f32(ha.data(), RAD_F8E4M3, i * PK + k, v);
av[(size_t)(i * PK + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * PK + k);
}
}
std::vector<uint16_t> hy((size_t)(M * N), 0x7fc0); /* bf16 NaN */
@@ -4937,8 +4944,8 @@ static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64
st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice);
st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_a, RAD_F8E4M3, { M, K }),
ablk ? T(d_s, RAD_F32, { M, asc }) : T(d_s, RAD_F32, { M }),
T(d_a, RAD_F8E4M3, { M, PK }),
ablk ? T(d_s, RAD_F32, { M, PA }) : T(d_s, RAD_F32, { M }),
T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }),
T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(d_r, RAD_U8, { (int64_t)wr.size() }),
};
@@ -4946,6 +4953,8 @@ static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "m2xfp4") };
if (tn) ps.push_back(PI("tn", tn));
if (pb1) ps.push_back(PI("pb1", pb1));
if (pb2) ps.push_back(PI("pb2", pb2));
for (const RadParam& p : extra) ps.push_back(p);
RadArgs a;
std::memset(&a, 0, sizeof(a));
@@ -4974,6 +4983,7 @@ static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64
double num = 0, den = 0;
for (int64_t i = 0; i < M; ++i)
for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) {
const int pt = cut.part_of(n);
double acc = 0;
for (int64_t k = 0; k < K; ++k) {
const uint8_t meta = p.data[(size_t)im][(size_t)(n * nblk + k / 32)];
@@ -4982,8 +4992,8 @@ static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64
(double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) *
(1.0 + kk / 4.0) *
(double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32);
acc += (double)av[(size_t)(i * K + k)] * w *
(ablk ? (double)as[(size_t)(i * asc + k / 128)] : 1.0);
acc += (double)av[(size_t)(i * PK + pt * K + k)] * w *
(ablk ? (double)as[(size_t)(i * PA + pt * asc + k / 128)] : 1.0);
}
if (!ablk) acc *= (double)as[(size_t)i];
const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc;
@@ -28215,17 +28225,22 @@ static void device_phase(const Plugin& pl) {
{ PI("ks", ks), PI("bk", bk), PI("nt", nt) });
}
/* The M2XFP4 rows: the decode band's rule and band edges, the tiled row at both widths and
* past the tn crossover, and both activation grids, at the three-plane encoding. */
* past the tn crossover, both activation grids, and parts (ParoQuant's rotated M2XFP4) --
* the same spread the OCP rows get, at the three-plane encoding. */
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 272, 640, 0, false);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 272, 640, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 40, 400, 2560, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 128, 512, 2560, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 5, 1040, 576, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 96, 14336, 640, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 400, 2560, 0, true, {}, 128);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 40, 512, 2560, 0, true, {}, 128, 384);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 40, 272, 640, 2, false);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 400, 640, 4, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 2100, 512, 2560, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 272, 576, 2, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 400, 640, 2, true, {}, 192);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 34816, 5120, 0, true, {}, 17408);
gemm_case(pl, "gemm_w4a8_tiled", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4);
gemm_case(pl, "gemm_w8a8_tiled", "w8a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K, 256*(K/128)*2);
gemm_case(pl, "gemm_w4a8_prefill", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4);
+40 -19
View File
@@ -16,6 +16,7 @@
* end of this file: each answers dtype m2xfp4 here and hands every other dtype, unchanged, to the
* hook the row had (ref_gemm.cpp, ref_shapes.cpp, ref_planes.h).
*/
#include <algorithm>
#include <cstring>
#include <vector>
#include "ref_common.h"
@@ -27,43 +28,59 @@ using namespace ref;
namespace {
/* The plain scheme as libquant writes it: no transform; codes [1 x 1], scale and meta [1 x 32]. */
/* The scheme as libquant writes it: codes [1 x 1], scale and meta [1 x 32]. A rotated weight
* (ParoQuant) carries the same three planes in the basis its "givens" transform names, with the
* rotation's tables beside them; the rotation is the activation's, so the planes are read as they
* are. */
bool m2_enc_planes(const RadEncoding* enc) {
if (!enc || !rad_enc_is(enc, "m2xfp4") || enc->transform[0] || enc->n_planes != 3)
return false;
if (!enc || !rad_enc_is(enc, "m2xfp4")) return false;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
const RadEncPlane* mt = rad_enc_plane(enc, "meta");
return enc->plane[0].kind == RAD_PLANE_TILED && enc->plane[0].dtype == RAD_FP4E2M1 &&
enc->plane[0].block[0] == 1 && enc->plane[0].block[1] == 1 && sc && mt &&
sc->kind == RAD_PLANE_TILED && sc->dtype == RAD_E8M0 && sc->block[0] == 1 &&
sc->block[1] == 32 && mt->kind == RAD_PLANE_TILED && mt->dtype == RAD_U8 &&
mt->block[0] == 1 && mt->block[1] == 32;
const bool planes = enc->plane[0].kind == RAD_PLANE_TILED &&
enc->plane[0].dtype == RAD_FP4E2M1 && enc->plane[0].block[0] == 1 &&
enc->plane[0].block[1] == 1 && sc && mt && sc->kind == RAD_PLANE_TILED &&
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == 32 &&
mt->kind == RAD_PLANE_TILED && mt->dtype == RAD_U8 &&
mt->block[0] == 1 && mt->block[1] == 32;
if (!planes) return false;
if (!enc->transform[0]) return enc->n_planes == 3;
return enc->n_planes >= 6 && rad_enc_plane(enc, "t.pairs") && rad_enc_plane(enc, "t.angle") &&
rad_enc_plane(enc, "t.scale");
}
/* Each product is one f32 multiply and each output one f32 accumulation in k order: the exact
* decode's own arithmetic, since the multipliers take the codes off the integer grid an mxfp4
* group sub-sum would use. */
* group sub-sum would use.
*
* Parts (`pb1`, `pb2`), a rotated (ParoQuant) fused projection's pieces, as gemm_ntq_impl's mxfp4
* arm reads them (ref_gemm.cpp): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each meet their own
* copy of the activation, side by side in a row of `a` ([M, parts * K]) and of its scale
* ([M, parts * K / 128]). 0 omits a bound. */
int m2_gemm(const RadArgs* a) {
if (a->n_t < 5) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
const RadTensor *as_ = t_in(a, 1), *bs_ = t_in(a, 3);
if (!A->data || !B->data || !Y->data) return RAD_E_INVAL;
if (t_in(a, 5)) return RAD_E_UNSUPPORTED; /* a_sum belongs to the asym grids */
/* Parts (pb1/pb2) are the rotated grids'; a plain m2xfp4 linear has none, and a case carrying
* them is declined rather than answered unsplit. */
if (p_int(a, "pb1", 0) > 0 || p_int(a, "pb2", 0) > 0) return RAD_E_UNSUPPORTED;
if (A->dtype != RAD_F8E4M3 || B->dtype != RAD_U8 || B->rank != 1) return RAD_E_DTYPE;
if (!as_ || !bs_ || bs_->dtype != RAD_E8M0 || bs_->rank < 2) return RAD_E_DTYPE;
const int64_t K = p_int(a, "K", 0), N = p_int(a, "N", 0);
if (K <= 0 || K % 32 || N <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
const int64_t kb = K / 32, akb = (K + 127) / 128;
if (numel(A) < M * K || numel(B) != N * (K / 2 + kb) || numel(bs_) < N * kb ||
numel(as_) < M * akb)
const int64_t pb1 = p_int(a, "pb1", 0), pb2 = p_int(a, "pb2", 0);
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
if (parts > 1 && (e1 % 16 || e2 % 16 || A->rank < 2 || A->shape[A->rank - 1] != parts * K))
return RAD_E_SHAPE;
const int64_t ars = row_stride(A, K), acs = laststride(A);
const int64_t srs = row_stride(as_, akb), scs = laststride(as_);
const int64_t kb = K / 32, akb = (K + 127) / 128;
if (numel(A) < M * parts * K || numel(B) != N * (K / 2 + kb) || numel(bs_) < N * kb ||
numel(as_) < M * parts * akb)
return RAD_E_SHAPE;
const int64_t ars = row_stride(A, parts * K), acs = laststride(A);
const int64_t srs = row_stride(as_, parts * akb), scs = laststride(as_);
const int64_t brs = row_stride(bs_, kb);
const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y);
const uint8_t* meta0 = (const uint8_t*)B->data + N * (K / 2);
@@ -72,6 +89,8 @@ int m2_gemm(const RadArgs* a) {
const uint8_t* codes = (const uint8_t*)B->data + n * (K / 2);
const uint8_t* meta = meta0 + n * kb;
const uint8_t* expe = (const uint8_t*)bs_->data + n * brs;
const int64_t part = n < e1 ? 0 : (n < e2 ? 1 : 2);
const int64_t ak0 = part * K, sk0 = part * akb; /* this part's copy of `a` */
/* The weight row decoded once, so the meta and exponent reads are not repeated per
* activation row. */
std::vector<float> w((size_t)K);
@@ -86,7 +105,8 @@ int m2_gemm(const RadArgs* a) {
const int64_t ab = m * ars;
float acc = 0.0f;
for (int64_t k = 0; k < K; ++k)
acc += ldt(A, ab + k * acs) * ldt(as_, m * srs + (k >> 7) * scs) * w[(size_t)k];
acc += ldt(A, ab + (ak0 + k) * acs) * ldt(as_, m * srs + (sk0 + (k >> 7)) * scs) *
w[(size_t)k];
stt(Y, m * ys_r + n * ys_c, acc);
}
}
@@ -111,7 +131,8 @@ int m2_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
}
/* The weight operand is codes and meta, concatenated; the scale and reference operands are the
* exponent plane, stored as it is. Any other encoding is refused, a transform included. */
* exponent plane, stored as it is. Any other encoding is refused, a transform other than
* "givens" included. */
int m2_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
const long long group = rad_param_geti(p, n_p, "group", 0);
+109
View File
@@ -1476,6 +1476,115 @@ TEST(a_paroquant_mxfp4_weight_carries_its_rotations_as_parts) {
}
}
/* ParoQuant M2XFP4 is the MXFP4 form plus one metadata byte a group (`weight_meta`, [N, K/32] u8):
* the three planes of the `m2xfp4` scheme byte for byte, joined row by row, with the rotations
* beside them as for ParoMx. A piece without its metadata plane is refused, and so is a grid the
* import does not read. */
TEST(a_paroquant_m2xfp4_weight_carries_its_meta_plane_and_rotations) {
const int64_t K = 128, S = 2, N = 16;
uint32_t rng = 777;
auto next = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; };
auto u8s = [&](const std::string& n, int64_t cols, uint32_t lo, uint32_t span) {
T t{ n, "U8", { N, cols }, {} };
for (int64_t i = 0; i < N * cols; ++i) t.bytes.push_back((uint8_t)(lo + next() % span));
return t;
};
auto pairs = [&](const std::string& n) {
T t{ n, "I16", { S, K }, {} };
for (int64_t st = 0; st < S; ++st) {
std::vector<int16_t> perm((size_t)K);
for (int64_t i = 0; i < K; ++i) perm[(size_t)i] = (int16_t)i;
for (int64_t i = K - 1; i > 0; --i) std::swap(perm[(size_t)i], perm[next() % (i + 1)]);
for (int64_t i = 0; i < K; ++i) {
t.bytes.push_back((uint8_t)(perm[(size_t)i] & 0xff));
t.bytes.push_back((uint8_t)(perm[(size_t)i] >> 8));
}
}
return t;
};
auto f16s = [&](const std::string& n, std::vector<int64_t> shape, float lo, float hi) {
T t{ n, "F16", shape, {} };
int64_t cnt = 1;
for (int64_t d : shape) cnt *= d;
for (int64_t i = 0; i < cnt; ++i) {
const uint16_t h = rad_f32_to_f16(lo + (hi - lo) * (float)(next() % 1000) / 1000.0f);
t.bytes.push_back((uint8_t)(h & 0xff));
t.bytes.push_back((uint8_t)(h >> 8));
}
return t;
};
std::vector<T> ts;
for (const char* b : { "g", "u" }) {
const std::string n = b;
ts.push_back(u8s(n + ".weight", K / 2, 0, 256));
ts.push_back(u8s(n + ".weight_scale", K / 32, 122, 5));
ts.push_back(u8s(n + ".weight_meta", K / 32, 0, 256));
ts.push_back(pairs(n + ".pairs"));
ts.push_back(f16s(n + ".theta", { S, K / 2 }, -3.0f, 3.0f));
ts.push_back(f16s(n + ".channel_scales", { 1, K }, 0.5f, 2.0f));
}
const std::string cfg = "{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":"
"\"paroquant_m2xfp4\",\"format\":\"m2xfp4\",\"bits\":4,\"group_size\":128,"
"\"mx_block\":32,\"subgroup\":8,\"krot\":2}}";
Checkpoint ck;
REQUIRE_EQ(ck.open(write_checkpoint(ts, cfg)), RAD_OK);
CHECK(ck.imports() == Checkpoint::Import::ParoM2);
Program prog;
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "g.weight", "u.weight" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
REQUIRE(w.paro);
CHECK(w.imported && !w.trivial);
REQUIRE(rad_enc_valid(&w.enc));
CHECK(rad_enc_is(&w.enc, "m2xfp4"));
CHECK_EQ(std::string(w.enc.transform), std::string("givens"));
CHECK_EQ(rad_enc_givens_parts(&w.enc), (int64_t)2);
CHECK_EQ(w.rows, (int64_t)2 * N);
REQUIRE_EQ(w.enc.n_planes, 8);
CHECK_EQ(std::string(w.enc.plane[2].role), std::string("meta"));
CHECK_EQ(w.enc.plane[2].dtype, (uint32_t)RAD_U8);
CHECK_EQ(w.enc.plane[2].block[1], (int64_t)32);
CHECK(ckpt_reads_any(w, { "u.weight_meta" }));
// codes, exponents and metadata are the checkpoint's bytes, gate's rows then up's
const std::vector<std::vector<uint8_t>> pl = read_planes(w);
REQUIRE(!pl.empty());
for (int k = 0; k < 3; ++k) {
const T& g = ts[(size_t)k];
const T& u = ts[(size_t)(6 + k)];
CHECK_EQ(std::memcmp(pl[(size_t)k].data(), g.bytes.data(), g.bytes.size()), 0);
CHECK_EQ(std::memcmp(pl[(size_t)k].data() + g.bytes.size(), u.bytes.data(), u.bytes.size()), 0);
}
// the rotation tables follow, as ParoMx's: part 1's stage 0 pairs in whole-row columns
REQUIRE_EQ(std::string(w.enc.plane[3].role), std::string("t.pairs"));
const int32_t* tp = (const int32_t*)pl[3].data();
for (int64_t c = 0; c < K; ++c)
CHECK_EQ(tp[S * K + c], (int32_t)(*(const int16_t*)(ts[9].bytes.data() + 2 * c)));
// a piece without its metadata plane is refused by name
{
std::vector<T> no_meta;
for (const T& t : ts)
if (t.name != "u.weight_meta") no_meta.push_back(t);
Checkpoint c2;
REQUIRE_EQ(c2.open(write_checkpoint(no_meta, cfg)), RAD_OK);
CkptWeight w2;
why.clear();
CHECK(ckpt_resolve(c2, prog, "gu", false, &w2, &why) != RAD_OK);
CHECK(why.find("u.weight_meta") != std::string::npos);
}
// another subgroup width is not the grid this reads
{
std::string other = cfg;
other.replace(other.find("\"subgroup\":8"), 12, "\"subgroup\":4");
Checkpoint c3;
REQUIRE_EQ(c3.open(write_checkpoint(ts, other)), RAD_OK);
CHECK(c3.imports() == Checkpoint::Import::None);
CHECK(c3.import_refusal().find("M2XFP4") != std::string::npos);
}
}
/* ParoQuant int5-bitplane: low nibbles AWQ-packed along N (qweight [K, N/8], eight columns per
* word in the order 0,2,4,6,1,3,5,7), a fifth-bit plane (qweight_hi [K, N/32], bit n % 32), and the
* same two packings for the zero points. The logical [N, K] weight becomes u5 codes (a bit stream
+33 -15
View File
@@ -10,9 +10,9 @@
* 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. The last case hands the
* planes to libref's gemm_nt_q row at m2xfp4 (ref_m2xfp4.cpp) and holds its product to the same
* hand decode.
* beat adaptive, its planes decoding bit for bit as the equation does. The last two cases hand the
* planes to libref's gemm_nt_q row at m2xfp4 (ref_m2xfp4.cpp) and hold its product to the same
* hand decode, the second over a fused projection's parts.
*/
#include "quant_fixture.h"
@@ -339,9 +339,9 @@ TEST(m2xfp4_wide_bias_sweep_contains_the_narrow_one_and_round_trips_bit_exact) {
/* libref's gemm_nt_q row at m2xfp4 over the quantiser's own planes: its layout hook takes codes and
* meta for the weight and the exponent plane as stored, its relayout concatenates the two, and
* the product is the hand decode's against an exact e4m3 activation and its per-128 scales,
* summed in double. N = 40 and M = 13 are not multiples of anything; K = 384 is three activation
* scale blocks. */
TEST(m2xfp4_libref_gemm_reads_the_planes_as_the_decode_does) {
* summed in double. With parts (pb1/pb2), weight rows [0, pb1), [pb1, pb2) and [pb2, N) each read
* their own copy of the activation, side by side in a row of `a`. */
static void libref_m2xfp4_gemm(int64_t M, int64_t N, int64_t K, int64_t pb1, int64_t pb2) {
NEED_LIBQUANT();
const std::string lib = home() + "/kernels/libref.so";
void* so = dlopen(lib.c_str(), RTLD_NOW | RTLD_LOCAL);
@@ -354,7 +354,10 @@ TEST(m2xfp4_libref_gemm_reads_the_planes_as_the_decode_does) {
if (std::strcmp(at(i)->name, "ref_gemm_nt_q") == 0) k = at(i);
REQUIRE(k && k->layout && k->relayout && k->launch);
const int64_t M = 13, N = 40, K = 384, kb = K / 32, akb = K / 128;
const int64_t kb = K / 32, akb = K / 128;
const int64_t e1 = pb1 > 0 ? pb1 : N, e2 = pb2 > 0 ? pb2 : N;
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
const int64_t PK = parts * K, PA = parts * akb; /* a row of `a`, and of its scale */
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
Opts o;
@@ -377,6 +380,8 @@ TEST(m2xfp4_libref_gemm_reads_the_planes_as_the_decode_does) {
};
Opts g;
g.i("M", M).i("N", N).i("K", K).i("group", 32).s("dtype", "m2xfp4");
if (pb1 > 0) g.i("pb1", pb1);
if (pb2 > 0) g.i("pb2", pb2);
const RadTensor pl[2] = { tensor(w.planes[0].data(), RAD_FP4E2M1, { N, K }),
tensor(w.planes[2].data(), RAD_U8, { N, kb }) };
const RadTensor sp = tensor(w.planes[1].data(), RAD_E8M0, { N, kb });
@@ -390,13 +395,13 @@ TEST(m2xfp4_libref_gemm_reads_the_planes_as_the_decode_does) {
(int)RAD_OK);
/* integer codes in [-13, 13], which e4m3 holds exactly */
std::vector<uint8_t> a((size_t)(M * K));
std::vector<float> as((size_t)(M * akb)), y((size_t)(M * N), NAN);
for (int64_t i = 0; i < M * K; ++i)
std::vector<uint8_t> a((size_t)(M * PK));
std::vector<float> as((size_t)(M * PA)), y((size_t)(M * N), NAN);
for (int64_t i = 0; i < M * PK; ++i)
rad_store_f32(a.data(), RAD_F8E4M3, i, (float)((i * 7) % 27 - 13));
for (int64_t i = 0; i < M * akb; ++i) as[(size_t)i] = 0.003f * (float)(1 + i % 5);
RadTensor t[7] = { tensor(a.data(), RAD_F8E4M3, { M, K }),
tensor(as.data(), RAD_F32, { M, akb }),
for (int64_t i = 0; i < M * PA; ++i) as[(size_t)i] = 0.003f * (float)(1 + i % 5);
RadTensor t[7] = { tensor(a.data(), RAD_F8E4M3, { M, PK }),
tensor(as.data(), RAD_F32, { M, PA }),
tensor(b.data(), RAD_U8, { lay.bytes }),
sp,
tensor(y.data(), RAD_F32, { M, N }),
@@ -412,10 +417,12 @@ TEST(m2xfp4_libref_gemm_reads_the_planes_as_the_decode_does) {
double err = 0, mag = 0;
for (int64_t m = 0; m < M; ++m)
for (int64_t n = 0; n < N; ++n) {
const int64_t pt = n < e1 ? 0 : (n < e2 ? 1 : 2);
double r = 0;
for (int64_t c = 0; c < K; ++c)
r += (double)rad_load_f32(a.data(), RAD_F8E4M3, m * K + c) *
(double)as[(size_t)(m * akb + c / 128)] * (double)wd[(size_t)(n * K + c)];
r += (double)rad_load_f32(a.data(), RAD_F8E4M3, m * PK + pt * K + c) *
(double)as[(size_t)(m * PA + pt * akb + c / 128)] *
(double)wd[(size_t)(n * K + c)];
err = std::max(err, std::fabs((double)y[(size_t)(m * N + n)] - r));
mag = std::max(mag, std::fabs(r));
}
@@ -424,4 +431,15 @@ TEST(m2xfp4_libref_gemm_reads_the_planes_as_the_decode_does) {
dlclose(so);
}
/* N = 40 and M = 13 are not multiples of anything; K = 384 is three activation scale blocks. */
TEST(m2xfp4_libref_gemm_reads_the_planes_as_the_decode_does) {
libref_m2xfp4_gemm(13, 40, 384, 0, 0);
}
/* A rotated fused projection's parts, two and three of them, at 16-row bounds. */
TEST(m2xfp4_libref_gemm_gives_each_part_its_own_activation) {
libref_m2xfp4_gemm(13, 48, 384, 16, 0);
libref_m2xfp4_gemm(13, 48, 384, 16, 32);
}
RAD_TEST_MAIN()