From 3402acf82de4fb5dcbeefd226c29ca01e912eb45 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Wed, 7 Oct 2026 23:52:17 +0000 Subject: [PATCH] format: import ParoQuant MXFP4 checkpoints (givens transform with parts, per-row fp8 scale) quant_method paroquant_mxfp4 is Quark's MXFP4 planes in a rotated basis plus z-lab's learned Givens rotations. rad-convert reads the codes and exponents byte for byte and builds the encoding's givens tables (t.pairs/t.angle/t.scale) from pairs/theta/channel_scales; a fused gate|up or qkv|z gets one set of tables a checkpoint tensor (new t.part table). The core decoder undoes the per-part rotation. fp8 tensors with one f32 scale a row are read exactly. --- abi/rad_encoding.h | 29 ++++++- core/format/checkpoint.cpp | 169 +++++++++++++++++++++++++++++++++++-- core/format/checkpoint.h | 12 ++- core/format/encoding.cpp | 76 ++++++++++++++--- tests/checkpoint_test.cpp | 150 ++++++++++++++++++++++++++++++++ tests/encoding_test.cpp | 46 ++++++++++ 6 files changed, 458 insertions(+), 24 deletions(-) diff --git a/abi/rad_encoding.h b/abi/rad_encoding.h index 49538c1e..f14f7ad3 100644 --- a/abi/rad_encoding.h +++ b/abi/rad_encoding.h @@ -73,6 +73,12 @@ * [S x cols] lists stage s's pairs as (pairs[s][2p], pairs[s][2p+1]), TABLE "t.angle" * f32 [S x cols/2] their angles, and a row vector's pair (a, b) at angle t becomes * (a cos t + b sin t, b cos t - a sin t). ParoQuant's scaled pairwise rotation. + * A weight whose row PARTS were rotated independently (a fused gate_up, a fused + * q|k|v: each projection has its own rotation) carries P parts: TABLE "t.part" i32 + * [1 x P] holds the END ROW (exclusive) of each part, and the other tables stack the + * parts in order -- t.pairs and t.angle S rows a part (P*S rows), t.scale one row a + * part (P rows). Without "t.part" the weight is one part. The stages of a part are + * applied in table order, and a part's pairs address columns of the whole row. * * Pure C, header-only, like the rest of abi/. */ @@ -213,6 +219,15 @@ static inline int64_t rad_enc_fwht(const RadEncoding* e) { return (int64_t)n; } +/* The number of independently rotated row parts of a "givens" weight: the width of its "t.part" + * table, or 1 without one. 0 when the table is malformed. */ +static inline int64_t rad_enc_givens_parts(const RadEncoding* e) { + const int i = rad_enc_find(e, "t.part"); + if (i < 0) return 1; + return e->plane[i].kind == RAD_PLANE_TABLE && e->plane[i].extent[0] == 1 && + e->plane[i].extent[1] >= 1 ? e->plane[i].extent[1] : 0; +} + /* Byte-for-byte equality, which is what two encodings agreeing means: the strings are * zero-padded by construction, so there is nothing a memcmp could see that a reader cannot. */ static inline int rad_enc_equal(const RadEncoding* a, const RadEncoding* b) { @@ -329,8 +344,18 @@ static inline int rad_enc_valid(const RadEncoding* e) { if (!t[0]) return 1; if (!strncmp(t, "fwht", 4)) return rad_enc_fwht(e) > 0; if (!strcmp(t, "perm")) return rad_enc_find(e, "t.perm") > 0; - if (!strcmp(t, "givens")) - return rad_enc_find(e, "t.pairs") > 0 && rad_enc_find(e, "t.angle") > 0; + if (!strcmp(t, "givens")) { + const int ip = rad_enc_find(e, "t.pairs"), ia = rad_enc_find(e, "t.angle"); + const int is = rad_enc_find(e, "t.scale"); + const int64_t np = rad_enc_givens_parts(e); + if (ip <= 0 || ia <= 0 || np < 1) return 0; + if (e->plane[ip].kind != RAD_PLANE_TABLE || e->plane[ia].kind != RAD_PLANE_TABLE) return 0; + if (e->plane[ip].extent[0] % np || e->plane[ia].extent[0] != e->plane[ip].extent[0]) return 0; + if (e->plane[ia].extent[1] * 2 != e->plane[ip].extent[1]) return 0; + if (is > 0 && (e->plane[is].kind != RAD_PLANE_TABLE || e->plane[is].extent[0] != np || + e->plane[is].extent[1] != e->plane[ip].extent[1])) return 0; + return 1; + } return 0; } diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index f53d5fae..b7275c49 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -543,6 +543,15 @@ void Checkpoint::detect_import() { else import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) " "throughout, which is the one this reads"; + } else if (qm == "paroquant_mxfp4") { + /* QUARK'S MXFP4 PLANES IN A ROTATED BASIS: e2m1 codes, an e8m0 exponent a 32 of K, and per + * projection the learned Givens rotations (`pairs`, `theta`) and channel scales in groups + * of 128 -- z-lab's ParoQuant, retrained for the MXFP4 grid. */ + if (qc("format") == "mxfp4" && qc("mxfp4_block") == "32" && qc("group_size") == "128") + import_ = Import::ParoMx; + 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"; } /* THE TOOL'S DESCRIPTION IS KEPT, UNDER ANOTHER NAME. A plugin reads quantization_config as * the statement of the format it serves (qwen35_fp8 checks quant_method is "fp8"), and an @@ -566,7 +575,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, return RAD_OK; } - if (import_ == Import::QuarkMx) { + if (import_ == Import::QuarkMx || import_ == Import::ParoMx) { /* QUARK'S MXFP4 IS THE ENCODING AS IT STANDS: two codes a byte, element 2j in the low * nibble, and one biased exponent a 32 of K -- `fp4_e2m1*e8m0[1x32]`. A view renames the * dtypes and the logical width; no byte moves. Its excluded layers are plain tensors. */ @@ -761,7 +770,7 @@ std::string ckpt_tensor_of(const SrcTensor& t) { bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set& names, std::unordered_set* hit) { bool any = false; - for (const auto* list : { &w.pieces, &w.scales }) + for (const auto* list : { &w.pieces, &w.scales, &w.pq_pairs, &w.pq_theta, &w.pq_scale }) for (const SrcTensor* t : *list) { if (!t) continue; const std::string n = ckpt_tensor_of(*t); @@ -773,6 +782,90 @@ bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set& return any; } +namespace { + +/* The ROTATION GROUP of a ParoQuant checkpoint: pairs address columns within a group of 128. */ +constexpr int64_t kParoGroup = 128; + +/* "model.layers.0.mlp.down_proj.weight" -> "model.layers.0.mlp.down_proj" */ +std::string paro_base(const SrcTensor& piece) { + std::string n = ckpt_tensor_of(piece); + const std::string suffix = ".weight"; + return n.size() > suffix.size() && n.compare(n.size() - suffix.size(), suffix.size(), suffix) == 0 + ? n.substr(0, n.size() - suffix.size()) : n; +} + +} /* namespace */ + +namespace { + +/* PARTS: EACH PIECE OF A ROTATED WEIGHT HAS ITS OWN ROTATION. A fused gate_up or q|k|v is several + * checkpoint projections, each learned with its own pairs, angles and channel scales, so the + * fused weight is one row PART per piece (abi/rad_encoding.h, "givens"). Gives the encoding its + * four tables -- t.pairs and t.angle stage-major per part, t.scale a row per part, t.part the end + * row of each -- and refuses a rotation that is not what the kernels read: a pair that leaves its + * group of 128, or a stage that does not use every column of a group exactly once. */ +int paro_attach(Checkpoint& ck, CkptWeight* out, std::string* why) { + auto refuse = [&](std::string m) { + if (why) *why = std::move(m); + return (int)RAD_E_FORMAT; + }; + const int64_t K = out->cols, P = (int64_t)out->pieces.size(); + if (K % kParoGroup) return refuse("'" + out->name + "' has " + std::to_string(K) + + " columns, which is not whole rotation groups of 128"); + int64_t S = 0; + out->pq_pairs.clear(); out->pq_theta.clear(); out->pq_scale.clear(); + for (const SrcTensor* piece : out->pieces) { + const std::string base = paro_base(*piece); + const SrcTensor* pr = ck.find(base + ".pairs"); + 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 + + "' 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 || + pr->shape[1] != K || th->shape[0] != pr->shape[0] || th->shape[1] != K / 2 || + cs->shape[0] != 1 || cs->shape[1] != K || pr->shape[0] < 1) + return refuse("'" + base + "' pairs/theta/channel_scales do not fit a " + + std::to_string(K) + "-column weight (int16 [S, K], f16 [S, K/2], f16 [1, K])"); + if (S == 0) S = pr->shape[0]; + if (pr->shape[0] != S) + return refuse("the pieces of '" + out->name + "' have different numbers of rotation stages"); + /* every stage is a perfect matching of each group's 128 columns */ + const int16_t* pv = (const int16_t*)pr->data; + for (int64_t st = 0; st < S; ++st) + for (int64_t g = 0; g < K / kParoGroup; ++g) { + bool seen[kParoGroup] = {}; + for (int64_t i = 0; i < kParoGroup; ++i) { + const int v = pv[st * K + g * kParoGroup + i]; + if (v < 0 || v >= kParoGroup || seen[v]) + return refuse("'" + pr->name + "' stage " + std::to_string(st) + " group " + + std::to_string(g) + " is not a pairing of its 128 columns"); + seen[v] = true; + } + } + out->pq_pairs.push_back(pr); + out->pq_theta.push_back(th); + out->pq_scale.push_back(cs); + } + RadEncoding& e = out->enc; + rad_enc_copy_str(e.transform, "givens"); + rad_enc_add_table(&e, "t.pairs", RAD_I32, P * S, K); + rad_enc_add_table(&e, "t.angle", RAD_F32, P * S, K / 2); + rad_enc_add_table(&e, "t.scale", RAD_F32, P, K); + if (P > 1) rad_enc_add_table(&e, "t.part", RAD_I32, 1, P); + if (!rad_enc_valid(&e)) return refuse("the rotation tables of '" + out->name + "' are malformed"); + out->imported = true; + out->paro = true; + out->trivial = false; + out->why = "it is ParoQuant MXFP4, which rad-convert imports with its rotation tables -- " + "serve the container it writes"; + return RAD_OK; +} + +} /* namespace */ + int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional, CkptWeight* out, std::string* why) { auto refuse = [&](int rc, std::string m) { @@ -808,6 +901,14 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b for (const Src1& s1 : srcs) { const SrcTensor* st = ck.find(s1.name); const SrcTensor* sc = st ? ck.find(scale_name(s1.name)) : nullptr; + /* ParoQuant's fp8 heads and embedding carry ONE f32 SCALE A ROW (`X.weight_scale`, [N]), + * not a block plane: Quark's `_scale` naming for a per-channel weight. */ + if (st && !sc && ck.imports() == Checkpoint::Import::ParoMx && + (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2) && st->shape.size() == 2) { + const SrcTensor* pr = ck.find(std::string(s1.name) + "_scale"); + if (pr && pr->rad_dtype == RAD_F32 && pr->shape.size() == 1 && pr->shape[0] == st->shape[0]) + sc = pr; + } /* A WEIGHT THE CHECKPOINT SHIPS IN AN IMPORTED FORM is read through that form's views. */ { const SrcTensor *ic = nullptr, *is = nullptr; @@ -923,6 +1024,10 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b rad_enc_copy_str(out->enc.scheme, "affine"); rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1); rad_enc_add_plane(&out->enc, "scale", RAD_E8M0, 1, 32); + if (ck.imports() == Checkpoint::Import::ParoMx) { + const int rc = paro_attach(ck, out, why); + if (rc != RAD_OK) return rc; + } } } else if ((dt == RAD_F8E4M3 || dt == RAD_F8E5M2) && scaled) { /* BLOCK-SCALED FP8, byte for byte: the codes and the scale plane are the planes of @@ -944,7 +1049,10 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b const int64_t want_r = (r + br - 1) / br, want_c = (c + bc - 1) / bc; int64_t sr = 0, scl = 0; rad_enc_view((uint32_t)sk.shape.size(), sk.shape.data(), &sr, &scl); - if (sk.rad_dtype != sdt || sr != want_r || scl != want_c) { + const bool per_row = sk.shape.size() == 1; /* one scale a row; see above */ + if (per_row && sk.shape[0] == r && sk.rad_dtype == sdt) { + /* fits */ + } else if (per_row || sk.rad_dtype != sdt || sr != want_r || scl != want_c) { out->trivial = false; out->why = "'" + sk.name + "' is not the [" + std::to_string(want_r) + ", " + std::to_string(want_c) + "] " + std::to_string(br) + "x" + @@ -959,7 +1067,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b rad_enc_clear(&out->enc); rad_enc_copy_str(out->enc.scheme, "affine"); rad_enc_add_plane(&out->enc, "codes", dt, 1, 1); - rad_enc_add_plane(&out->enc, "scale", sdt, br, bc); + if (out->scales[0]->shape.size() == 1) rad_enc_add_plane(&out->enc, "scale", sdt, 1, 0); + else rad_enc_add_plane(&out->enc, "scale", sdt, br, bc); } } else if (!unscaled) { out->why = "some of its pieces carry a scale plane and some do not"; @@ -1127,6 +1236,11 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std:: return rc; }; if (r0 < 0 || nr < 0 || r0 + nr > w.rows) return refuse(RAD_E_SHAPE, "rows out of range"); + /* A ROTATED WEIGHT's codes are in the rotated basis; its f32 value would be the unrotated one, + * which only a decoder over the container's tables computes. Nothing quantises it again. */ + if (w.paro) + return refuse(RAD_E_UNSUPPORTED, "'" + w.name + "' is a ParoQuant weight, stored rotated; " + "it is kept as it is and has no f32 view here"); Joined j; j.init(w.pieces, w.concat_dim); /* the runs come in order, so the cursor is the elements already written */ @@ -1165,13 +1279,15 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std:: * are that piece's. */ if (!w.scales.empty() && w.scales[0]) { const int64_t br = w.enc.n_planes > 1 ? w.enc.plane[1].block[0] : 128; - const int64_t bc = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128; + /* a block extent of 0 is the whole extent: a scale a row, one column of scales */ + const int64_t bc0 = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128; int64_t base = 0; for (size_t k = 0; k < w.pieces.size(); ++k) { const SrcTensor& pk = *w.pieces[k]; const SrcTensor& sk = *w.scales[k]; int64_t pr = 0, pc = 0; rad_enc_view((uint32_t)pk.shape.size(), pk.shape.data(), &pr, &pc); + const int64_t bc = bc0 > 0 ? bc0 : pc; const int64_t sc = (pc + bc - 1) / bc; for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r) for (int64_t c = 0; c < w.cols; ++c) @@ -1198,7 +1314,47 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds const uint32_t dt = w.enc.plane[k].dtype; const int64_t eb = rad_dtype_bits(dt) / 8; uint8_t* o = (uint8_t*)dst; - if (w.imported) { + if (w.paro && k >= 2) { + /* A ROTATION TABLE, built from the checkpoint's own tensors a row at a time: the pairs + * from group-local to whole-row columns, the angles widened, the channel scale inverted + * (the checkpoint multiplies the activation by it; the encoding's t.scale is the factor + * the stored row was MULTIPLIED by, so the activation is divided), the part ends. */ + const RadEncPlane& pl = w.enc.plane[k]; + const int64_t P = (int64_t)w.pieces.size(), S = w.pq_pairs[0]->shape[0], K = w.cols; + const std::string role = pl.role; + for (int64_t r = r0; r < r0 + nr; ++r) { + if (role == "t.pairs") { + const int16_t* pv = (const int16_t*)w.pq_pairs[(size_t)(r / S)]->data + (r % S) * K; + int32_t* d = (int32_t*)o; + for (int64_t c = 0; c < K; ++c) + d[c] = (int32_t)((c / kParoGroup) * kParoGroup + pv[c]); + o += K * 4; + } else if (role == "t.angle") { + const SrcTensor& th = *w.pq_theta[(size_t)(r / S)]; + float* d = (float*)o; + for (int64_t c = 0; c < K / 2; ++c) + d[c] = rad_load_f32(th.data, th.rad_dtype, (r % S) * (K / 2) + c); + o += K / 2 * 4; + } else if (role == "t.scale") { + const SrcTensor& cs = *w.pq_scale[(size_t)r]; + float* d = (float*)o; + for (int64_t c = 0; c < K; ++c) d[c] = 1.0f / rad_load_f32(cs.data, cs.rad_dtype, c); + o += K * 4; + } else if (role == "t.part") { + int32_t* d = (int32_t*)o; + int64_t end = 0; + for (int64_t q = 0; q < P; ++q) { + end += w.pieces[(size_t)q]->shape[0]; + d[q] = (int32_t)end; + } + o += P * 4; + } else { + return refuse(RAD_E_STATE, "plane '" + role + "' of a ParoQuant weight is not a table"); + } + } + return RAD_OK; + } + if (w.imported && !w.paro) { /* GPTQ-PACKED, RE-LAID: a row of codes is a column of the qweight, its words' bytes in * order -- two codes a byte for int4, low nibble first, as the encoding packs them -- each * offset to signed by flipping the top bit of every field; a row of scales is a column of @@ -1249,6 +1405,7 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds for (const SrcTensor* s : src) { int64_t sr = 0, scl = 0; rad_enc_view((uint32_t)s->shape.size(), s->shape.data(), &sr, &scl); + if (s->shape.size() == 1) { sr = s->shape[0]; scl = 1; } /* one scale a row */ const int64_t lo = std::max(r0, base), hi = std::min(r0 + nr, base + sr); if (hi > lo) { std::memcpy(o, (const uint8_t*)s->data + (lo - base) * scl * eb, diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 1b5cf248..7548e5ad 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -128,11 +128,12 @@ public: /* THE CHECKPOINT'S QUANTISATION, IMPORTED WEIGHT BY WEIGHT, or None. Read from * quantization_config at open: AutoRound's `auto_round:auto_gptq` export and GPTQ's own (v1, * the zero point stored less one) are Gptq; Quark's MXFP4 (fp4 weights, per_group 32, e8m0 - * scales, no per-layer overrides) is QuarkMx. A quantisation of one of those tools in a form + * scales, no per-layer overrides) is QuarkMx; ParoQuant's MXFP4 (`paroquant_mxfp4`: Quark's + * codes and exponents in a ROTATED basis, with the rotations beside them) is ParoMx. A quantisation of one of those tools in a form * this does not read stays None, with the reason in import_refusal(). */ /* Its quantization_config keys are then renamed `imported_quantization_config.*`: they * describe the tool, not a served format, and a plugin reads the latter there. */ - enum class Import { None, Gptq, QuarkMx }; + enum class Import { None, Gptq, QuarkMx, ParoMx }; Import imports() const { return import_; } const std::string& import_refusal() const { return import_why_; } @@ -186,6 +187,13 @@ struct CkptWeight { * Not trivial -- the rounding means the numbers are not served as shipped -- so the loader * refuses one and rad-convert keeps it in `enc`, as it keeps a trivial weight. */ bool imported = false; + /* PAROQUANT MXFP4, IMPORTED (Import::ParoMx): `imported` too, so the loader refuses it and + * rad-convert writes it 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 here + * from `pq_pairs`/`pq_theta`/`pq_scale`, one set per piece (a piece is a row PART: gate and up, + * or q, k and v, each rotated on its own). */ + bool paro = false; + std::vector pq_pairs, pq_theta, pq_scale; RadEncoding enc{}; std::string why; }; diff --git a/core/format/encoding.cpp b/core/format/encoding.cpp index eb7a9c5d..538d3726 100644 --- a/core/format/encoding.cpp +++ b/core/format/encoding.cpp @@ -102,31 +102,77 @@ Rd plane(const EncodedView& v, int idx) { return r; } -/* Undo a "givens" transform on one row in place: w = v . G_S^T ... G_1^T . D^-1. */ -int givens_inverse(const EncodedView& v, float* row, std::string* why) { +/* The tables of one row part of a "givens" weight, read once: the cosine and sine of every angle + * and the pairs as indices, so undoing a row is arithmetic and not a table walk. A decode asks for + * the part its row falls in, and rows of one part follow each other. */ +struct GivensPart { + int64_t part = -1; + int64_t S = 0; + std::vector pair; /* [S][K] */ + std::vector cs, sn; /* [S][K/2] */ + std::vector scale; /* [K], empty without t.scale */ +}; + +int givens_part(const EncodedView& v, int64_t r, GivensPart* g, std::string* why) { const Rd pairs = plane(v, rad_enc_find(&v.enc, "t.pairs")); const Rd angle = plane(v, rad_enc_find(&v.enc, "t.angle")); const Rd scale = plane(v, rad_enc_find(&v.enc, "t.scale")); - const int64_t S = pairs.v->rows, K = v.cols; - if (pairs.v->cols != K || angle.v->rows != S || angle.v->cols != K / 2 || (K & 1) || - (scale && (scale.v->rows != 1 || scale.v->cols != K))) { + const Rd bound = plane(v, rad_enc_find(&v.enc, "t.part")); + const int64_t K = v.cols, P = rad_enc_givens_parts(&v.enc); + if (P < 1 || pairs.v->rows % P || pairs.v->cols != K || angle.v->rows != pairs.v->rows || + angle.v->cols != K / 2 || (K & 1) || + (scale && (scale.v->rows != P || scale.v->cols != K))) { if (why) *why = fmt("a givens transform's tables do not fit a %lld-column row", K); return RAD_E_SHAPE; } - for (int64_t s = S - 1; s >= 0; --s) - for (int64_t p = 0; p < K / 2; ++p) { - const int64_t a = (int64_t)pairs.at(s, 2 * p), b = (int64_t)pairs.at(s, 2 * p + 1); - if (a < 0 || a >= K || b < 0 || b >= K || a == b) { - if (why) *why = fmt("givens stage %lld pairs columns %lld and %lld", s, a, b); + int64_t part = 0; + while (bound && part + 1 < P && r >= (int64_t)bound.at(0, part)) ++part; + if (g->part == part) return RAD_OK; + g->part = part; + g->S = pairs.v->rows / P; + g->pair.assign((size_t)(g->S * K), 0); + g->cs.assign((size_t)(g->S * K / 2), 0.0); + g->sn.assign((size_t)(g->S * K / 2), 0.0); + for (int64_t s = 0; s < g->S; ++s) { + for (int64_t k = 0; k < K; ++k) { + const int64_t c = (int64_t)pairs.at(part * g->S + s, k); + if (c < 0 || c >= K) { + if (why) *why = fmt("givens stage %lld names column %lld", s, c); return RAD_E_SHAPE; } - const double t = angle.at(s, p), c = std::cos(t), sn = std::sin(t); + g->pair[(size_t)(s * K + k)] = (int32_t)c; + } + for (int64_t p = 0; p < K / 2; ++p) { + const double t = angle.at(part * g->S + s, p); + g->cs[(size_t)(s * K / 2 + p)] = std::cos(t); + g->sn[(size_t)(s * K / 2 + p)] = std::sin(t); + } + } + g->scale.clear(); + if (scale) { + g->scale.resize((size_t)K); + for (int64_t k = 0; k < K; ++k) g->scale[(size_t)k] = scale.at(part, k); + } + return RAD_OK; +} + +/* Undo a "givens" transform on one row in place: w = v . G_S^T ... G_1^T . D^-1, with the tables + * of the row part `g` holds. */ +int givens_inverse(const GivensPart& g, int64_t K, float* row, std::string* why) { + for (int64_t s = g.S - 1; s >= 0; --s) + for (int64_t p = 0; p < K / 2; ++p) { + const int64_t a = g.pair[(size_t)(s * K + 2 * p)], b = g.pair[(size_t)(s * K + 2 * p + 1)]; + if (a == b) { + if (why) *why = fmt("givens stage %lld pairs column %lld with itself", s, a); + return RAD_E_SHAPE; + } + const double c = g.cs[(size_t)(s * K / 2 + p)], sn = g.sn[(size_t)(s * K / 2 + p)]; const double x = row[a], y = row[b]; row[a] = (float)(c * x - sn * y); row[b] = (float)(sn * x + c * y); } - if (scale) - for (int64_t k = 0; k < K; ++k) row[k] /= scale.at(0, k); + if (!g.scale.empty()) + for (int64_t k = 0; k < K; ++k) row[k] /= g.scale[(size_t)k]; return RAD_OK; } @@ -219,6 +265,7 @@ int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, s return RAD_E_SHAPE; } std::vector tmp(perm ? (size_t)v.cols : 0); + GivensPart gv; /* THE COMMON FORM, A ROW AT A TIME: codes with no codebook, sign, zero or minimum and at most * one scale level -- int4 experts, fp8 rows, a fixed-scale table. The element walk below * resolves every element's dtype and its scale's index through a switch and two divisions, @@ -288,7 +335,8 @@ int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, s } std::memcpy(o, tmp.data(), (size_t)v.cols * sizeof(float)); } else if (giv) { - const int st = givens_inverse(v, o, why); + int st = givens_part(v, r, &gv, why); + if (st == RAD_OK) st = givens_inverse(gv, v.cols, o, why); if (st != RAD_OK) return st; } } diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index 0711eec5..0f8a9488 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -8,6 +8,7 @@ */ #include "rad_test.h" #include "format/checkpoint.h" +#include "format/encoding.h" #include "rad_plugin.h" #include @@ -684,3 +685,152 @@ TEST(the_index_decides_which_shard_a_tensor_is_read_from) { std::remove((dir + "/" + f).c_str()); ::rmdir(dir.c_str()); } + +/* PAROQUANT MXFP4 is Quark's codes and exponents in a rotated basis plus the rotations: each + * projection's pairs (group-local int16), theta and channel scales. Gate and up are two PARTS of + * the fused weight, and the tables must say so: pairs made whole-row, angles widened, the channel + * scale inverted, the part ends. Decoding the planes through the core must then give a weight + * that, rotated forward again, is the codes the checkpoint shipped. */ +TEST(a_paroquant_mxfp4_weight_carries_its_rotations_as_parts) { + const int64_t K = 128, S = 2; + uint32_t rng = 12345; + auto next = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; }; + auto codes = [&](const std::string& n, int64_t N) { + T t{ n, "U8", { N, K / 2 }, {} }; + for (int64_t i = 0; i < N * K / 2; ++i) t.bytes.push_back((uint8_t)(next() & 0xff)); + return t; + }; + auto exps = [&](const std::string& n, int64_t N) { + T t{ n, "U8", { N, K / 32 }, {} }; + for (int64_t i = 0; i < N * K / 32; ++i) t.bytes.push_back((uint8_t)(122 + next() % 5)); + return t; + }; + auto pairs = [&](const std::string& n) { + T t{ n, "I16", { S, K }, {} }; + for (int64_t s = 0; s < S; ++s) { + std::vector 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 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 float f = lo + (hi - lo) * (float)(next() % 1000) / 1000.0f; + const uint16_t h = rad_f32_to_f16(f); + t.bytes.push_back((uint8_t)(h & 0xff)); + t.bytes.push_back((uint8_t)(h >> 8)); + } + return t; + }; + const T gw = codes("g.weight", 16), gs = exps("g.weight_scale", 16), gp = pairs("g.pairs"), + gt = f16s("g.theta", { S, K / 2 }, -3.0f, 3.0f), gc = f16s("g.channel_scales", { 1, K }, 0.5f, 2.0f); + const T uw = codes("u.weight", 16), us = exps("u.weight_scale", 16), up = pairs("u.pairs"), + ut = f16s("u.theta", { S, K / 2 }, -3.0f, 3.0f), uc = f16s("u.channel_scales", { 1, K }, 0.5f, 2.0f); + // a per-row fp8 head beside them: weight_scale is one f32 a row + T hs{ "h.weight_scale", "F32", { 4 }, {} }; + for (int i = 0; i < 4; ++i) { float f = 0.25f * (float)(i + 1); hs.bytes.resize(hs.bytes.size() + 4); std::memcpy(hs.bytes.data() + 4 * i, &f, 4); } + const std::string dir = write_checkpoint( + { gw, gs, gp, gt, gc, uw, us, up, ut, uc, fp8("h.weight", { 4, 8 }), hs }, + "{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":\"paroquant_mxfp4\"," + "\"format\":\"mxfp4\",\"bits\":4,\"group_size\":128,\"mxfp4_block\":32,\"krot\":2}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK(ck.imports() == Checkpoint::Import::ParoMx); + Program prog; + prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "g.weight", "u.weight" })); + prog.name_map.push_back(map("h", RAD_MAP_COPY, { "h.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_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)32); + REQUIRE_EQ(w.enc.n_planes, 6); + + std::vector> pl((size_t)w.enc.n_planes); + for (int k = 0; k < w.enc.n_planes; ++k) { + int64_t pr = 0, pc = 0; + rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc); + pl[(size_t)k].resize((size_t)(pr * rad_enc_row_bytes(w.enc.plane[k].dtype, pc))); + REQUIRE_EQ(ckpt_plane_rows(w, k, 0, pr, pl[(size_t)k].data(), &why), RAD_OK); + } + // codes and exponents are the checkpoint's bytes, joined + CHECK_EQ(std::memcmp(pl[0].data(), gw.bytes.data(), gw.bytes.size()), 0); + CHECK_EQ(std::memcmp(pl[0].data() + gw.bytes.size(), uw.bytes.data(), uw.bytes.size()), 0); + CHECK_EQ(std::memcmp(pl[1].data() + gs.bytes.size(), us.bytes.data(), us.bytes.size()), 0); + const int32_t* tp = (const int32_t*)pl[2].data(); + const float* ta = (const float*)pl[3].data(); + const float* tsc = (const float*)pl[4].data(); + const int32_t* tpart = (const int32_t*)pl[5].data(); + CHECK_EQ(tpart[0], 16); + CHECK_EQ(tpart[1], 32); + for (int64_t c = 0; c < K; ++c) { + CHECK_EQ(tp[c], (int32_t)(*(const int16_t*)(gp.bytes.data() + 2 * c))); // part 0, stage 0 + CHECK_EQ(tp[(S + 1) * K + c], (int32_t)(*(const int16_t*)(up.bytes.data() + 2 * (K + c)))); // part 1, stage 1 + const uint16_t h = *(const uint16_t*)(gc.bytes.data() + 2 * c); + CHECK(std::fabs(tsc[c] - 1.0f / rad_f16_to_f32(h)) < 1e-6f); + } + CHECK(std::fabs(ta[0] - rad_f16_to_f32(*(const uint16_t*)gt.bytes.data())) == 0.0f); + + // decode, rotate forward again with the checkpoint's own convention, compare to the codes + const void* data[6]; + for (int k = 0; k < 6; ++k) data[k] = pl[(size_t)k].data(); + EncodedView v; + enc_view(w.enc, w.rows, w.cols, data, &v); + std::vector dec((size_t)(w.rows * K)); + REQUIRE_EQ(enc_decode_rows(v, 0, w.rows, dec.data(), &why), RAD_OK); + const T* cw[2] = { &gw, &uw }; + const T* es[2] = { &gs, &us }; + const T* pp[2] = { &gp, &up }; + const T* th[2] = { >, &ut }; + const T* cc[2] = { &gc, &uc }; + double worst = 0; + for (int64_t r = 0; r < w.rows; ++r) { + const int part = r >= 16, rr = r - 16 * part; + std::vector x((size_t)K); + for (int64_t k = 0; k < K; ++k) + x[(size_t)k] = (double)dec[(size_t)(r * K + k)] * + (1.0 / rad_f16_to_f32(*(const uint16_t*)(cc[part]->bytes.data() + 2 * k))); + for (int64_t s = 0; s < S; ++s) + for (int64_t p = 0; p < K / 2; ++p) { + const int16_t* pv = (const int16_t*)pp[part]->bytes.data(); + const int64_t a = pv[s * K + 2 * p], b = pv[s * K + 2 * p + 1]; + const double t = rad_f16_to_f32(*(const uint16_t*)(th[part]->bytes.data() + 2 * (s * (K / 2) + p))); + const double c = std::cos(t), sn = std::sin(t); + const double xa = x[(size_t)a], xb = x[(size_t)b]; + x[(size_t)a] = xa * c + xb * sn; + x[(size_t)b] = xb * c - xa * sn; + } + for (int64_t k = 0; k < K; ++k) { + const uint8_t bt = cw[part]->bytes[(size_t)(rr * K / 2 + k / 2)]; + const float code = rad_fp4e2m1_to_f32((uint8_t)(k % 2 ? bt >> 4 : bt & 15)); + const float sc = std::ldexp(1.0f, (int)es[part]->bytes[(size_t)(rr * K / 32 + k / 32)] - 127); + worst = std::max(worst, std::fabs(x[(size_t)k] - (double)code * sc)); + } + } + CHECK(worst < 1e-4); + + // the per-row fp8 head: one f32 scale a row, read as [N, 1] + REQUIRE_EQ(ckpt_resolve(ck, prog, "h", false, &w, &why), RAD_OK); + REQUIRE(w.trivial); + CHECK_EQ(w.enc.plane[1].block[0], (int64_t)1); + CHECK_EQ(w.enc.plane[1].block[1], (int64_t)0); + std::vector f(4 * 8); + REQUIRE_EQ(ckpt_rows_f32(w, 0, 4, f.data(), &why), RAD_OK); + for (int r = 0; r < 4; ++r) { + const float q = rad_load_f32(fp8("h.weight", { 4, 8 }).bytes.data(), RAD_F8E4M3, r * 8); + CHECK_EQ(f[(size_t)(r * 8)], q * 0.25f * (float)(r + 1)); + } + remove_checkpoint(dir); +} diff --git a/tests/encoding_test.cpp b/tests/encoding_test.cpp index 81f3edd2..3343c66e 100644 --- a/tests/encoding_test.cpp +++ b/tests/encoding_test.cpp @@ -433,6 +433,52 @@ TEST(a_givens_transform_with_channel_scales_inverts) { for (int k = 0; k < K; ++k) CHECK(std::fabs(out[k] - w[k]) < 1e-5f); } +TEST(a_givens_weight_with_two_parts_undoes_each_rows_own_rotation) { + /* Two rows over 4 columns, each its own PART (row 0 ends part 0, row 1 ends part 1): the + * tables stack part-major, t.scale has a row a part, and decoding row r reads its part's. */ + const int K = 4; + const float w[2][4] = { { 1.0f, -2.0f, 0.5f, 3.0f }, { -0.25f, 1.5f, 2.0f, -1.0f } }; + const float dsc[2][4] = { { 2.0f, 0.5f, 1.0f, 4.0f }, { 1.0f, 3.0f, 0.25f, 2.0f } }; + const int32_t pairs[2][4] = { { 0, 1, 2, 3 }, { 0, 3, 1, 2 } }; /* one stage a part */ + const float ang[2][2] = { { 0.3f, -1.1f }, { 0.9f, 2.2f } }; + const int32_t end[2] = { 1, 2 }; + float vq[2][4]; + for (int r = 0; r < 2; ++r) { + double x[4]; + for (int k = 0; k < K; ++k) x[k] = (double)w[r][k] * dsc[r][k]; + for (int p = 0; p < 2; ++p) { + const int a = pairs[r][2 * p], b = pairs[r][2 * p + 1]; + const double c = std::cos((double)ang[r][p]), sn = std::sin((double)ang[r][p]); + const double xa = x[a], xb = x[b]; + x[a] = xa * c + xb * sn; + x[b] = xb * c - xa * sn; + } + for (int k = 0; k < K; ++k) vq[r][k] = (float)x[k]; + } + RadEncoding e = rad_enc_plain(RAD_F32); + rad_enc_copy_str(e.scheme, "affine"); + rad_enc_add_plane(&e, "scale", RAD_F32, 0, 0); + rad_enc_add_table(&e, "t.pairs", RAD_I32, 2, 4); + rad_enc_add_table(&e, "t.angle", RAD_F32, 2, 2); + rad_enc_add_table(&e, "t.scale", RAD_F32, 2, 4); + rad_enc_add_table(&e, "t.part", RAD_I32, 1, 2); + rad_enc_copy_str(e.transform, "givens"); + REQUIRE(rad_enc_valid(&e)); + CHECK_EQ(rad_enc_givens_parts(&e), (int64_t)2); + const float one = 1.0f; + const void* planes[6] = { vq, &one, pairs, ang, dsc, end }; + EncodedView v; + enc_view(e, 2, 4, planes, &v); + float out[8]; + REQUIRE_EQ(enc_decode_rows(v, 0, 2, out), RAD_OK); + for (int r = 0; r < 2; ++r) + for (int k = 0; k < K; ++k) CHECK(std::fabs(out[r * K + k] - w[r][k]) < 1e-5f); + /* a part table that does not stack to the pairs' rows is not well formed */ + RadEncoding bad = e; + bad.plane[bad.n_planes - 1].extent[1] = 3; + CHECK(!rad_enc_valid(&bad)); +} + TEST(the_core_declines_a_scheme_it_did_not_define) { RadEncoding e; rad_enc_clear(&e);