From 3402acf82de4fb5dcbeefd226c29ca01e912eb45 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Wed, 7 Oct 2026 23:52:17 +0000 Subject: [PATCH 01/17] 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); From 1213c05cd8d551f1090ac7f38d60f6813e4675ec Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Wed, 7 Oct 2026 23:52:17 +0000 Subject: [PATCH 02/17] ops: givens_quant_act_fp8; gemm_nt_q pb1/pb2 for activation copies per weight part libref implements both (and is the oracle); libavx refuses a call that names a part. --- docs/OPS.md | 25 ++++++- libavx/avx_gemm.cpp | 4 ++ libavx/avx_registry.cpp | 4 +- libref/ref_gemm.cpp | 47 ++++++++++++++ libref/ref_ops.h | 2 + libref/ref_quant.cpp | 76 ++++++++++++++++++++++ libref/ref_registry.cpp | 27 +++++++- libref/ref_shapes.cpp | 8 +++ tests/ref_test.cpp | 141 +++++++++++++++++++++++++++++++++++++++- 9 files changed, 329 insertions(+), 5 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index 28d74441..31cfd85a 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -362,10 +362,33 @@ spelling of `act`, not the vocabulary's. |---|---|---| | `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | +| `givens_quant_act_fp8` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | | `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | +### `givens_quant_act_fp8`: ParoQuant's rotated activation + +A weight stored with the `givens` transform (`abi/rad_encoding.h`) is `v = w . D . G_1 ... G_S`: the +channel scale `D` and `S` stages of disjoint pairwise rotations were applied to each row BEFORE it +was quantised (ParoQuant, z-lab), so the product the GEMM contracts is `` with +`x' = x . D^-1 . G_1 ... G_S` -- the activation takes the same rotation, forward, once a token. +`givens_quant_act_fp8` is that: `x / rscale`, then for each stage `a' = a cos t + b sin t, +b' = b cos t - a sin t` over its pairs, then `quant_act_fp8`'s quantiser (scale `amax / 448` per +`group` columns). The pairs are column indices of the row and each pair lies inside ONE scale group +(ParoQuant's are within groups of 128), so the kernel rotates a group at a time and the quantiser +sees the rotated group. The consumer is the plain `gemm_nt_q` at `mxfp4a8`; nothing in the weight's +codes or exponents changed. + +A fused projection (gate|up, qkv|z) was rotated PER CHECKPOINT TENSOR, so it has `parts` rotated +copies of the activation, written side by side -- `q` is `[M, parts * n]`, `scale` +`[M, parts * n / group]` -- and `pairs` and `angle` stack the parts' `stages` rows each, `rscale` +one row a part. `gemm_nt_q` then takes `pb1` and `pb2`, the row bounds of the weight's parts: its +rows `[0, pb1)`, `[pb1, pb2)` and `[pb2, N)` meet copy 0, 1 and 2, and `a`/`a_scale` are the wide +planes. `pb1` absent is one part; `pb2` absent ends the second part at `N`. Only the `mxfp4a8` rows +read them, and the host rows that do not (`libavx`) refuse a call that names one rather than +contract against the wrong copy. + ### The int8 and gated fp8 fusions — device-only | op | params | operands | @@ -410,7 +433,7 @@ waiting on the mover's event — a read of weight bytes that may not have arrive |---|---|---| | `gemm_nt` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` | | `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` | -| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | +| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | | `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` | `nt` is A row-major `[M,K]` times B **transposed** `[N,K]`, giving `[M,N]` — the layout every diff --git a/libavx/avx_gemm.cpp b/libavx/avx_gemm.cpp index ca9855ad..0969d2db 100644 --- a/libavx/avx_gemm.cpp +++ b/libavx/avx_gemm.cpp @@ -755,6 +755,10 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { const RadTensor* bs_ = rad_arg_in(a, 3); const RadTensor* bias = bias_operand ? rad_arg_in(a, 4) : nullptr; + /* `pb1`/`pb2` split the weight's rows into parts that meet separate copies of the activation + * (ParoQuant); this driver reads one. Refused rather than computed against the wrong copy. */ + if (p_int(a, "pb1", 0) || p_int(a, "pb2", 0)) return RAD_E_UNSUPPORTED; + const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 96137405..03cef4bf 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -210,6 +210,8 @@ static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD OUT("y") }; static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), + P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2") }; +static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype") }; static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"), WGT("b_scale"), OUT("y"), OPD_O("a_sum"), WGT_O("b_ref") }; @@ -567,7 +569,7 @@ static const RadOpSchema kSchemas[] = { { "gemm_nt_q", ARR(pGemmQ), ARR(oGemmQ), "C = A B^T with group-scaled quantised operands. `a_sum` and `b_ref` are libr4d's asymmetric and " "mxfp4 forms and are ignored here, as they are in libref." }, -{ "gemm_nt_q_bias", ARR(pGemmQ), ARR(oGemmQBias), "quantised C = A B^T + bias." }, +{ "gemm_nt_q_bias", ARR(pGemmQBias), ARR(oGemmQBias), "quantised C = A B^T + bias." }, { "gemm_nt_q_gated", ARR(pGemmQGated), ARR(oGemmQGated), "gemm_nt_q over a [N, K] gate_up plane with gated_quant_fp8's pass in the epilogue, byte for " "byte the pair. `N` is the weight's rows, twice the fused width; the output is [M, N/2]." }, diff --git a/libref/ref_gemm.cpp b/libref/ref_gemm.cpp index 2c0c66da..bf642575 100644 --- a/libref/ref_gemm.cpp +++ b/libref/ref_gemm.cpp @@ -17,6 +17,7 @@ * thousands in every GEMM a transformer issues. Each thread owns whole output elements, so the * summation order does not depend on the thread count. */ +#include #include "ref_common.h" #include "ref_gemm.h" #include "ref_ops.h" @@ -253,6 +254,52 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE; if (bias && numel(bias) < N) return RAD_E_SHAPE; + /* PARTS (`pb1`, `pb2`): the weight's rows are [0, pb1), [pb1, pb2) and [pb2, N), each against + * its own copy of the activation -- a fused projection whose pieces were rotated separately + * (ParoQuant). The copies sit side by side in a row of `a`, so `a` is [M, parts * K] and its + * scale [M, parts * K / 128]; a part is the plain product over its rows, which is how it is + * computed. 0 leaves a bound out: no `pb1` is one part, no `pb2` ends the second at N. */ + const int64_t pb1 = p_int(a, "pb1", 0), pb2 = p_int(a, "pb2", 0); + if (pb1 > 0 || pb2 > 0) { + if (bias_operand || B->dtype != RAD_FP4E2M1 || A->rank < 2) return RAD_E_UNSUPPORTED; + const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; + const int64_t bound[4] = { 0, e1, e2, N }; + const int64_t acols = A->shape[A->rank - 1]; + const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + if (acols != parts * K || (e1 % 16) || (e2 % 16)) return RAD_E_SHAPE; + const bool sa_row = as_ && as_->data && as_->rank >= 2; + if (!sa_row) return RAD_E_INVAL; + const int64_t sa_cols = as_->shape[as_->rank - 1]; + if (sa_cols % parts) return RAD_E_SHAPE; + const int64_t sa_part = sa_cols / parts; /* K / 128 */ + for (int p = 0; p < 3; ++p) { + const int64_t n0 = bound[p], n1 = bound[p + 1]; + if (n1 <= n0) continue; + RadTensor Ap = *A, Sp = *as_, Bp = *B, Bsp = *bs_, Yp = *Y; + Ap.data = (uint8_t*)A->data + rad_dtype_bytes(A->dtype, p * K); + Ap.rank = 2; Ap.shape[0] = M; Ap.shape[1] = K; + Ap.stride[0] = row_stride(A, acols); Ap.stride[1] = 1; + Sp.data = (uint8_t*)as_->data + rad_dtype_bytes(as_->dtype, p * sa_part); + Sp.shape[Sp.rank - 1] = sa_part; + Bp.data = (uint8_t*)B->data + rad_dtype_bytes(B->dtype, n0 * K); + Bp.rank = 2; Bp.shape[0] = n1 - n0; Bp.shape[1] = K; Bp.stride[0] = K; Bp.stride[1] = 1; + const int64_t bs_cols = bs_->shape[bs_->rank - 1]; + Bsp.data = (uint8_t*)bs_->data + rad_dtype_bytes(bs_->dtype, n0 * bs_cols); + Bsp.rank = 2; Bsp.shape[0] = n1 - n0; Bsp.shape[1] = bs_cols; + Bsp.stride[0] = bs_cols; Bsp.stride[1] = 1; + const int64_t ys = row_stride(Y, N); + Yp.data = (uint8_t*)Y->data + rad_dtype_bytes(Y->dtype, n0); + Yp.rank = 2; Yp.shape[0] = M; Yp.shape[1] = n1 - n0; Yp.stride[0] = ys; Yp.stride[1] = 1; + Scales SAp = make_scales(&Sp, M, K, false), SBp = make_scales(&Bsp, n1 - n0, K, true); + const Mat map_ = as_mat(&Ap, M, K), mbp = as_mat(&Bp, n1 - n0, K); + QuantFn fn = pick_quant(Ap.dtype, Bp.dtype); + if (fn) fn(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K, 1.0f); + else gemm_quant_generic(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K, 1.0f); + } + return RAD_OK; + } + const bool mx = B->dtype == RAD_FP4E2M1; Scales SA = make_scales(as_, M, K, false); Scales SB = make_scales(bs_, N, K, mx); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 276f0209..1c91d3eb 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -100,6 +100,7 @@ int ref_quant_act_i8 (const RadArgs*, RadStream); int ref_had_quant_act_i8 (const RadArgs*, RadStream); int ref_quant_act_fp8 (const RadArgs*, RadStream); int ref_had_quant_act_fp8 (const RadArgs*, RadStream); +int ref_givens_quant_act_fp8(const RadArgs*, RadStream); int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); int ref_gated_quant_fp8 (const RadArgs*, RadStream); int ref_gemm_nt_q_gated (const RadArgs*, RadStream); @@ -228,6 +229,7 @@ REF_SHAPE_FN(ref_quant_act_i8); REF_SHAPE_FN(ref_had_quant_act_i8); REF_SHAPE_FN(ref_quant_act_fp8); REF_SHAPE_FN(ref_had_quant_act_fp8); +REF_SHAPE_FN(ref_givens_quant_act_fp8); REF_SHAPE_FN(ref_rmsnorm_quant_fp8); REF_SHAPE_FN(ref_gated_quant_fp8); REF_SHAPE_FN(ref_gemm_nt_q_gated); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index f01559b0..666126f9 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -410,6 +410,82 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------- givens_quant_act_fp8 */ +/* ParoQuant's activation side: every row scaled by its channel factors, rotated by `stages` + * rounds of disjoint Givens pairs, then the same symmetric block-scaled E4M3 quantiser. A weight + * stored as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens") meets the activation + * x . D^-1 . G_1 ... G_S, because = and each G is orthogonal. + * + * PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row has `parts` rotated + * copies, written side by side: q is [rows, parts * n] and scale [rows, parts * n/group], part p at + * columns [p*n, (p+1)*n). The tables stack the parts: pairs and angle `stages` rows each, scale one + * row, per part. A part's pairs address columns of the row, and a pair must stay inside one scale + * group (the checkpoint's are within groups of 128): the quantiser reads each group's rotated + * values after the stages and the device kernel rotates a group at a time. + * + * The arithmetic is the device kernel's, restated: the divide by the channel scale, then for each + * stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32, then amax/448 per group. Not + * bit-identical to the device on the angle: cos and sin of an f32 differ by an ulp between libm + * and the GPU's. */ +int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { + if (!have(a, 6)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3]; + const RadTensor *q = &a->t[4], *s = &a->t[5]; + const int64_t n = p_int(a, "n", 0), S = p_int(a, "stages", 0), P = p_int(a, "parts", 1); + int64_t g = p_int(a, "group", 0); + if (n <= 0 || S <= 0 || P <= 0 || (n & 1)) return RAD_E_SHAPE; + if (g <= 0 || g > n || n % g != 0) return RAD_E_SHAPE; + if (numel(pr) < P * S * n || numel(an) < P * S * (n / 2) || numel(sc) < P * n) return RAD_E_SHAPE; + const int64_t rows = numel(x) / n; + const int64_t ngrp = n / g; + if (rows <= 0 || numel(q) < rows * P * n || numel(s) < rows * P * ngrp) return RAD_E_SHAPE; + + // validated before the loop, because an OpenMP body cannot return + for (int64_t i = 0; i < P * S * n; ++i) { + const int64_t c = ld_int(pr->dtype, pr->data, i); + if (c < 0 || c >= n) return RAD_E_INVAL; + } + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + std::vector buf((size_t)n); + const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n); + const int64_t xs = laststride(x), qs = laststride(q); + for (int64_t p = 0; p < P; ++p) { + for (int64_t k = 0; k < n; ++k) buf[(size_t)k] = ldt(x, xb + k * xs) / ldt(sc, p * n + k); + for (int64_t st = 0; st < S; ++st) { + const int64_t t0 = (p * S + st) * n, a0 = (p * S + st) * (n / 2); + for (int64_t j = 0; j < n / 2; ++j) { + const int64_t ia = ld_int(pr->dtype, pr->data, t0 + 2 * j); + const int64_t ib = ld_int(pr->dtype, pr->data, t0 + 2 * j + 1); + const float th = ldt(an, a0 + j), c = std::cos(th), sn = std::sin(th); + const float va = buf[(size_t)ia], vb = buf[(size_t)ib]; + buf[(size_t)ia] = va * c + vb * sn; + buf[(size_t)ib] = vb * c - va * sn; + } + } + for (int64_t gi = 0; gi < ngrp; ++gi) { + const int64_t k0 = gi * g; + float amax = 0.0f; + for (int64_t i = 0; i < g; ++i) { + const float m = std::fabs(buf[(size_t)(k0 + i)]); + if (m > amax) amax = m; + } + const float scl = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; + const float inv = 1.0f / scl; + for (int64_t i = 0; i < g; ++i) { + float v = buf[(size_t)(k0 + i)] * inv; + if (v > 448.0f) v = 448.0f; + if (v < -448.0f) v = -448.0f; + st_dt(q->dtype, q->data, qb + (p * n + k0 + i) * qs, v); + } + stt(s, rowoff(s, r, P * ngrp) + (p * ngrp + gi) * laststride(s), scl); + } + } + } + return RAD_OK; +} + /* ---------------------------------------------------------------- the Gram accumulator * * h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the DEQUANTISED E4M3 input, or diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index abc3ba3c..17b4d554 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -201,6 +201,13 @@ static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") }; /* No `asum`: that output exists for the asymmetric integer grids and an fp8 grid is symmetric by * construction (libr4d/r4d_rows.cpp says the same). */ static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; +/* ParoQuant's activation quantiser: a rotation per part in front of quant_act_fp8's. The three + * tables are the "givens" encoding's (abi/rad_encoding.h) and are WEIGHT operands, so they are + * resolved, moved and placed with the weight they belong to. */ +static const RadParamSpec pGivensQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), + P_INT("stages"), P_INT("parts") }; +static const RadOperandSpec oGivensQuant[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), + OUT("q"), OUT("scale") }; /* ---- the fp8 fusions ---------------------------------------------------------------------- * A fused op's operands are the unfused pair's minus the tensor between them, and `out_bf16` @@ -264,7 +271,10 @@ static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD OUT("y") }; static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), - P_STR("dtype") }; + P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2") }; +/* The bias form has no parts: a fused projection rotated apart is the plain product's. */ +static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), + P_STR("dtype") }; /* `a_sum` and `b_ref` are libr4d's, appended AFTER `y` so docs/OPS.md's list stays a positional * prefix: the asymmetric 4-bit and 2-bit grids subtract the activation's per-group code sums, and * mxfp4 folds a per-output-row reference exponent. Neither is expressible as a weight aux stream, @@ -790,6 +800,15 @@ static const RadOpSchema kSchemas[] = { "previous pick. `hp` absent is a plane of ones, which drops the form to a plain low-rank " "bigram. Serial in l by construction -- the predecessor is not known until the previous step " "has been decided." }, +{ "givens_quant_act_fp8", ARR(pGivensQuant), ARR(oGivensQuant), + "ParoQuant's activation quantiser: x is divided by the channel scale `rscale`, rotated by " + "`stages` rounds of disjoint Givens pairs (a' = a cos t + b sin t, b' = b cos t - a sin t, pairs " + "as column indices of the row, each inside one scale group), then quantised as quant_act_fp8 " + "does: scale = amax / 448 per `group`. `parts` rotated copies are written side by side -- q is " + "[M, parts * n], scale [M, parts * n / group] -- part p from table rows [p * stages, (p + 1) * " + "stages) of `pairs` and `angle` and row p of `rscale`: a fused projection's pieces were each " + "rotated on their own. Only a weight stored with the \"givens\" transform reads the result; " + "it is NOT quant_act_fp8's output in either direction." }, { "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "A Walsh-Hadamard rotation of width `group` along n, then symmetric E4M3 per group: scale = " "amax(rotated) / 448, shaped [M, n/group] in f32. n must be a multiple of `group` -- a rotation " @@ -831,7 +850,7 @@ static const RadOpSchema kSchemas[] = { "gemm_nt with quantised operands. The group sub-sum is accumulated from the raw codes and " "scaled once per group, which is what an int8 or fp8 WMMA kernel does. Scale streams are " "[rows, groups] or [rows]; an mxfp4 weight's u8 scale stream is read as OCP e8m0." }, -{ "gemm_nt_q_bias", ARR(pGemmQ), ARR(oGemmQBias), "gemm_nt_q with a per-column bias." }, +{ "gemm_nt_q_bias", ARR(pGemmQBias), ARR(oGemmQBias), "gemm_nt_q with a per-column bias." }, { "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged), "Paged attention over kv_cache[num_blocks, kv_heads, block_size, 2*head_dim] (K then V per " @@ -1152,6 +1171,10 @@ SIMPLE("ref_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm", SIMPLE("ref_dflash_select", "dflash_select", "draft", "DFlash2's greedy walk over the candidate lattice", "i32 candidates, bf16 codebooks, i32 tokens out", ref_dflash_select), +SIMPLE("ref_givens_quant_act_fp8", "givens_quant_act_fp8", "quant", + "channel scale and Givens rotations per part, then the block-scaled E4M3 quantiser", + "float in, fp8_e4m3 out, f32 scale per group; int32 pairs, f32 angles and channel scales", + ref_givens_quant_act_fp8), SIMPLE("ref_had_quant_act_fp8", "had_quant_act_fp8", "quant", "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; n a multiple of group", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 684aa57a..f06563bb 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -828,6 +828,14 @@ int ref_gram_accum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("gram_accum", operand, out); } +/* DECLINED, on purpose: `pairs` must be a pairing of each group's columns (every column once a + * stage, the partner inside the group), and a described operand can only be drawn, not constructed + * -- an index draw has repeats, and a Givens stage over a repeated column is not a rotation. A case + * built from one would compare two implementations of nothing. r4d_selftest builds real pairings. */ +int ref_givens_quant_act_fp8_shape(const RadParam*, int, int, RadOpdDesc*) { + return RAD_E_UNSUPPORTED; +} + int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index ec553ff0..40cad408 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -261,7 +261,8 @@ TEST(op_vocabulary) { "embed_lookup_q", "cast", "scale_rows", "softmax", - "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "had_quant_act_i8", "gram_accum", + "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "had_quant_act_i8", + "gram_accum", /* The fused fp8 forms. A host run needs EVERY op covered, so these are what stands * between a host-backend run and "site 'host' is unavailable for this band". */ "rmsnorm_quant_fp8", "gated_quant_fp8", "gemm_nt_q_gated", "dflash_select", @@ -1456,6 +1457,144 @@ TEST(op_gemm_nt_q) { CHECK_EQ(y3.at(1), (3 * 2.0f + 4 * 4.0f) * 1.0f); } +/* A weight whose row PARTS meet their own copy of the activation: parts = 2 rows [0, 16) and + * [16, 32) over K = 128, the copies side by side in one row of `a`. The parted product must be the + * plain product of each part's rows against its own copy -- computed here as two plain calls. */ +TEST(op_gemm_nt_q_parts_read_their_own_activation_copy) { + const int64_t M = 3, N = 32, K = 128, P = 2; + uint32_t rng = 7; + auto nxt = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 9; }; + T a2(RAD_F8E4M3, {M, P * K}); + std::vector av((size_t)(M * P * K)); + for (auto& v : av) v = (float)((int)(nxt() % 15) - 7) * 0.25f; + a2.f(av); + T as2(RAD_F32, {M, P}); + std::vector asv((size_t)(M * P)); + for (auto& v : asv) v = 0.01f * (float)(1 + nxt() % 9); + as2.f(asv); + T b_(RAD_FP4E2M1, {N, K}); + for (int64_t i = 0; i < N * K / 2; ++i) b_.mem[(size_t)i] = (uint8_t)nxt(); + T bs(RAD_U8, {N, K / 32}); + for (int64_t i = 0; i < N * K / 32; ++i) bs.mem[(size_t)i] = (uint8_t)(124 + nxt() % 5); + + T y(RAD_BF16, {M, N}); + A a; a.t(a2).t(as2).t(b_).t(bs).t(y).tnull().tnull() + .i("M", M).i("N", N).i("K", K).i("group", 32).s("dtype", "mxfp4a8").i("pb1", 16); + CHECK_OK(run("gemm_nt_q", a)); + + for (int64_t p = 0; p < P; ++p) { + T ap(RAD_F8E4M3, {M, K}), asp(RAD_F32, {M, 1}); + std::vector v1((size_t)(M * K)), v2((size_t)M); + for (int64_t m = 0; m < M; ++m) { + for (int64_t k = 0; k < K; ++k) v1[(size_t)(m * K + k)] = av[(size_t)(m * P * K + p * K + k)]; + v2[(size_t)m] = asv[(size_t)(m * P + p)]; + } + ap.f(v1); + asp.f(v2); + T bp(RAD_FP4E2M1, {N / P, K}), bsp(RAD_U8, {N / P, K / 32}); + std::memcpy(bp.mem.data(), b_.mem.data() + p * (N / P) * K / 2, (size_t)((N / P) * K / 2)); + std::memcpy(bsp.mem.data(), bs.mem.data() + p * (N / P) * K / 32, (size_t)((N / P) * K / 32)); + T yp(RAD_BF16, {M, N / P}); + A c; c.t(ap).t(asp).t(bp).t(bsp).t(yp).tnull().tnull() + .i("M", M).i("N", N / P).i("K", K).i("group", 32).s("dtype", "mxfp4a8"); + CHECK_OK(run("gemm_nt_q", c)); + int bad = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t n = 0; n < N / P; ++n) + if (y.at(m * N + p * (N / P) + n) != yp.at(m * (N / P) + n)) ++bad; + CHECK_EQ(bad, 0); + } +} + +/* ParoQuant's activation quantiser. With zero angles and unit channel scales it IS quant_act_fp8; + * with real rotations the dequantised row is the rotated row to within the fp8 grid, and the + * rotation preserves the row's norm -- checked per part, against a double-precision rotation. */ +TEST(op_givens_quant_act_fp8) { + const int64_t M = 3, n = 256, S = 3, P = 2, G = 128; + uint32_t rng = 99; + auto nxt = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; }; + auto frand = [&](float lo, float hi) { return lo + (hi - lo) * (float)(nxt() % 10000) / 10000.0f; }; + T x(RAD_BF16, {M, n}); + std::vector xv((size_t)(M * n)); + for (auto& v : xv) v = frand(-3.0f, 3.0f); + x.f(xv); + for (int64_t m = 0; m < M; ++m) xv[(size_t)(m * n + 7)] = 0; // a zero in the mix + // a pairing of each group of 128 per stage per part + T pr(RAD_I32, {P * S, n}), an(RAD_F32, {P * S, n / 2}), rs(RAD_F32, {P, n}); + for (int64_t ps = 0; ps < P * S; ++ps) + for (int64_t g = 0; g < n / G; ++g) { + std::vector perm((size_t)G); + for (int i = 0; i < G; ++i) perm[(size_t)i] = (int32_t)(g * G + i); + for (int i = (int)G - 1; i > 0; --i) std::swap(perm[(size_t)i], perm[nxt() % (i + 1)]); + for (int i = 0; i < G; ++i) st_int(RAD_I32, pr.t.data, ps * n + g * G + i, perm[(size_t)i]); + } + std::vector av((size_t)(P * S * n / 2)), sv((size_t)(P * n)); + for (auto& v : av) v = frand(-3.0f, 3.0f); + for (auto& v : sv) v = frand(0.5f, 2.0f); + an.f(av); + rs.f(sv); + + T q(RAD_F8E4M3, {M, P * n}), s(RAD_F32, {M, P * n / G}); + A a; a.t(x).t(pr).t(an).t(rs).t(q).t(s) + .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("stages", S).i("parts", P); + CHECK_OK(run("givens_quant_act_fp8", a)); + double worst = 0; + int bad_norm = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t p = 0; p < P; ++p) { + std::vector b((size_t)n); + double n0 = 0; + for (int64_t k = 0; k < n; ++k) { + b[(size_t)k] = (double)x.at(m * n + k) / (double)sv[(size_t)(p * n + k)]; + n0 += b[(size_t)k] * b[(size_t)k]; + } + for (int64_t st = 0; st < S; ++st) + for (int64_t j = 0; j < n / 2; ++j) { + const int64_t ia = pr.iat((p * S + st) * n + 2 * j), ib = pr.iat((p * S + st) * n + 2 * j + 1); + const double t = av[(size_t)((p * S + st) * (n / 2) + j)], c = std::cos(t), sn = std::sin(t); + const double va = b[(size_t)ia], vb = b[(size_t)ib]; + b[(size_t)ia] = va * c + vb * sn; + b[(size_t)ib] = vb * c - va * sn; + } + double n1 = 0; + for (int64_t k = 0; k < n; ++k) n1 += b[(size_t)k] * b[(size_t)k]; + if (std::fabs(n1 - n0) > 1e-9 * n0) ++bad_norm; + for (int64_t g = 0; g < n / G; ++g) { + double amax = 0; + for (int64_t i = 0; i < G; ++i) amax = std::max(amax, std::fabs(b[(size_t)(g * G + i)])); + const double sc = s.at(m * (P * n / G) + p * (n / G) + g); + CHECK(std::fabs(sc - amax / 448.0) < 1e-5 * amax / 448.0 + 1e-12); + for (int64_t i = 0; i < G; ++i) { + const double deq = (double)q.at(m * P * n + p * n + g * G + i) * sc; + worst = std::max(worst, std::fabs(deq - b[(size_t)(g * G + i)]) / amax); + } + } + } + CHECK_EQ(bad_norm, 0); + CHECK(worst < 0.04); // half an e4m3 step at the top of the range is 1/16 of 1/2 + + // zero angles, unit scales: exactly quant_act_fp8 + T an0(RAD_F32, {P * S, n / 2}), rs1(RAD_F32, {P, n}); + std::vector ones((size_t)(P * n), 1.0f); + rs1.f(ones); + T q1(RAD_F8E4M3, {M, P * n}), s1(RAD_F32, {M, P * n / G}); + A b; b.t(x).t(pr).t(an0).t(rs1).t(q1).t(s1) + .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("stages", S).i("parts", P); + CHECK_OK(run("givens_quant_act_fp8", b)); + T q2(RAD_F8E4M3, {M, n}), s2(RAD_F32, {M, n / G}); + A c; c.t(x).t(q2).t(s2).i("M", M).i("n", n).i("group", G).s("dtype", "bf16"); + CHECK_OK(run("quant_act_fp8", c)); + int diff = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t p = 0; p < P; ++p) { + for (int64_t k = 0; k < n; ++k) + if (q1.mem[(size_t)(m * P * n + p * n + k)] != q2.mem[(size_t)(m * n + k)]) ++diff; + for (int64_t g = 0; g < n / G; ++g) + if (s1.at(m * (P * n / G) + p * (n / G) + g) != s2.at(m * (n / G) + g)) ++diff; + } + CHECK_EQ(diff, 0); +} + /* A BLOCK GRID WHOSE LAST BLOCK IS PARTIAL, on both axes. K = 300 at 128 is three scales over 128, * 128 and 44 columns; N = 129 is two row blocks, the second of one row, and N = 300 is three. The * expected value of every output is written out from that definition: with every code 1, output From 36e3b78c765a9590e03e6807d7df7d342efcd63c Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Wed, 7 Oct 2026 23:52:17 +0000 Subject: [PATCH 03/17] libr4d: givens_quant_act_fp8 kernel; mxfp4a8 GEMMs take parts as launches over windows The rotate+scale+quantise kernel does a (part, group) per wave with the stages' tables prefetched. The three MXFP4 GEMM rows learn row pitches (lda, ldws, ldc) and launch once per weight part; the layout hook accepts the codes/exponent planes of a givens-encoded weight. r4d_selftest checks the kernel against an f64 rotation and every GEMM row's parts against the planes' meaning. --- libr4d/CMakeLists.txt | 1 + libr4d/r4d.h | 9 +- libr4d/r4d_gemm_args.h | 57 +++++++- libr4d/r4d_gemm_mxfp4a8_decode.hip | 81 +++++++---- libr4d/r4d_gemm_mxfp4a8_nt_m64.hip | 45 ++++-- libr4d/r4d_gemm_mxfp4a8_tiled.hip | 68 +++++---- libr4d/r4d_givens_quant_act_fp8.hip | 206 ++++++++++++++++++++++++++++ libr4d/r4d_layout.cpp | 26 +++- libr4d/r4d_plugin.h | 2 + libr4d/r4d_rows.cpp | 52 +++++++ libr4d/r4d_selftest.cpp | 166 ++++++++++++++++++++-- 11 files changed, 626 insertions(+), 87 deletions(-) create mode 100644 libr4d/r4d_givens_quant_act_fp8.hip diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index d36d4198..b37c6bab 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -123,6 +123,7 @@ set(R4D_UNITS "r4d_gemm_fp8a16_nt_m1|" "r4d_gemm_fp8a8|" "r4d_quant_act_fp8|" + "r4d_givens_quant_act_fp8|" "r4d_fused_quant_fp8|" "r4d_gram_accum_fp8|" "r4d_qsa_block_key_bf16|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index b497ab09..22c1d6ce 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -570,7 +570,8 @@ void r4d_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, i // as_group 0 = one f32 activation scale per row, 128 = one per (row, 128 of K) at row stride as_rs. void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, - int as_group, int as_rs, long stream); + int as_group, int as_rs, long stream, + int lda = 0, int ldws = 0, int ldc = 0); int r4d_gemm_mxfp4a8_nt_m64_max_m(void); int r4d_gemm_mxfp4a8_nt_m64_group(void); // The same weight tiled for PREFILL: a 256-row block reads A fragments straight from a @@ -579,8 +580,10 @@ int r4d_gemm_mxfp4a8_nt_m64_group(void); // the per-wave column width in 16-column fragments. as_group 0 = one f32 activation scale per row, // 128 = one per (row, 128 of K) at row stride as_rs. void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c, - int M, int K, int N, int TN, int as_group, int as_rs, long stream); -void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream); + int M, int K, int N, int TN, int as_group, int as_rs, long stream, + int ldws = 0, int ldc = 0); +// `lda` is the activation's row pitch in bytes (0 = K), for a window of a wider plane. +void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda = 0); long r4d_mxfp4a8_tile_a_bytes(int M, int K); int r4d_gemm_mxfp4a8_tiled_group(void); // The DECODE band (M <= 128) is r4d_rad_gemm_mxfp4a8_decode alone: its split-K partial is the op's diff --git a/libr4d/r4d_gemm_args.h b/libr4d/r4d_gemm_args.h index 3c534d32..37aab7a6 100644 --- a/libr4d/r4d_gemm_args.h +++ b/libr4d/r4d_gemm_args.h @@ -326,7 +326,7 @@ struct GemmOps { * the block-scaled fp8 family's quantisers, which every fused producer in arch/common writes) is * group 128, read at the operand's own row stride. Anything else is refused by shape: a grid read * at the wrong width is an answer that is merely wrong. */ -static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) { +static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs, int parts = 1) { const RadTensor* s = g.ascale; if (!s || g.M <= 0) return R4D_NO(RAD_E_INVAL); long long cols = 1, rstride = 1; @@ -340,11 +340,62 @@ static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) { rstride = cols; } const long long kb = (g.K + 127) / 128; - if (cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; } - if (cols == kb && rstride >= kb) { *group = 128; *rs = (int)rstride; return RAD_OK; } + /* PARTS: the activation's copies sit side by side in a row, so its scale row is `parts` times + * as long; each part reads its own kb of them at the row stride. */ + if (parts == 1 && cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; } + if (cols == kb * parts && rstride >= kb * parts) { *group = 128; *rs = (int)rstride; return RAD_OK; } return R4D_NO(RAD_E_SHAPE); } +/* THE PARTS OF A PARTITIONED MXFP4 WEIGHT (gemm_nt_q's `pb1`/`pb2`), as launches. + * + * A fused projection whose pieces were rotated apart (ParoQuant: gate|up, q|k|v) has one copy of + * the activation a piece, written side by side in a row of `a` -- [M, parts * K] -- and its scales + * the same, so the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet THEIR copy. A part is + * then the ordinary product over a window of the planes: the activation from byte p * K of each row + * and its scales from p * ceil(K/128), the fragment-order weight from tile n0 / 16 (its bytes are + * n0 * K / 2 in), the exponents and reference from column n0, the output from column n0, the last + * three with the full planes' row pitch. So the kernels learn only row pitches (`lda`, `ldws`, + * `ldc`) and a part is one launch of the kernel the shape would have picked anyway. + * + * `pb1` = 0 is one part and `pb2` = 0 ends the second part at N, as libref reads them. Bounds are + * whole 16-row tiles (the weight's fragment unit). Returns the parts in `p`, K corrected to the + * op's own (gemm_ops read the row's width, which is parts * K), and the activation's row pitch in + * `lda`. */ +struct MxParts { + int n = 1; + long long n0[3] = { 0, 0, 0 }, n1[3] = { 0, 0, 0 }; + long long lda = 0; /* 0: the plane's own K */ +}; + +static inline int mx_parts(const RadArgs* a, GemmOps* g, MxParts* p) { + const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0); + p->n = 1; + p->n0[0] = 0; + p->n1[0] = g->N; + p->lda = 0; + if (pb1 <= 0 && pb2 <= 0) return RAD_OK; + const long long K = r4d_geti_or(a, "K", 0); + if (K <= 0) return R4D_NO(RAD_E_INVAL); + const long long e1 = pb1 > 0 ? (pb1 < g->N ? pb1 : g->N) : g->N; + long long e2 = pb2 > 0 ? (pb2 < g->N ? pb2 : g->N) : g->N; + if (e2 < e1) e2 = e1; + const long long bound[4] = { 0, e1, e2, g->N }; + const int segs = e2 < g->N ? 3 : (e1 < g->N ? 2 : 1); + if (g->K != (long long)segs * K || (e1 % 16) || (e2 % 16)) return R4D_NO(RAD_E_SHAPE); + p->n = 0; + for (int i = 0; i < 3; ++i) + if (bound[i + 1] > bound[i]) { + p->n0[p->n] = bound[i]; + p->n1[p->n] = bound[i + 1]; + ++p->n; + } + if (p->n != segs) return R4D_NO(RAD_E_SHAPE); /* an empty middle part has no copy to meet */ + p->lda = g->K; + g->K = K; + return RAD_OK; +} + /* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major and the weight is * an opaque packed blob whose element count the layout hook owns -- so the weight's SHAPE is not * checked here beyond being present, which is deliberate: the byte count that matters is the one diff --git a/libr4d/r4d_gemm_mxfp4a8_decode.hip b/libr4d/r4d_gemm_mxfp4a8_decode.hip index e45b6ed8..b397b50e 100644 --- a/libr4d/r4d_gemm_mxfp4a8_decode.hip +++ b/libr4d/r4d_gemm_mxfp4a8_decode.hip @@ -119,8 +119,8 @@ template static __device__ __forceinline__ void mxd_epilogue( const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs, const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt, - __hip_bfloat16* __restrict__ C, int M, int N, int n0, int wave, int col, int kb8, int ks, - int kb_end, unsigned* s_last, float* sR) { + __hip_bfloat16* __restrict__ C, int M, int N, int ldc, int n0, int wave, int col, int kb8, + int ks, int kb_end, unsigned* s_last, float* sR) { constexpr int NTHR = R4D_MXD_DWN * 32, BND = R4D_MXD_DWN * 16; constexpr int ROWS = R4D_MXD_MTILE * DTM; const int tid = threadIdx.x; @@ -149,7 +149,7 @@ static __device__ __forceinline__ void mxd_epilogue( #pragma unroll for (int e = 0; e < 8; ++e) o.h[e] = (__hip_bfloat16)(ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i]); - *(mxd_u4*)(C + (size_t)m * N + nb) = o.v; + *(mxd_u4*)(C + (size_t)m * ldc + nb) = o.v; } } } @@ -189,7 +189,7 @@ static __device__ __forceinline__ void mxd_epilogue( float sum = 0.f; #pragma unroll for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn]; - C[(size_t)m * N + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs])); + C[(size_t)m * ldc + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs])); } } } @@ -199,7 +199,8 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern const unsigned char* __restrict__ A, const float* __restrict__ As, const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt, - __hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) { + __hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs, int lda, int ldws, + int ldc) { constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32; constexpr int ROWS = R4D_MXD_MTILE * DTM; constexpr int STR = DBK + R4D_MXD_PAD; @@ -245,7 +246,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern if (idx < ROWS * DBK) { const int r = idx / DBK, c = idx % DBK; const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate - *(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c); + *(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * lda + k0 + c); } } // ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3 @@ -269,7 +270,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP; #pragma unroll for (int q = 0; q < 2; ++q) { - const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * N + gc + q]); + const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * ldws + gc + q]); unsigned int lo, hi; r4d_mxfp4_unpack8(q ? wv[1] : wv[0], d, &lo, &hi); *(mxd_u2*)(&sW[(r + q) * STR + kloc]) = mxd_u2{lo, hi}; @@ -302,7 +303,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern __syncthreads(); } const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0; - mxd_epilogue(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks, + mxd_epilogue(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks, kb_end, &s_last, sR); } @@ -318,7 +319,8 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_ker const unsigned char* __restrict__ A, const float* __restrict__ As, const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt, - __hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) { + __hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs, int lda, int ldws, + int ldc) { constexpr int DTM = 1, VEC = 4; constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32; constexpr int ROWS = R4D_MXD_MTILE * DTM; @@ -381,7 +383,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_ker if (idx < ROWS * DBK) { const int r = idx / DBK, c = idx % DBK; const int rc = r < M - 1 ? r : M - 1; - ra[j] = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c); + ra[j] = *(const mxd_u4*)(A + (size_t)rc * lda + k0 + c); } } const int kstep0 = k0 / 16; @@ -392,7 +394,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_ker rw[it] = mxd_ld((const wv_t*)&Wp[slot]); const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP; #pragma unroll - for (int q = 0; q < VEC; ++q) rd[it][q] = (int)Ws[(size_t)blk * N + s_gc[it] + q]; + for (int q = 0; q < VEC; ++q) rd[it][q] = (int)Ws[(size_t)blk * ldws + s_gc[it] + q]; } }; auto store = [&]() { @@ -450,7 +452,7 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_ker __syncthreads(); } const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0; - mxd_epilogue(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks, + mxd_epilogue(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks, kb_end, &s_last, sR); } @@ -508,7 +510,7 @@ long mxd_partial_bytes(int M, int N, int ks) { void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N, int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch, - long scratch_bytes) { + long scratch_bytes, int lda, int ldws, int ldc) { if (M < 1 || M > R4D_MXD_MTILE * R4D_MXD_MAX_TM) throw std::runtime_error("r4d gemm_mxfp4a8_decode: M must be 1..128"); if (N < 16 || N % 16 || N > R4D_MXD_MAX_N) @@ -543,10 +545,10 @@ void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, auto Cp = (__hip_bfloat16*)c; #define MXD_L(BK_, KS_, TM_, NT_, AB_) \ hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode_kernel), grid, block, 0, \ - st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs) + st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc) #define MXD_L1(BK_, KS_, NT_, AB_) \ hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode1_kernel), grid, block, 0, st, \ - Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs) + Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc) #define MXD_AB(BK_, KS_, TM_, NT_) \ { if (ablk) MXD_L(BK_, KS_, TM_, NT_, true); else MXD_L(BK_, KS_, TM_, NT_, false); } #define MXD_NT(BK_, KS_, TM_) \ @@ -583,35 +585,58 @@ extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) { int rc = gemm_ops(a, &g, 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_mxfp4a8_decode_max_m() || g.N > R4D_MXD_MAX_N) return R4D_NO(RAD_E_SHAPE); - if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL); 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); - R4D_TRY("gemm_mxfp4a8_decode", - mxd_launch(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), - r4d_addr(g.bscale), 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)); + const long long kb = (g.K + 127) / 128; + 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_mxfp4a8_decode", + mxd_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.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 core sizes the op's scratch from this. `M` is the band's widest, and a narrower M can split * wider (the fill rule asks for more blocks at M <= 24), so the size is the widest split over the - * band times its widest M -- an upper bound on every launch the band can make. */ + * band times its widest M -- an upper bound on every launch the band can make. A partitioned + * weight launches each part at ITS rows, which splits wider than the whole would, so the bound is + * the largest of the parts' (they run one after another and share the scratch). */ extern "C" int64_t r4d_rad_gemm_mxfp4a8_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_mxfp4a8_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 = mxd_plan(m, (int)K, (int)N, t.ks, t.bk, t.nt).ks; - if (k > ks) ks = k; + const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0); + const long long e1 = pb1 > 0 ? (pb1 < N ? pb1 : N) : N; + long long e2 = pb2 > 0 ? (pb2 < N ? pb2 : N) : N; + if (e2 < e1) e2 = e1; + const long long bound[4] = { 0, e1, e2, N }; + 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 = mxd_plan(m, (int)K, (int)np, t.ks, t.bk, t.nt).ks; + if (k > ks) ks = k; + } + const int64_t b = (int64_t)mxd_partial_bytes((int)M, (int)np, ks); + if (b > worst) worst = b; } - return (int64_t)mxd_partial_bytes((int)M, (int)N, ks); + return worst; } diff --git a/libr4d/r4d_gemm_mxfp4a8_nt_m64.hip b/libr4d/r4d_gemm_mxfp4a8_nt_m64.hip index a8cdfb9a..d600149b 100644 --- a/libr4d/r4d_gemm_mxfp4a8_nt_m64.hip +++ b/libr4d/r4d_gemm_mxfp4a8_nt_m64.hip @@ -115,7 +115,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel( const unsigned char* __restrict__ A, const float* __restrict__ As, const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C, - int M, int K, int N, int WV, int SK, int as_rs) { + int M, int K, int N, int WV, int SK, int as_rs, int lda, int ldws, int ldc) { extern __shared__ float red[]; const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32; const int col_local = wave / SK, ksplit = wave % SK; @@ -189,7 +189,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel( for (int i = 0; i < MT; i++) { int r = (mt0 + i) * 16 + nlane; r = r < M - 1 ? r : M - 1; - const unsigned int* pa = (const unsigned int*)(A + (size_t)r * K + kg + mhalf); + const unsigned int* pa = (const unsigned int*)(A + (size_t)r * lda + kg + mhalf); af[i][0] = (int)pa[0]; af[i][1] = (int)pa[1]; } @@ -200,7 +200,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel( // wave reads 128 contiguous bytes. In checkpoint order these would be sixteen rows K/2 bytes // apart -- a fully strided read on the operand that dominates traffic. const unsigned int wv = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane]; - const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * N + n])); + const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * ldws + n])); #pragma unroll for (int i = 0; i < MT; i++) acc[j][i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(af[i], wf, acc[j][i]); @@ -232,7 +232,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel( if (n >= N || m >= M) continue; float v = 0.f; for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off]; - C[(size_t)m * N + n] = + C[(size_t)m * ldc + n] = (__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * (ABLK ? 1.f : As[m])); } } @@ -243,7 +243,14 @@ extern "C" int r4d_gemm_mxfp4a8_nt_m64_group(void) { return R4D_GEMM_MXFP4_GROUP extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, - int as_group, int as_rs, long stream) { + int as_group, int as_rs, long stream, + int lda, int ldws, int ldc) { + // The operands of one PART of a partitioned weight (ParoQuant) are windows of larger planes: + // the activation a row of lda bytes, the exponents a row of ldws, the output a row of ldc. + // 0 is the plane's own width, which is every other caller. + if (!lda) lda = K; + if (!ldws) ldws = N; + if (!ldc) ldc = N; if (M < 1 || M > R4D_GEMM_MXFP4_MAX_M) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: M must be 1..64"); if (N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: N must be a multiple of 16"); @@ -273,9 +280,10 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l #define LAUNCH(MTv, NPv) \ do { \ if (ablk) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel), grid, block, \ - smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \ + smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs, lda, ldws, ldc); \ else hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel), grid, block, \ - smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \ + smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs, \ + lda, ldws, ldc); \ } while (0) #define LAUNCH_MB(NPv) switch (MB) { \ case 1: LAUNCH(1, NPv); break; \ @@ -309,18 +317,27 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) { * so gemm_nt_q carries it as a trailing optional weight operand. Without it the fold has no * reference and every element would be scaled against zero. */ if (!g.bref) return R4D_NO(RAD_E_INVAL); + MxParts mp; + rc = mx_parts(a, &g, &mp); + if (rc != RAD_OK) return rc; const int group = r4d_gemm_mxfp4a8_nt_m64_group(); 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; Cfg c; rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c); if (rc != RAD_OK) return rc; - R4D_TRY("gemm_mxfp4a8_nt_m64", - r4d_gemm_mxfp4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), - r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y), - (int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, - as_group, as_rs, (long)(uintptr_t)s)); + const long long kb = (g.K + 127) / 128; + 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_mxfp4a8_nt_m64", + r4d_gemm_mxfp4a8_nt_m64(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.bref) + n0, r4d_addr(g.y) + n0 * 2, + (int)g.M, (int)g.K, (int)np, c.wv, c.sk, c.mb, c.npw, + as_group, as_rs, (long)(uintptr_t)s, + (int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N)); + } return RAD_OK; } - diff --git a/libr4d/r4d_gemm_mxfp4a8_tiled.hip b/libr4d/r4d_gemm_mxfp4a8_tiled.hip index 4ebf5b74..6330e288 100644 --- a/libr4d/r4d_gemm_mxfp4a8_tiled.hip +++ b/libr4d/r4d_gemm_mxfp4a8_tiled.hip @@ -101,7 +101,7 @@ static __device__ __forceinline__ void mxt_lds_barrier() { // contiguous and each lane reads one 8-byte group of one row. __global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel( const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K, - long long slots) { + long long slots, int lda) { const long long o = (long long)blockIdx.x * 256 + threadIdx.x; if (o >= slots) return; const int ks = K / 16; @@ -110,7 +110,7 @@ __global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel( const int mt = (int)(f / ks), kst = (int)(f % ks); const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8; mxt_u2 v = { 0u, 0u }; - if (r < M) v = *(const mxt_u2*)(A + (size_t)r * K + k); + if (r < M) v = *(const mxt_u2*)(A + (size_t)r * lda + k); *(mxt_u2*)(AT + o * 8) = v; } @@ -119,7 +119,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( const unsigned char* __restrict__ AT, const float* __restrict__ As, const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C, - int M, int K, int N, int as_rs) { + int M, int K, int N, int as_rs, int ldws, int ldc) { constexpr int TM = R4D_MXT_TM, WN = R4D_MXT_WN, NTHR = R4D_MXT_NTHR, BMF = R4D_MXT_BMF; constexpr int NS = LBK / 16, STR = LBK + R4D_MXT_PAD, BNF = WN * TN * 16; constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32; @@ -213,14 +213,14 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( if constexpr (WSLOTS == 4) { const mxt_u4 v = *(const mxt_u4*)src; wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3]; - wsw = *(const unsigned int*)(Ws + (size_t)blk * N + wrc[it]); + wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]); } else if constexpr (WSLOTS == 2) { const mxt_u2 v = *(const mxt_u2*)src; wq[0] = v[0]; wq[1] = v[1]; - wsw = *(const unsigned short*)(Ws + (size_t)blk * N + wrc[it]); + wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]); } else { wq[0] = *src; - wsw = Ws[(size_t)blk * N + wrc[it]]; + wsw = Ws[(size_t)blk * ldws + wrc[it]]; } #pragma unroll for (int q = 0; q < WSLOTS; ++q) { @@ -306,7 +306,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23); o.h[e] = (__hip_bfloat16)(acc[i][j][e] * rf * sc[i]); } - *(mxt_u4*)(C + (size_t)m * N + nb) = o.v; + *(mxt_u4*)(C + (size_t)m * ldc + nb) = o.v; } } } @@ -317,17 +317,20 @@ extern "C" long r4d_mxfp4a8_tile_a_bytes(int M, int K) { return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K; } -extern "C" void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream) { +extern "C" void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda) { + if (!lda) lda = K; if (M < 1) throw std::runtime_error("r4d mxfp4a8_tile_a: M must be >= 1"); if (K < 16 || K % 16) throw std::runtime_error("r4d mxfp4a8_tile_a: K must be a multiple of 16"); const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32; hipLaunchKernelGGL(r4d_mxfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256), 0, - (hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots); + (hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots, lda); } extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c, int M, int K, int N, int TN, int as_group, int as_rs, - long stream) { + long stream, int ldws, int ldc) { + if (!ldws) ldws = N; + if (!ldc) ldc = N; if (M < 1) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: M must be >= 1"); if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: N must be a multiple of 16"); if (K < R4D_MXT_KUNIT || K % R4D_MXT_KUNIT) @@ -355,7 +358,7 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l hipStream_t st = (hipStream_t)stream; #define MXT_LAUNCH(TNv, LBKv, ABv) \ hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel), grid, block, 0, st, Ap, Sp, \ - Wp, Zp, Rp, Cp, M, K, N, as_rs) + Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc) if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); } else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); } else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); } @@ -364,35 +367,52 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l // ============================================================== the plugin ABI entry point // The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there. +// A partitioned weight re-tiles each part's copy of the activation into its own slab of the +// scratch and runs the GEMM over that part's rows (mx_parts). extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1); if (rc != RAD_OK) return rc; if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE); - if (g.K % R4D_MXT_KUNIT) return R4D_NO(RAD_E_SHAPE); if (!g.ascale) return R4D_NO(RAD_E_INVAL); /* The per-row reference exponent, as in r4d_rad_gemm_mxfp4a8_m64: without it the fold has no * reference and every element would be scaled against zero. */ if (!g.bref) return R4D_NO(RAD_E_INVAL); - int as_group = 0, as_rs = 1; - rc = mx_ascale_grid(g, &as_group, &as_rs); + MxParts mp; + rc = mx_parts(a, &g, &mp); if (rc != RAD_OK) return rc; - if (!a->scratch || a->scratch_bytes < r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K)) - return R4D_NO(RAD_E_INVAL); + if (g.K % R4D_MXT_KUNIT) return R4D_NO(RAD_E_SHAPE); + int as_group = 0, as_rs = 1; + rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n); + if (rc != RAD_OK) return rc; + const long long slab = r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K); + if (!a->scratch || a->scratch_bytes < slab * mp.n) return R4D_NO(RAD_E_INVAL); R4dMxTileCfg t; r4d_cfg_mxfp4_tiled(a, &t); - const long at = (long)(uintptr_t)a->scratch; - R4D_TRY("gemm_mxfp4a8_tiled", - r4d_mxfp4a8_tile_a(r4d_addr(g.a), at, (int)g.M, (int)g.K, (long)(uintptr_t)s); - r4d_gemm_mxfp4a8_tiled(at, r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), - 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)); + const long kb = (long)((g.K + 127) / 128); + for (int p = 0; p < mp.n; ++p) { + const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p]; + const long at = (long)(uintptr_t)a->scratch + (long)(p * slab); + R4D_TRY("gemm_mxfp4a8_tiled", + r4d_mxfp4a8_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_mxfp4a8_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.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 core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of - * the activation, whole 16-row fragments. */ + * the activation, whole 16-row fragments -- one a part. */ extern "C" int64_t r4d_rad_gemm_mxfp4a8_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_mxfp4a8_tile_a_bytes((int)M, (int)K); + const long long N = r4d_geti_or(a, "N", 0); + const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0); + const long long e1 = pb1 > 0 ? (pb1 < N ? pb1 : N) : N; + long long e2 = pb2 > 0 ? (pb2 < N ? pb2 : N) : N; + if (e2 < e1) e2 = e1; + const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K) * parts; } diff --git a/libr4d/r4d_givens_quant_act_fp8.hip b/libr4d/r4d_givens_quant_act_fp8.hip new file mode 100644 index 00000000..e8cc1fe9 --- /dev/null +++ b/libr4d/r4d_givens_quant_act_fp8.hip @@ -0,0 +1,206 @@ +// ParoQuant's activation side: channel scale, Givens rotations, then the per-(row, 128-column) +// symmetric E4M3 quantiser of r4d_quant_act_fp8.hip. The weight it pairs with is stored as +// v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product with +// x' = x . D^-1 . G_1 ... G_S is : the rotation is the activation's to do, once a token, and +// the weight is read by the plain MXFP4 GEMM unchanged. +// +// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- +// that is how the checkpoint is trained, and the converter refuses one that does -- so a group is a +// closed system: its 128 values are rotated by S stages of 64 disjoint pairs and then quantised +// with ONE scale. A wave owns a group. The values sit in LDS (128 floats a wave, no barrier +// needed: a wave's LDS accesses are in order, and the pairs of a stage are disjoint so no two lanes +// touch one address), each lane takes two pairs a stage, and the absmax is a wave reduction. The +// quantiser after it is quant_act_fp8's, byte for byte. +// +// PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row yields `parts` rotated +// copies, side by side: q is [M, parts * K] and scale [M, parts * K/128]. A (part, group) pair is +// one unit of work, one wave's (a row is several blocks, grid.y). The tables stack the parts +// as the "givens" encoding does -- stages rows each of pairs and angle, one row of channel scales. +// +// THE CHANNEL SCALE IS A DIVIDE, because the encoding's t.scale is the factor the stored row was +// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the +// reference (libref) divides in f32 too, so the two agree on this step exactly. +// +// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or +// two, which is also what libref's libm is. The rotation is a handful of FMAs on top of that; the +// quantiser's rounding to E4M3 then swallows nearly all of the difference, and rad-kbench-style +// comparisons against the reference allow one code of disagreement per element. +// +// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. + +#include "r4d.h" +#include "r4d_emit.h" +#include "r4d_fp8_args.h" +#include "r4d_fp8_wmma.h" + +namespace { + +constexpr uint32_t kWave = 32; +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr uint32_t kGroup = 128; +constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2 + +// kPre stages' tables are loaded and their angles' sine and cosine taken BEFORE the first of them is +// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS +// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency +// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages. +constexpr uint32_t kPre = 8; + +__device__ __forceinline__ void wave_sync() { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); + __builtin_amdgcn_wave_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); +} + +// One wave rotates and quantises one (part, group) of one row: grid.x is the row, and grid.y +// spreads a row's `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is +// several blocks and a decode step of a few rows still fills the part. A wave that has no group +// returns at once; nothing in the kernel is a block barrier. +__global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( + const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs, + const float* __restrict__ angle, const float* __restrict__ rscale, uint8_t* __restrict__ q, + float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages, + uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) { + __shared__ float sbuf[kWaves][kGroup]; + const uint32_t row = blockIdx.x; + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + const uint32_t item = blockIdx.y * kWaves + wave; + if (item >= parts * nkb) return; + const uint32_t part = item / nkb, g = item % nkb; + const uint32_t c0 = g * kGroup; + const size_t xrow = (size_t)row * x_ld; + float* buf = sbuf[wave]; + + // channel scale: v = x / D, four consecutive columns a lane + { + const float4 d = *(const float4*)(rscale + (size_t)part * K + c0 + lane * 4u); + const uint32_t xc = c0 + lane * 4u; + const float v0 = __uint_as_float((uint32_t)x[xrow + xc + 0] << 16) / d.x; + const float v1 = __uint_as_float((uint32_t)x[xrow + xc + 1] << 16) / d.y; + const float v2 = __uint_as_float((uint32_t)x[xrow + xc + 2] << 16) / d.z; + const float v3 = __uint_as_float((uint32_t)x[xrow + xc + 3] << 16) / d.w; + *(float4*)(buf + lane * 4u) = make_float4(v0, v1, v2, v3); + } + + for (uint32_t st0 = 0; st0 < stages; st0 += kPre) { + const uint32_t nst = (stages - st0) < kPre ? (stages - st0) : kPre; + int2 ab[kPre][kPairsPerLane]; + float th[kPre][kPairsPerLane], cs[kPre][kPairsPerLane], sn[kPre][kPairsPerLane]; +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) { + const size_t trow = (size_t)part * stages + st0 + k; + const int32_t* pr = pairs + trow * K + c0; + const float* an = angle + trow * (K / 2u) + g * (kGroup / 2u); +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) { + const uint32_t j = lane + u * kWave; + ab[k][u] = *(const int2*)(pr + 2u * j); + th[k][u] = an[j]; + } + } +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) sincosf(th[k][u], &sn[k][u], &cs[k][u]); + wave_sync(); // the scaled row (or the previous chunk's last stage) is in LDS +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) { +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) { + const int ia = ab[k][u].x - (int)c0, ib = ab[k][u].y - (int)c0; + const float va = buf[ia], vb = buf[ib]; + buf[ia] = fmaf(cs[k][u], va, sn[k][u] * vb); + buf[ib] = fmaf(cs[k][u], vb, -sn[k][u] * va); + } + wave_sync(); + } + } + + const float4 r = *(const float4*)(buf + lane * 4u); + float v[4] = { r.x, r.y, r.z, r.w }; + float m = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); + m = r4d_wave_max(m); + const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f; + if (lane == 0) s[(size_t)row * s_ld + (size_t)part * nkb + g] = sc; + const float inv = 1.0f / sc; + int pk = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f), + fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f), + fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true); + *(uint32_t*)(q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = (uint32_t)pk; +} + +} // namespace + +// x [M][K] bf16, `x_ld` elements a row (0 = K) +// pairs [parts*stages][K] int32 column indices; (pairs[2j], pairs[2j+1]) is pair j +// angle [parts*stages][K/2] f32 +// rscale [parts][K] f32, the factor the stored row was multiplied by +// q [M][parts*K] E4M3 +// s [M][parts*K/128] f32 +static int givens_quant_launch(long x, long pairs, long angle, long rscale, long q, long s, int M, + int K, int parts, int stages, int x_ld, int q_ld, int s_ld, + const R4dSink& sk) { + if (!x || !pairs || !angle || !rscale || !q || !s) return -1; + if (M <= 0 || K <= 0 || parts <= 0 || stages <= 0) return -2; + if (K % (int)kGroup) return -3; // a rotation group cannot straddle the end of a row + if (!x_ld) x_ld = K; + const int nkb = K / (int)kGroup; + if (!q_ld) q_ld = parts * K; + if (!s_ld) s_ld = parts * nkb; + const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves; + const int rc = R4D_EMIT(sk, givens_quant_act_fp8_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, + (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, + (const float*)rscale, (uint8_t*)q, (float*)s, (uint32_t)K, + (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, (uint32_t)x_ld, + (uint32_t)q_ld, (uint32_t)s_ld); + if (rc != RAD_OK) return -4; + return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0; +} + +extern "C" int r4d_givens_quant_act_fp8_group(void) { return (int)kGroup; } + +// ============================================================== the plugin ABI entry point +enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Q = 4, GV_S = 5 }; + +static int rad_givens_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { + const RadTensor* x = r4d_opt(a, GV_X); + const RadTensor* pr = r4d_opt(a, GV_PAIRS); + const RadTensor* an = r4d_opt(a, GV_ANGLE); + const RadTensor* rs = r4d_opt(a, GV_RSCALE); + const RadTensor* q = r4d_opt(a, GV_Q); + const RadTensor* sc = r4d_opt(a, GV_S); + if (!x || !pr || !an || !rs || !q || !sc) return R4D_NO(RAD_E_INVAL); + if (x->rank < 2 || q->rank != 2 || sc->rank != 2 || pr->rank != 2 || an->rank != 2 || + rs->rank != 2) return R4D_NO(RAD_E_SHAPE); + if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32) + return R4D_NO(RAD_E_DTYPE); + // rows are dim 0 and everything after it is the row, as quant_act_fp8 reads them + const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); + const long long grp = (long long)kGroup, nkb = K / grp; + const long long parts = r4d_geti_or(a, "parts", 1), stages = r4d_geti_or(a, "stages", 0); + if (r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1) + return R4D_NO(RAD_E_SHAPE); + if (q->shape[0] != M || q->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE); + if (sc->shape[0] != M || sc->shape[1] != parts * nkb) return R4D_NO(RAD_E_SHAPE); + // the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles + if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE); + if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE); + if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); + if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(q->data, 4)) + return R4D_NO(RAD_E_ALIGN); + const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); + if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); + const int e = givens_quant_launch(r4d_addr(x), r4d_addr(pr), r4d_addr(an), r4d_addr(rs), + r4d_addr(q), r4d_addr(sc), (int)M, (int)K, (int)parts, + (int)stages, (int)xp, (int)qp, (int)sp, sk); + return e == 0 ? RAD_OK : RAD_E_SHAPE; +} +R4D_ENTRY(r4d_rad_givens_quant_act_fp8, rad_givens_quant_act_fp8_body) diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 700a4ce9..8aef605f 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -615,6 +615,29 @@ extern "C" int r4d_rad_unrelayout_w2a8(const RadParam* p, int n_p, int operand, * exponents to [K/32][N], and b_ref is each row's largest exponent -- a reduction over the plane, * which is a derivation any reader of the plane could make and so not a choice. */ namespace { +/* A ROTATED MXFP4 WEIGHT (ParoQuant): the same two planes -- e2m1 codes, an E8M0 exponent a 32 -- + * stored in the basis the "givens" transform names, with the rotation's tables beside them. The + * GEMM reads the codes and exponents exactly as it reads an unrotated weight; the rotation is the + * activation's (givens_quant_act_fp8), and the tables are separate weight operands of that op, so + * nothing here touches them. What is checked is that they are there and are the kind of + * rotation the quantiser applies: a transform this library does not read would hand the kernel + * codes that decode to other numbers. */ +bool mx_paro_enc(const RadEncoding* e, long long K) { + if (!e || !rad_enc_is(e, "affine") || std::strncmp(e->transform, "givens", RAD_ENC_STR) != 0) return false; + if (e->n_planes < 5 || !rad_enc_valid(e)) return false; + if (std::strncmp(e->plane[0].role, "codes", RAD_ENC_STR) != 0 || e->plane[0].dtype != RAD_FP4E2M1 || + e->plane[0].block[0] != 1 || e->plane[0].block[1] != 1) return false; + const int s = rad_enc_find(e, "scale"); + if (s != 1 || e->plane[s].dtype != RAD_E8M0 || e->plane[s].kind != RAD_PLANE_TILED || + e->plane[s].block[0] != 1 || e->plane[s].block[1] != R4D_MXFP4_GROUP) return false; + const int p = rad_enc_find(e, "t.pairs"), an = rad_enc_find(e, "t.angle"), sc = rad_enc_find(e, "t.scale"); + if (p < 0 || an < 0 || sc < 0) return false; + if (e->plane[p].dtype != RAD_I32 || e->plane[an].dtype != RAD_F32 || e->plane[sc].dtype != RAD_F32) + return false; + // the quantiser rotates whole groups of 128 columns, one scale per group + return K % 128 == 0 && e->plane[p].extent[1] == K; +} + int mx_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; @@ -622,7 +645,8 @@ int mx_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en int rc = wgeom(p, n_p, R4D_MXFP4_GROUP, &g); if (rc != RAD_OK) return rc; if (g.group != R4D_MXFP4_GROUP || g.K % 16) return RAD_E_SHAPE; - if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, R4D_MXFP4_GROUP)) return RAD_E_DTYPE; + if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, R4D_MXFP4_GROUP) && + !mx_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) { diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 2d227f5a..cca59c78 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -319,6 +319,8 @@ int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_had_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +int r4d_rad_givens_quant_act_fp8 (const RadArgs*, RadStream); +int r4d_rad_givens_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 4d13d05a..16f0636b 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -704,12 +704,18 @@ static const RadOperandSpec oGemmNt[] = { { "y", RAD_OPD_OUT, 0 }, }; +/* `pb1` and `pb2` are ParoQuant's, and the mxfp4a8 rows alone read them: the weight's rows + * [0, pb1), [pb1, pb2) and [pb2, N) each meet their own copy of the activation, side by side in a + * row of `a` (so `a` is [M, parts * K]). 0 leaves a bound out. Optional, and absent from every + * other grid: a fused projection whose pieces were not rotated apart has one activation. */ static const RadParamSpec pGemmNtQ[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "N", RAD_P_INT, RAD_REQUIRED }, { "K", RAD_P_INT, RAD_REQUIRED }, { "group", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "pb1", RAD_P_INT, RAD_OPTIONAL }, + { "pb2", RAD_P_INT, RAD_OPTIONAL }, }; /* docs/OPS.md's `gemm_nt_q` is `a`, `a_scale`, `b`w, `b_scale`w -> `y`. Two of libr4d's six * quantised GEMMs need a seventh operand each and neither is expressible as a weight aux stream, @@ -1045,6 +1051,26 @@ static const RadOperandSpec oQuantActFp8[] = { { "scale", RAD_OPD_OUT, 0 }, }; +/* `givens_quant_act_fp8` is ParoQuant's activation side, and libref declared this schema first + * (the loader refuses two that differ). The tables are the "givens" encoding's, as WEIGHT operands; + * see libref/ref_quant.cpp for the contract and r4d_givens_quant_act_fp8.hip for the kernel. */ +static const RadParamSpec pGivensQuantAct[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + { "group", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "stages", RAD_P_INT, RAD_REQUIRED }, + { "parts", RAD_P_INT, RAD_REQUIRED }, +}; +static const RadOperandSpec oGivensQuantAct[] = { + { "x", RAD_OPD_IN, 0 }, + { "pairs", RAD_OPD_WEIGHT, 0 }, + { "angle", RAD_OPD_WEIGHT, 0 }, + { "rscale", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, +}; + /* `gram_accum` is a NEW OP and this plugin fixes its schema. It is the calibration half of GPTQ: * `h += x^T x` over an E4M3 activation, accumulated across every launch of a corpus. * @@ -2298,6 +2324,16 @@ static const RadOpSchema kSchemas[] = { SCHEMA("had_quant_act_i8g", pQuantActFp8, oQuantActFp8, "quant_act_i8g with a `group`-wide Hadamard along K first; pairs with an i8 weight stored " "rotated, its scale carrying the residual factor of `group`."), + SCHEMA("givens_quant_act_fp8", pGivensQuantAct, oGivensQuantAct, + "ParoQuant's activation quantiser: x is divided by the channel scale `rscale`, rotated by " + "`stages` rounds of disjoint Givens pairs (a' = a cos t + b sin t, b' = b cos t - a sin t, " + "pairs as column indices of the row, each inside one scale group), then quantised as " + "quant_act_fp8 does: scale = amax / 448 per `group`. `parts` rotated copies are written " + "side by side -- q is [M, parts * n], scale [M, parts * n / group] -- part p from table " + "rows [p * stages, (p + 1) * stages) of `pairs` and `angle` and row p of `rscale`: a " + "fused projection's pieces were each rotated on their own. Only a weight stored with " + "the \"givens\" transform reads the result; it is NOT quant_act_fp8's output in either " + "direction."), SCHEMA("had_quant_act_fp8", pQuantActFp8, oQuantActFp8, "the same, with a `group`-wide Hadamard along K applied BEFORE the absmax. Pairs with " "an expert weight stored at dtype w4a8h, which carries the matching rotation and the " @@ -5115,6 +5151,22 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_had_quant_act_fp8, nullptr, nullptr, nullptr, r4d_shape_quant_act_fp8, nullptr, nullptr, r4d_rad_had_quant_act_fp8_describe }, +/* ParoQuant's rotation and the quantiser in one pass, because the rotation changes the maximum the + * scale is taken over and so cannot be a separate launch ahead of quant_act_fp8 without writing + * and re-reading the rotated row. It exists for the MXFP4 weight stored rotated and for nothing + * else. */ +{ "givens_quant_act_fp8", "givens_quant_act_fp8", "quant", + "the channel scale, ParoQuant's Givens rotations, then per-(row, 128-column) symmetric E4M3 " + "quantisation, once for each rotated part of a fused projection", + "n a multiple of 128 -- a rotation group cannot straddle the end of a row -- and group 128, " + "which is both the rotation group and the weight scale's activation block", + "bf16 in, E4M3 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale per (row, part, " + "128 columns); the tables are the weight's int32 pairs, f32 angles and f32 channel scales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cHadQuantActFp8), NOTUNE, + nullptr, nullptr, r4d_rad_givens_quant_act_fp8, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, r4d_rad_givens_quant_act_fp8_describe }, + { "quant_act_i8g", "quant_act_i8g", "quant", "per-(row, 128-column) symmetric int8 quantisation of a bf16 activation", "quant_act_fp8's: n a multiple of 4, group 128, a ragged last group written zero-padded", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 2cf5af7c..64db78cf 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3604,11 +3604,19 @@ static float mxfp4_act(int64_t i, int64_t k, uint32_t seed) { * spread over two decades and every eleventh block's is ZERO with zero codes behind it (an * all-zero activation block), which is the case the kernels carry their previous scale through. */ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K, - int tn, bool ablk = false, std::vector extra = {}) { + int tn, bool ablk = false, std::vector extra = {}, + int64_t pb1 = 0, int64_t pb2 = 0) { if (!sel(row)) return; + /* PARTS (ParoQuant): the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy + * of the activation, the copies side by side in a row. `K` is one copy's width. */ + const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; + const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; 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); @@ -3633,20 +3641,21 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ } const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1; - std::vector ha((size_t)(M * K)); - std::vector 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 ha((size_t)(M * PK)); + std::vector 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 hy((size_t)(M * N), 0); @@ -3663,8 +3672,8 @@ static void mxfp4a8_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 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() }), }; @@ -3672,6 +3681,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") }; 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)); @@ -3702,11 +3713,12 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ 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)) { double acc = 0; + const int pt = part_of(n); for (int64_t k = 0; k < K; ++k) { const double w = (double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) * (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; @@ -3721,6 +3733,111 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ } +/* PAROQUANT'S ACTIVATION QUANTISER AGAINST A DOUBLE-PRECISION ROTATION. The tables are real + * pairings -- every stage of every group is a random permutation of the group's 128 columns read + * as 64 pairs -- with angles over (-pi, pi) and channel scales over (0.5, 2), drawn through + * st_mix32 of their coordinates. The reference divides, rotates in f64 and takes the absmax; the + * kernel's scale must match it to the rounding of its f32 sincos, and every dequantised element + * must sit within the E4M3 grid of the reference (half a step at the top of the range is 1/16 of + * the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */ +static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages) { + const char* row = "givens_quant_act_fp8"; + if (!sel(row)) return; + char nm[160]; + std::snprintf(nm, sizeof nm, "%s numeric M=%lld K=%lld parts=%d stages=%d", row, (long long)M, + (long long)K, parts, stages); + const RadKernelInfo* r = find(pl, row); + if (!r || !r->launch) { ok(nm, false, "row absent"); return; } + const int64_t G = 128, ng = K / G; + std::vector hx((size_t)(M * K)); + std::vector xv((size_t)(M * K)); + for (int64_t i = 0; i < M; ++i) + for (int64_t k = 0; k < K; ++k) { + const uint32_t h = st_mix32((uint32_t)(i * 0x10001 + k) ^ 0x77u); + const float v = (float)((int)(h % 4001) - 2000) * 0.002f * (i % 4 == 3 ? 40.0f : 1.0f); + hx[(size_t)(i * K + k)] = h_to_bf16(v); + xv[(size_t)(i * K + k)] = h_bf16(hx[(size_t)(i * K + k)]); + } + const int64_t NPS = (int64_t)parts * stages; + std::vector pairs((size_t)(NPS * K)); + std::vector ang((size_t)(NPS * K / 2)), rs((size_t)(parts * K)); + for (int64_t ps = 0; ps < NPS; ++ps) { + for (int64_t g = 0; g < ng; ++g) { + std::vector perm((size_t)G); + for (int i = 0; i < G; ++i) perm[(size_t)i] = i; + for (int i = (int)G - 1; i > 0; --i) + std::swap(perm[(size_t)i], + perm[st_mix32((uint32_t)(ps * 7919 + g * 104729 + i)) % (uint32_t)(i + 1)]); + for (int i = 0; i < G; ++i) pairs[(size_t)(ps * K + g * G + i)] = (int32_t)(g * G + perm[(size_t)i]); + } + for (int64_t j = 0; j < K / 2; ++j) + ang[(size_t)(ps * K / 2 + j)] = + (float)(st_mix32((uint32_t)(ps * 31337 + j) ^ 0x5bu) % 6283) / 1000.0f - 3.1415f; + } + for (int64_t i = 0; i < parts * K; ++i) + rs[(size_t)i] = 0.5f + (float)(st_mix32((uint32_t)i ^ 0xc3u) % 1500) / 1000.0f; + + void* d_x = dalloc(hx.size() * 2); + void* d_p = dalloc(pairs.size() * 4); + void* d_a = dalloc(ang.size() * 4); + void* d_r = dalloc(rs.size() * 4); + void* d_q = dalloc((size_t)(M * parts * K)); + void* d_s = dalloc((size_t)(M * parts * ng) * 4); + if (!d_x || !d_p || !d_a || !d_r || !d_q || !d_s) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_p, pairs.data(), pairs.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_a, ang.data(), ang.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_r, rs.data(), rs.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { + T(d_x, RAD_BF16, { M, K }), T(d_p, RAD_I32, { NPS, K }), T(d_a, RAD_F32, { NPS, K / 2 }), + T(d_r, RAD_F32, { (int64_t)parts, K }), T(d_q, RAD_F8E4M3, { M, parts * K }), + T(d_s, RAD_F32, { M, parts * ng }), + }; + std::vector ps = { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"), + PI("stages", stages), PI("parts", parts) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + const int rc = r->launch(&a, (RadStream) nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { ok(nm, false, "rc=" + std::to_string(rc)); return; } + std::vector hq((size_t)(M * parts * K)); + std::vector hs((size_t)(M * parts * ng)); + st_memcpy(hq.data(), d_q, hq.size(), hipMemcpyDeviceToHost); + st_memcpy(hs.data(), d_s, hs.size() * 4, hipMemcpyDeviceToHost); + + double worst_scale = 0, worst_val = 0; + std::vector b((size_t)K); + for (int64_t i = 0; i < M; ++i) + for (int p = 0; p < parts; ++p) { + for (int64_t k = 0; k < K; ++k) b[(size_t)k] = (double)xv[(size_t)(i * K + k)] / (double)rs[(size_t)(p * K + k)]; + for (int st = 0; st < stages; ++st) + for (int64_t j = 0; j < K / 2; ++j) { + const int64_t ia = pairs[(size_t)((p * stages + st) * K + 2 * j)]; + const int64_t ib = pairs[(size_t)((p * stages + st) * K + 2 * j + 1)]; + const double t = ang[(size_t)((p * stages + st) * (K / 2) + j)], c = std::cos(t), sn = std::sin(t); + const double va = b[(size_t)ia], vb = b[(size_t)ib]; + b[(size_t)ia] = va * c + vb * sn; + b[(size_t)ib] = vb * c - va * sn; + } + for (int64_t g = 0; g < ng; ++g) { + double amax = 0; + for (int k = 0; k < G; ++k) amax = std::max(amax, std::fabs(b[(size_t)(g * G + k)])); + const double sc = hs[(size_t)(i * parts * ng + p * ng + g)]; + worst_scale = std::max(worst_scale, std::fabs(sc - amax / 448.0) / (amax / 448.0 + 1e-30)); + for (int k = 0; k < G; ++k) { + const double deq = (double)rad_load_f32(hq.data(), RAD_F8E4M3, i * parts * K + p * K + g * G + k) * sc; + worst_val = std::max(worst_val, std::fabs(deq - b[(size_t)(g * G + k)]) / (amax + 1e-30)); + } + } + } + char d[96]; + std::snprintf(d, sizeof d, "scale rel %.2e, value/amax %.3f", worst_scale, worst_val); + ok(nm, worst_scale < 1e-4 && worst_val < 0.07, d); +} + + /* TWO DECODE GEMMS THE ENGINE MAY OVERLAP (gemm_mxfp4a8_decode is a concurrent row: its split partial * is the op's scratch and its arrival counters are keyed on the output). Each GEMM has its own * weights, activations and output and a DISJOINT slice of one scratch allocation, with a split @@ -12233,6 +12350,17 @@ static void device_phase(const Plugin& pl) { mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 64, 512, 2560, 0, true); mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 5, 1040, 576, 0, true); mxd_overlap_case(pl); + /* PARTS (ParoQuant): each part of the weight against its own copy of the activation, with + * bounds that do not fall on a tile of any kernel's, two parts and three, at every band. */ + mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 400, 640, 0, true, {}, 144); + mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 400, 640, 0, true, {}, 144, 288); + mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 400, 2560, 0, true, {}, 128); + mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 40, 512, 2560, 0, true, {}, 128, 384); + mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 4, 34816, 5120, 0, true, {}, 17408); + mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 2, true, {}, 192); + mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4, true, {}, 96, 304); + mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0, true, {}, 256); + mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 34816, 5120, 0, true, {}, 17408); /* Above 64 rows, every branch of the measured table: 110+ column blocks, 48+, 8 or * fewer (with a K that is not a multiple of 128, so the slab falls back to 64), a deep K * on both sides of M=80, and the plain case; then every split and slab forced. */ @@ -12649,6 +12777,16 @@ static void device_phase(const Plugin& pl) { moe_w4_rot(pl); } + if (sel("givens_quant_act_fp8")) { + if (!g_case) std::printf("\nParoQuant's rotate-and-quantise, against an f64 rotation\n"); + givens_numeric(pl, 1, 128, 1, 8); + givens_numeric(pl, 3, 5120, 1, 8); + givens_numeric(pl, 5, 5120, 2, 8); + givens_numeric(pl, 64, 17408, 1, 8); + givens_numeric(pl, 300, 6144, 2, 8); + givens_numeric(pl, 7, 5120, 3, 2); + } + if (sel("gram_accum")) { if (!g_case) std::printf("\nthe GPTQ calibration accumulator, against an f64 host Gram\n"); gram_accum_case(pl); From 5681da471c956c4cf5e7140cd9a4770e2967e146 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Wed, 7 Oct 2026 23:52:17 +0000 Subject: [PATCH 04/17] qwen35_fp8: serve rotated MXFP4 linears (LinearFP8 rotates its input first); paro recipe A rotated weight reads the producer's bf16 plane, rotates and quantises it into its own planes (parts side by side) and runs the ordinary mxfp4a8 GEMM. Adds data/recipes/q38-27b-paro-mxfp4-df2.recipe and the GUIDE entry. --- arch/common/rad_block_gdn_fp8.h | 4 +- arch/common/rad_fp8.h | 137 ++++++++++++++++++++- data/recipes/q38-27b-paro-mxfp4-df2.recipe | 38 ++++++ docs/GUIDE.md | 9 +- 4 files changed, 180 insertions(+), 8 deletions(-) create mode 100644 data/recipes/q38-27b-paro-mxfp4-df2.recipe diff --git a/arch/common/rad_block_gdn_fp8.h b/arch/common/rad_block_gdn_fp8.h index 67b12a6c..a410d813 100644 --- a/arch/common/rad_block_gdn_fp8.h +++ b/arch/common/rad_block_gdn_fp8.h @@ -275,7 +275,9 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con * all of q, all of k and a third of v, a well-formed wrong model. */ RAD_ARCH_TRY(in.declare(b, nm, g, nm.f("blk.%d.ssm_inz", l), conv_dim + v_dim, g.n_embd, RAD_SHARD_ROW, grp_layer(l), { s.in_qkv, s.in_z }, w.h, w.in.x, 0, - { cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() })); + { cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }, 0, 0, + /* a rotated weight was rotated per CHECKPOINT tensor: q|k|v, then z */ + { 2 * cfg.k_dim() + cfg.v_dim(), cfg.v_dim() })); if (cfg.uneven()) { /* THIS RANK'S HEADS OF EACH PART, in the container's rows: q and k by K head, v and z by * V head. The scale plane of a row shard has the same rows (its blocks run along K). */ diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index e0212f47..7415fbae 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -58,6 +58,7 @@ #include #include +#include namespace rad { namespace arch { @@ -690,6 +691,17 @@ struct LinearFP8 { * feeds an MXFP4 linear unchanged. Read off the weight's encoding like `bf16` and `i8`. */ bool mx = false; rad_weight wref = 0; + /* ...ROTATED (ParoQuant), a variant of `mx`: the same GEMM over an activation that + * `givens_quant_act_fp8` made from the input's bf16 plane -- the channel scale, the Givens + * stages and the E4M3 quantiser in one pass, once for each rotated PART of a fused projection + * (gate|up, qkv|z: each piece was rotated on its own) -- into this linear's own code and + * scale planes, `parts` copies side by side. The tables are views of the weight's own planes. + * The GEMM takes the parts' row bounds as `pb1`/`pb2` and meets copy p with part p's rows. */ + bool paro = false, probed_paro = false; + rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0; + rad_buf rot_q = 0, rot_s = 0; + rad_op op_rot = 0; + int64_t rot_parts = 1; /* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear * before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */ bool probed_i8 = false; @@ -728,12 +740,16 @@ struct LinearFP8 { /* `span_lo`/`span_hi`, when hi is set, is this rank's uneven slice of the split dimension in * the model's units -- rows of each row part for RAD_SHARD_ROW, columns for RAD_SHARD_COL -- * and n_out / n_in is already its width; see rad_weight_shard_span. Whole scale blocks. */ + /* `rot_parts`: the rows of each independently rotated part of a ROTATED weight (probed_paro), + * which `row_parts` is when the pieces and the shard parts are the same cut -- gate|up -- and + * is not when they are not: the delta net's qkv|z is four shard parts and two rotated ones. */ int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, std::initializer_list src, const ActFP8& a, rad_buf y, int64_t max_rows = 0, std::initializer_list row_parts = {}, - int64_t span_lo = 0, int64_t span_hi = 0); + int64_t span_lo = 0, int64_t span_hi = 0, + std::initializer_list rot_part_rows = {}); void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; /* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale @@ -797,6 +813,21 @@ inline bool linear_is_mxfp4(const RadEncoding& e) { sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP; } +/* The ROTATED OCP-MXFP4 weight (ParoQuant): the same codes and E8M0 exponents, stored in the basis + * a "givens" transform names, with the rotation's tables as planes of their own (int32 column + * pairs, f32 angles, f32 channel scales, and for a fused projection one set a part). The GEMM + * reads it as the plain MXFP4 weight; the activation in front of it is rotated first. */ +inline bool linear_is_paro_mxfp4(const RadEncoding& e) { + if (!rad_enc_is(&e, "affine") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false; + if (!rad_enc_valid(&e) || e.n_planes < 5) return false; + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + const RadEncPlane *pr = rad_enc_plane(&e, "t.pairs"), *an = rad_enc_plane(&e, "t.angle"), + *rs = rad_enc_plane(&e, "t.scale"); + return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc && + sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP && + pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32; +} + inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base, std::initializer_list src) { if (src.size() == 0) return RAD_E_INVAL; @@ -808,7 +839,9 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16; probed_i8 = known && linear_is_w8(enc); - reads_x = g.w_bf16 || plain || probed_i8; + /* A ROTATED weight rotates the bf16 plane itself: its quantiser is not the producer's. */ + probed_paro = known && linear_is_paro_mxfp4(enc); + reads_x = g.w_bf16 || plain || probed_i8 || probed_paro; return RAD_OK; } @@ -817,7 +850,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha std::initializer_list src, const ActFP8& a, rad_buf y, int64_t max_rows, std::initializer_list row_parts, - int64_t span_lo, int64_t span_hi) { + int64_t span_lo, int64_t span_hi, + std::initializer_list rot_part_rows) { N = n_out; K = n_in; if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; @@ -941,9 +975,24 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * the exponent plane as `b_scale`, and the same plane again as `b_ref`. Every view takes the * weight's row parts as they are -- the exponent grid is one row tall -- and a column slice in * whole 128s, which is the ACTIVATION's scale block and so the stricter of the two. */ - mx = known && linear_is_mxfp4(enc); + paro = known && linear_is_paro_mxfp4(enc); + mx = known && (linear_is_mxfp4(enc) || paro); if (mx) { - if (!a.q || !a.s) { + if (paro) { + /* THE ROTATION OF A ROTATED WEIGHT IS THE ACTIVATION'S, so this linear needs the input's + * bf16 plane (probe() set reads_x; the producer wrote it) and quantises it itself. */ + if (!a.x) { + fprintf(stderr, "radiance: '%s' is a rotated MXFP4 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 MXFP4 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 MXFP4 weight read against its input's E4M3 " "pair, and its input has none\n", wn); return RAD_E_DTYPE; @@ -966,6 +1015,58 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha } parts[np++] = p; } + int64_t pb1 = 0, pb2 = 0; + if (paro) { + /* THE PARTS, in rows, and the tables as weights of their own. The container records + * how many parts there are and not where they end -- a declaration has no plane bytes + * -- so the block says: `rot_part_rows`, or its row parts when those are the cut. */ + const int64_t P = rad_enc_givens_parts(&enc); + const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs"); + if (P < 1 || !tp || tp->extent[0] % P || tp->extent[1] != K) { + fprintf(stderr, "radiance: '%s' has rotation tables that do not fit %lld columns\n", + wn, (long long)K); + return RAD_E_SHAPE; + } + const int64_t S = tp->extent[0] / P; + std::vector 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); + if (cut.empty() && P == 1) cut.push_back(N); + int64_t sum = 0; + for (int64_t p : cut) sum += p; + if ((int64_t)cut.size() != P || sum != N || P > 3) { + fprintf(stderr, "radiance: '%s' was rotated as %lld part(s) and is declared as %zu " + "rotated part(s) of %lld rows; the GEMM meets up to three copies " + "of the activation\n", wn, (long long)P, cut.size(), (long long)sum); + return RAD_E_SHAPE; + } + for (int64_t i = 0; i + 1 < P; ++i) if (cut[(size_t)i] % 128) { + fprintf(stderr, "radiance: '%s' rotation part of %lld rows is not whole 128s\n", + wn, (long long)cut[(size_t)i]); + return RAD_E_SHAPE; + } + rot_parts = P; + pb1 = P > 1 ? cut[0] : 0; + pb2 = P > 2 ? cut[0] + cut[1] : 0; + rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, + { P * S, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + rot_angle = decl_view(b, nm.f("%s.rot_angle", base), wn, "t.angle", RAD_F32, + { P * S, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + rot_scale = decl_view(b, nm.f("%s.rot_scale", base), wn, "t.scale", RAD_F32, + { P, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + if (!rot_pairs || !rot_angle || !rot_scale) return RAD_E_INVAL; + 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, P * K }); + rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, P * (K / RAD_FP8_BLOCK) }); + if (!rot_q || !rot_s) return RAD_E_INVAL; + op_rot = rw(b, RAD_OP(b, "givens_quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), + RAD_INT("stages", S), RAD_INT("parts", P)), + RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), + { a.x }, { 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", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN, @@ -990,6 +1091,21 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi)); } const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; + if (paro) { + op = rot_parts > 1 + ? rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), + RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), + RAD_WEIGHTS(w, ws, wref)), + { rot_q, rot_s }, { y }) + : rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")), + RAD_WEIGHTS(w, ws, wref)), + { rot_q, rot_s }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } op = rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")), @@ -1096,6 +1212,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, r0, rows, N), RAD_NONE, RAD_NONE); return; } + if (paro) { + /* The rotation first: this linear's own codes, `rot_parts` copies side by side. */ + RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), + RAD_W(rot_angle), RAD_W(rot_scale), + brow_slice(rot_q, r0, rows, rot_parts * K), + brow_slice(rot_s, r0, rows, rot_parts * (K / RAD_FP8_BLOCK))); + RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), + brow_slice(rot_s, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)), + RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref)); + return; + } if (mx) { RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K), brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK), diff --git a/data/recipes/q38-27b-paro-mxfp4-df2.recipe b/data/recipes/q38-27b-paro-mxfp4-df2.recipe new file mode 100644 index 00000000..2059d764 --- /dev/null +++ b/data/recipes/q38-27b-paro-mxfp4-df2.recipe @@ -0,0 +1,38 @@ +# q38-27b-paro-mxfp4-df2.recipe -- a ParoQuant MXFP4 Qwen3.8-27B (quant_method paroquant_mxfp4) with the +# DFlash2 drafter. +# +# rad-convert --draft-model \ +# --recipe q38-27b-paro-mxfp4-df2.recipe -o q38-27b-paro-mxfp4-df2.rad +# +# The trunk's linears are imported as they ship, and need no rule: e2m1 codes and an E8M0 exponent a +# 32 of K -- Quark's planes byte for byte -- stored in the ROTATED basis ParoQuant trained them in, +# with the rotations beside them as the encoding's "givens" transform (abi/rad_encoding.h): per +# projection the Givens pairs and angles of 8 stages inside groups of 128 columns, and the channel +# scales. A fused gate|up or qkv|z keeps one set of tables a checkpoint tensor (parts). rad-convert +# writes them as planes of the weight; the GEMM is the plain MXFP4 one, and the activation is +# rotated in front of it (givens_quant_act_fp8) -- nothing is re-quantised, so the weights are the +# release's to the bit. +# +# What the checkpoint does NOT ship in a form the architecture declares gets a rule. The release is +# fp16 throughout (norms, the delta net's a|b and conv, the vision tower), where the plugin declares +# bf16: `cast` rounds f16 to bf16 once. Its embedding and head are fp8 with one f32 scale a ROW, +# read exactly and re-expressed: the embedding as bf16, the head as block fp8 like every other +# recipe here. Its MTP head is not read: the DFlash2 drafter displaces it. +# +# THE DRAFTER is made as small as its acceptance allows, as in q38-27b-quark-mxfp4-df2.recipe. + +blk.*.ssm_ab.weight cast dtype=bf16 +blk.*.ssm_conv1d.weight cast dtype=bf16 +token_embd.weight cast dtype=bf16 +v.* cast dtype=bf16 + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search + +dflash.fc.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 diff --git a/docs/GUIDE.md b/docs/GUIDE.md index f7e7a529..414d3e98 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -344,12 +344,13 @@ that points each name at its copy. A name two shards hold that no index entry se The conversions of record live in `scripts/convfn.sh` and `scripts/convdspark.sh`, with their recipes in `data/recipes/`. -**A release someone else already quantised is read as it ships.** Two forms are imported weight +**A release someone else already quantised is read as it ships.** Three forms are imported weight by weight, so their quantised linears need no recipe rule: | `quantization_config` | read as | | |---|---|---| | `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) | +| `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_quant_act_fp8` and the ordinary MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule | | `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped | The width is read per tensor, so a release mixing int4 experts with int8 projections imports both. @@ -359,13 +360,17 @@ form, so it is kept in the container as `imported_quantization_config.*`, and th its family's quantised plugin (`qwen35_fp8` for Qwen3.8-27B; `qwen4exp_fp8` for Flash-Next). A weight the architecture declares in another form than the release holds still takes a rule: the -recipe dequantises the import exactly and quantises from that. The two recipes of record: +recipe dequantises the import exactly and quantises from that. The recipes of record: ```sh # AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter rad-convert ~/models/amd/Qwen3.8-27B-Quark-AWQ-MXFP4 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \ --recipe data/recipes/q38-27b-quark-mxfp4-df2.recipe -o q38-27b-quark-mxfp4-df2.rad +# A ParoQuant MXFP4 Qwen3.8-27B (rotated MXFP4 trunk imported with its rotations; fp16 parts cast to bf16) +rad-convert ~/models/MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \ + --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe -o q38-27b-paro-mxfp4-df2.rad + # An AutoRound int4 Qwen3.8-Flash-Next: its experts imported, its int4 projections made int8 rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \ --recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe -o swift-autoround.rad From 9af15f3a6e8e8628d497272ade5c407631be9cd1 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 18:14:14 +0200 Subject: [PATCH 05/17] ParoQuant: check the givens pairs at load; one re-tile slab for every part; one bounds helper; one mxfp4 GEMM declaration * libr4d: givens_quant_act_fp8 gets layout/relayout/unrelayout hooks for `pairs` -- stored as is, refused (RAD_E_FORMAT) when a stage is not a pairing of its own group of 128, which the kernel would index out of bounds. relayout_parity_test covers it. * gemm_mxfp4a8_tiled: the parts run in order on one stream, so they share one re-tiled activation; the scratch is one slab again. * mx_part_bounds: the pb1/pb2 clamping in one place (mx_parts, the decode scratch hook). * LinearFP8: one gemm_nt_q declaration and one issue path for the plain and the rotated MXFP4 weight; pb1/pb2 still only on a weight with parts, so a one-part op keeps its tune-cache geometry. --- arch/common/rad_fp8.h | 52 +++++++++-------------- libr4d/r4d_gemm_args.h | 25 +++++++---- libr4d/r4d_gemm_mxfp4a8_decode.hip | 7 +--- libr4d/r4d_gemm_mxfp4a8_tiled.hip | 19 ++++----- libr4d/r4d_givens_quant_act_fp8.hip | 4 +- libr4d/r4d_layout.cpp | 65 +++++++++++++++++++++++++++++ libr4d/r4d_plugin.h | 6 +++ libr4d/r4d_rows.cpp | 8 ++-- tests/relayout_parity_test.cpp | 46 ++++++++++++++++++++ 9 files changed, 169 insertions(+), 63 deletions(-) diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 7415fbae..5f1ef819 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -1090,27 +1090,16 @@ 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)); } + /* ONE GEMM for both: a rotated weight reads its own rotated pair, a plain one the + * producer's. `pb1`/`pb2` (the last two params) go only to a weight with parts, so a one-part + * op keeps the plain op's geometry -- the key the tune cache is read by. */ const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; - if (paro) { - op = rot_parts > 1 - ? rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), - RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), - RAD_WEIGHTS(w, ws, wref)), - { rot_q, rot_s }, { y }) - : rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")), - RAD_WEIGHTS(w, ws, wref)), - { rot_q, rot_s }, { y }); - return op ? RAD_OK : RAD_E_INVAL; - } - op = rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")), - RAD_WEIGHTS(w, ws, wref)), - { a.q, a.s }, { y }); + const RadParam ps[] = { RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), + RAD_INT("pb1", pb1), RAD_INT("pb2", pb2) }; + const int n_ps = (int)(sizeof ps / sizeof ps[0]) - (rot_parts > 1 ? 0 : 2); + op = rw(b, rad_decl_op(b, "gemm_nt_q", ps, n_ps, RAD_WEIGHTS(w, ws, wref)), + { paro ? rot_q : a.q, paro ? rot_s : a.s }, { y }); return op ? RAD_OK : RAD_E_INVAL; } @@ -1212,20 +1201,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, r0, rows, N), RAD_NONE, RAD_NONE); return; } - if (paro) { - /* The rotation first: this linear's own codes, `rot_parts` copies side by side. */ - RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), - RAD_W(rot_angle), RAD_W(rot_scale), - brow_slice(rot_q, r0, rows, rot_parts * K), - brow_slice(rot_s, r0, rows, rot_parts * (K / RAD_FP8_BLOCK))); - RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), - brow_slice(rot_s, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref)); - return; - } if (mx) { - RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K), - brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK), + /* A rotated weight rotates its input first, into its own codes, `rot_parts` copies side + * by side (one for a plain weight, which reads the producer's). */ + const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s; + const int64_t ak = rot_parts * K; + if (paro) + RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), + RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(aq, r0, rows, ak), + brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK)); + RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak), + brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK), RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref)); return; } diff --git a/libr4d/r4d_gemm_args.h b/libr4d/r4d_gemm_args.h index 37aab7a6..2336906e 100644 --- a/libr4d/r4d_gemm_args.h +++ b/libr4d/r4d_gemm_args.h @@ -368,21 +368,30 @@ struct MxParts { long long lda = 0; /* 0: the plane's own K */ }; +/* The bounds `pb1`/`pb2` name over N rows, as every reader takes them: { 0, e1, e2, N }, part i + * being [bound[i], bound[i+1]). Returns how many copies of the activation they imply, 1..3. */ +static inline int mx_part_bounds(long long N, long long pb1, long long pb2, long long bound[4]) { + const long long e1 = pb1 > 0 && pb1 < N ? pb1 : N; + long long e2 = pb2 > 0 && pb2 < N ? pb2 : N; + if (e2 < e1) e2 = e1; + bound[0] = 0; + bound[1] = e1; + bound[2] = e2; + bound[3] = N; + return e2 < N ? 3 : (e1 < N ? 2 : 1); +} + static inline int mx_parts(const RadArgs* a, GemmOps* g, MxParts* p) { - const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0); p->n = 1; p->n0[0] = 0; p->n1[0] = g->N; p->lda = 0; - if (pb1 <= 0 && pb2 <= 0) return RAD_OK; + long long bound[4]; + const int segs = mx_part_bounds(g->N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound); + if (segs == 1) return RAD_OK; const long long K = r4d_geti_or(a, "K", 0); if (K <= 0) return R4D_NO(RAD_E_INVAL); - const long long e1 = pb1 > 0 ? (pb1 < g->N ? pb1 : g->N) : g->N; - long long e2 = pb2 > 0 ? (pb2 < g->N ? pb2 : g->N) : g->N; - if (e2 < e1) e2 = e1; - const long long bound[4] = { 0, e1, e2, g->N }; - const int segs = e2 < g->N ? 3 : (e1 < g->N ? 2 : 1); - if (g->K != (long long)segs * K || (e1 % 16) || (e2 % 16)) return R4D_NO(RAD_E_SHAPE); + if (g->K != (long long)segs * K || (bound[1] % 16) || (bound[2] % 16)) return R4D_NO(RAD_E_SHAPE); p->n = 0; for (int i = 0; i < 3; ++i) if (bound[i + 1] > bound[i]) { diff --git a/libr4d/r4d_gemm_mxfp4a8_decode.hip b/libr4d/r4d_gemm_mxfp4a8_decode.hip index b397b50e..79f263cf 100644 --- a/libr4d/r4d_gemm_mxfp4a8_decode.hip +++ b/libr4d/r4d_gemm_mxfp4a8_decode.hip @@ -621,11 +621,8 @@ extern "C" int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) { if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_mxfp4a8_decode_max_m()) return 0; R4dMxDecCfg t; r4d_cfg_mxfp4_decode(a, &t); - const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0); - const long long e1 = pb1 > 0 ? (pb1 < N ? pb1 : N) : N; - long long e2 = pb2 > 0 ? (pb2 < N ? pb2 : N) : N; - if (e2 < e1) e2 = e1; - const long long bound[4] = { 0, e1, e2, N }; + 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]; diff --git a/libr4d/r4d_gemm_mxfp4a8_tiled.hip b/libr4d/r4d_gemm_mxfp4a8_tiled.hip index 6330e288..e1c32c23 100644 --- a/libr4d/r4d_gemm_mxfp4a8_tiled.hip +++ b/libr4d/r4d_gemm_mxfp4a8_tiled.hip @@ -367,8 +367,8 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l // ============================================================== the plugin ABI entry point // The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there. -// A partitioned weight re-tiles each part's copy of the activation into its own slab of the -// scratch and runs the GEMM over that part's rows (mx_parts). +// A partitioned weight re-tiles each part's copy of the activation into the scratch in turn and +// runs the GEMM over that part's rows (mx_parts). extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) { GemmOps g; int rc = gemm_ops(a, &g, 1); @@ -386,13 +386,13 @@ extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) { rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n); if (rc != RAD_OK) return rc; const long long slab = r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K); - if (!a->scratch || a->scratch_bytes < slab * mp.n) return R4D_NO(RAD_E_INVAL); + 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; for (int p = 0; p < mp.n; ++p) { const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p]; - const long at = (long)(uintptr_t)a->scratch + (long)(p * slab); R4D_TRY("gemm_mxfp4a8_tiled", r4d_mxfp4a8_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)); @@ -405,14 +405,9 @@ extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) { } /* The core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of - * the activation, whole 16-row fragments -- one a part. */ + * the activation, whole 16-row fragments. One copy for every part: the parts run one after another + * on the op's stream, so a part's re-tile cannot overtake the previous part's GEMM. */ extern "C" int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs* a) { const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0); - const long long N = r4d_geti_or(a, "N", 0); - const long long pb1 = r4d_geti_or(a, "pb1", 0), pb2 = r4d_geti_or(a, "pb2", 0); - const long long e1 = pb1 > 0 ? (pb1 < N ? pb1 : N) : N; - long long e2 = pb2 > 0 ? (pb2 < N ? pb2 : N) : N; - if (e2 < e1) e2 = e1; - const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); - return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K) * parts; + return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K); } diff --git a/libr4d/r4d_givens_quant_act_fp8.hip b/libr4d/r4d_givens_quant_act_fp8.hip index e8cc1fe9..a677f17a 100644 --- a/libr4d/r4d_givens_quant_act_fp8.hip +++ b/libr4d/r4d_givens_quant_act_fp8.hip @@ -5,8 +5,8 @@ // the weight is read by the plain MXFP4 GEMM unchanged. // // WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- -// that is how the checkpoint is trained, and the converter refuses one that does -- so a group is a -// closed system: its 128 values are rotated by S stages of 64 disjoint pairs and then quantised +// that is how the checkpoint is trained, and the converter and the loader (r4d_rad_relayout_givens_pairs) +// refuse one that does -- so a group is a closed system: its 128 values are rotated by S stages of 64 disjoint pairs and then quantised // with ONE scale. A wave owns a group. The values sit in LDS (128 floats a wave, no barrier // needed: a wave's LDS accesses are in order, and the pairs of a stage are disjoint so no two lanes // touch one address), each lane takes two pairs a stage, and the absmax is a wave reduction. The diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 8aef605f..268639b2 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -611,6 +611,71 @@ extern "C" int r4d_rad_unrelayout_w2a8(const RadParam* p, int n_p, int operand, return RAD_OK; } +/* ---- givens pairs: ParoQuant's rotation pairs (i32 [P*S, K]), stored as they are but CHECKED. + * The rotate kernels index a group's 128 LDS slots with them unchecked, so a stage that is not a + * pairing of its own group -- an index outside the group, or one column twice -- is refused here, + * at load, rather than read out of bounds. Operand 1 of the givens rows; the rest is as stored. */ +namespace { +constexpr int GV_PAIRS_OPERAND = 1; +constexpr long long GV_GROUP = 128; + +int gv_pairs_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + if (!out || !pl) return RAD_E_INVAL; + if (operand != GV_PAIRS_OPERAND) return RAD_E_UNSUPPORTED; + const long long K = r4d_pgeti_or(p, n_p, "n", 0); + if (K <= 0 || K % GV_GROUP || !selects(enc, sel, n, "t.pairs") || pl[0].rank != 2 || + pl[0].dtype != RAD_I32 || pl[0].shape[1] != K) return RAD_E_SHAPE; + fill(out, "r4d.givens.pairs", RAD_I32, pl[0].shape[0], K, pl[0].shape[0] * K * 4); + return RAD_OK; +} + +/* Every row (a stage of a part) is, group by group, a perfect matching of the group's columns. */ +bool gv_pairs_ok(const int32_t* pairs, long long rows, long long K) { + for (long long r = 0; r < rows; ++r) + for (long long g = 0; g < K; g += GV_GROUP) { + bool seen[GV_GROUP] = {}; + for (long long i = 0; i < GV_GROUP; ++i) { + const long long c = (long long)pairs[r * K + g + i] - g; + if (c < 0 || c >= GV_GROUP || seen[c]) return false; + seen[c] = true; + } + } + return true; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_givens_pairs(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + return gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, out); +} + +extern "C" int r4d_rad_relayout_givens_pairs(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + if (!gv_pairs_ok((const int32_t*)pl[0].data, L.shape[0], L.shape[1])) return RAD_E_FORMAT; + std::memcpy(dst, pl[0].data, (size_t)L.bytes); + return RAD_OK; +} + +extern "C" int r4d_rad_unrelayout_givens_pairs(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + std::memcpy(pl[0].data, src, (size_t)L.bytes); + return RAD_OK; +} + /* ---- MXFP4: fp4 e2m1 codes with an E8M0 exponent a 32. The codes go to fragment order, the * exponents to [K/32][N], and b_ref is each row's largest exponent -- a reduction over the plane, * which is a derivation any reader of the plane could make and so not a choice. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index cca59c78..87f3c96c 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -391,6 +391,12 @@ int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const in const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, void*, int64_t); +int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); +int r4d_rad_unrelayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); /* -- the small bf16 model ops (r4d_model_bf16.hip) -- * diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 16f0636b..92ad5970 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -5161,11 +5161,13 @@ static const RadKernelInfo kKernels[] = { "n a multiple of 128 -- a rotation group cannot straddle the end of a row -- and group 128, " "which is both the rotation group and the weight scale's activation block", "bf16 in, E4M3 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale per (row, part, " - "128 columns); the tables are the weight's int32 pairs, f32 angles and f32 channel scales", + "128 columns); the tables are the weight's int32 pairs (checked at load to pair each group's own " + "columns), f32 angles and f32 channel scales", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHadQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_givens_quant_act_fp8, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_givens_quant_act_fp8_describe }, + nullptr, nullptr, r4d_rad_givens_quant_act_fp8, nullptr, r4d_rad_layout_givens_pairs, + r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, + r4d_rad_givens_quant_act_fp8_describe }, { "quant_act_i8g", "quant_act_i8g", "quant", "per-(row, 128-column) symmetric int8 quantisation of a bf16 activation", diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index f1f45f96..d34b2801 100644 --- a/tests/relayout_parity_test.cpp +++ b/tests/relayout_parity_test.cpp @@ -760,3 +760,49 @@ TEST(a_kernel_refuses_an_encoding_it_does_not_read) { } RAD_TEST_MAIN() + +/* ParoQuant's rotation pairs are stored as they are -- and refused at load when a stage is not a + * pairing of its own group's 128 columns, which the rotate kernels would index out of bounds. */ +TEST(givens_pairs_are_stored_as_they_are_and_checked) { + const int64_t K = 256, R = 2; /* two groups, two stages */ + RadEncoding e = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + rad_enc_add_table(&e, "t.pairs", RAD_I32, R, K); + const int sel[1] = { rad_enc_find(&e, "t.pairs") }; + std::vector pairs((size_t)(R * K)); + for (int64_t r = 0; r < R; ++r) + for (int64_t c = 0; c < K; ++c) /* stage 0 reverses each group, stage 1 not */ + pairs[(size_t)(r * K + c)] = (int32_t)((c / 128) * 128 + (r ? c % 128 : 127 - c % 128)); + RadTensor t{}; + t.data = pairs.data(); + t.dtype = RAD_I32; + t.rank = 2; + t.shape[0] = R; + t.shape[1] = K; + t.stride[0] = K; + t.stride[1] = 1; + Opts kp; + kp.i("n", K).i("stages", 1).i("parts", 2); + RadLayout L{}; + CHECK_EQ(r4d_rad_layout_givens_pairs(kp.data(), kp.n(), 2, &e, sel, &t, 1, &L), RAD_E_UNSUPPORTED); + REQUIRE_EQ(r4d_rad_layout_givens_pairs(kp.data(), kp.n(), 1, &e, sel, &t, 1, &L), RAD_OK); + REQUIRE_EQ(L.bytes, (int64_t)(R * K * 4)); + std::vector dst((size_t)L.bytes); + REQUIRE_EQ(r4d_rad_relayout_givens_pairs(kp.data(), kp.n(), 1, &e, sel, &t, 1, dst.data(), L.bytes), + RAD_OK); + CHECK_EQ(std::memcmp(dst.data(), pairs.data(), dst.size()), 0); + std::vector back((size_t)(R * K), -1); + RadTensor tb = t; + tb.data = back.data(); + REQUIRE_EQ(r4d_rad_unrelayout_givens_pairs(kp.data(), kp.n(), 1, &e, sel, dst.data(), L.bytes, &tb, 1), + RAD_OK); + CHECK(back == pairs); + /* a pair leaving its group, and a column paired twice in a stage */ + std::vector out = pairs, dup = pairs; + out[(size_t)(K + 5)] = 130; + dup[3] = dup[4]; + for (std::vector* bad : { &out, &dup }) { + t.data = bad->data(); + CHECK_EQ(r4d_rad_relayout_givens_pairs(kp.data(), kp.n(), 1, &e, sel, &t, 1, dst.data(), L.bytes), + RAD_E_FORMAT); + } +} From e45bb596f4979e1e47288b85ad790c76daba9b36 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 06:50:50 +0000 Subject: [PATCH 06/17] format: import ParoQuant int5-bitplane and z-lab's int4 (u5/u4 codes, f16 scale, u8 zero, givens tables) --- core/format/checkpoint.cpp | 130 ++++++++++++++++++++++++++++++++++++- core/format/checkpoint.h | 9 ++- tests/checkpoint_test.cpp | 98 ++++++++++++++++++++++++++++ 3 files changed, 235 insertions(+), 2 deletions(-) diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index b7275c49..55d0c061 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -543,6 +543,17 @@ 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") { + /* z-lab's ParoQuant at integer widths, in the "int5-bitplane" packing: AWQ nibbles of the + * low four bits plus a bit plane for the fifth, group 128, asymmetric, with the learned + * rotations beside. Other widths and packings are not read. */ + if (qc("format") == "int5-bitplane" && qc("bits") == "5" && qc("group_size") == "128") + import_ = Import::ParoI5; + else if (qc("format").empty() && qc("bits") == "4" && qc("group_size") == "128") + import_ = Import::ParoI4; /* z-lab's own release: AWQ-packed int4, asymmetric */ + else + import_why_ = "ParoQuant here is not the int5-bitplane format with 5-bit codes in groups " + "of 128, 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 @@ -575,6 +586,51 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, return RAD_OK; } + if (import_ == Import::ParoI5 || import_ == Import::ParoI4) { + const bool i5 = import_ == Import::ParoI5; + /* PARO int5: `X.weight` is X.qweight/.qweight_hi (codes), X.scales (f16 [G, N]) and + * X.qzeros/.qzeros_hi (zero points). The view carries the logical [N, K] u5 matrix; the + * planes are re-laid row by row by ckpt_plane_rows. */ + const std::string suffix = ".weight"; + if (name.size() <= suffix.size() || + name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0) + return RAD_E_NOTFOUND; + const std::string base = name.substr(0, name.size() - suffix.size()); + const SrcTensor* qw = find(base + ".qweight"); + if (!qw) return RAD_E_NOTFOUND; + const SrcTensor* hi = i5 ? find(base + ".qweight_hi") : nullptr; + const SrcTensor* sc = find(base + ".scales"); + const SrcTensor* qz = find(base + ".qzeros"); + const SrcTensor* qzh = i5 ? find(base + ".qzeros_hi") : nullptr; + if ((i5 && (!hi || !qzh)) || !sc || !qz || qw->rad_dtype != RAD_I32 || + qz->rad_dtype != RAD_I32 || sc->rad_dtype != RAD_F16 || qw->shape.size() != 2 || + qz->shape.size() != 2 || sc->shape.size() != 2 || + (i5 && (hi->rad_dtype != RAD_I32 || qzh->rad_dtype != RAD_I32 || + hi->shape.size() != 2 || qzh->shape.size() != 2))) + return refuse(RAD_E_FORMAT, "'" + qw->name + "' lacks an int32 " + + (i5 ? "qweight_hi, qzeros_hi, " : "") + + "qzeros and an f16 scales beside it"); + const int64_t K = qw->shape[0], N = qw->shape[1] * 8, G = sc->shape[0]; + if (N % 32 || K % 128 || G * 128 != K || sc->shape[1] != N || qz->shape[0] != G || + qz->shape[1] != N / 8 || + (i5 && (hi->shape[0] != K || hi->shape[1] != N / 32 || qzh->shape[0] != G || + qzh->shape[1] != N / 32))) + return refuse(RAD_E_SHAPE, "'" + qw->name + "' planes do not fit a [" + + std::to_string(N) + ", " + std::to_string(K) + "] weight"); + SrcTensor c = *qw; + c.name = name; + c.rad_dtype = i5 ? RAD_U5 : RAD_U4; + c.shape = { N, K }; + c.int5 = true; + c.pbits = i5 ? 5 : 4; + c.aux[0] = hi; c.aux[1] = qz; c.aux[2] = qzh; + sliced_.push_back(std::move(c)); + *codes = &sliced_.back(); + *scale = sc; + imported_[name] = { *codes, *scale }; + return RAD_OK; + } + 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 @@ -991,6 +1047,25 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b (gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor"; } else if (!same) { out->why = "its pieces are stored in different dtypes"; + } else if (p0.int5) { + /* PARO int5-bitplane: u5 codes, an f16 scale and a u8 zero point a 128 of K, then the + * rotation tables. Joined only along rows (gate|up), as every imported form is. */ + bool fits = d == 0 || out->pieces.size() == 1; + for (const SrcTensor* pk : out->pieces) fits = fits && pk->int5 && pk->pbits == p0.pbits; + if (!fits) { + out->why = "its int5 pieces are joined along a column, across their groups"; + } else { + rad_enc_clear(&out->enc); + rad_enc_copy_str(out->enc.scheme, "affine"); + rad_enc_add_plane(&out->enc, "codes", p0.pbits == 5 ? RAD_U5 : RAD_U4, 1, 1); + rad_enc_add_plane(&out->enc, "scale", RAD_F16, 1, 128); + rad_enc_add_plane(&out->enc, "zero", RAD_U8, 1, 128); + const int rc = paro_attach(ck, out, why); + if (rc != RAD_OK) return rc; + out->why = std::string("it is ParoQuant int") + (p0.pbits == 5 ? "5" : "4") + + ", which rad-convert imports with its zero points and rotation tables -- " + "serve the container it writes"; + } } else if (p0.gptq_bits) { /* GPTQ-PACKED, IMPORTED: one width and one group throughout, joined only along rows -- * a column join would put two pieces' groups in one scale block. */ @@ -1314,7 +1389,60 @@ 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.paro && k >= 2) { + if (w.paro && w.pieces[0]->int5 && k <= 2) { + /* PARO int5-bitplane, RE-LAID a row of the logical [N, K] matrix at a time. The checkpoint + * packs along N: qweight [K, N/8] holds eight low nibbles per word in AWQ order (word + * column c of a group of eight sits in nibble j, ORDER[j] == c), and qweight_hi [K, N/32] + * the fifth bit of 32 columns, bit n % 32. The zero points are the same two packings over + * [G, N]. */ + auto nib = [](int c) { return c % 2 == 0 ? c / 2 : 4 + c / 2; }; /* AWQ order */ + auto u32 = [](const SrcTensor& t, int64_t i) { + uint32_t v; + std::memcpy(&v, (const uint8_t*)t.data + i * 4, 4); + return v; + }; + int64_t base = 0; + for (size_t pi = 0; pi < w.pieces.size(); ++pi) { + const SrcTensor* pc = w.pieces[pi]; + const int64_t Np = pc->shape[0], K = pc->shape[1], G = K / 128; + const SrcTensor *hip = pc->aux[0], *qzp = pc->aux[1], *qzhp = pc->aux[2]; + const SrcTensor& sc = *w.scales[pi]; + for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + Np); ++r) { + const int64_t n = r - base; + const int cn = (int)(n % 8); + if (k == 0) { + const int pb = pc->pbits; + const int64_t rb = (K * pb + 7) / 8; + std::memset(o, 0, (size_t)rb); + for (int64_t kk = 0; kk < K; ++kk) { + const uint32_t lo = (u32(*pc, kk * (Np / 8) + n / 8) >> (4 * nib(cn))) & 15u; + const uint32_t h = pb == 5 ? (u32(*hip, kk * (Np / 32) + n / 32) >> (n % 32)) & 1u : 0u; + const uint32_t code = lo | (h << 4); + const int64_t bit = kk * pb; + const uint32_t sh = (uint32_t)(bit & 7); + const uint32_t v = code << sh; + o[bit >> 3] |= (uint8_t)(v & 0xFFu); + if (sh + pb > 8) o[(bit >> 3) + 1] |= (uint8_t)(v >> 8); + } + o += rb; + } else if (k == 1) { + for (int64_t g = 0; g < G; ++g) { + std::memcpy(o, (const uint8_t*)sc.data + (g * Np + n) * 2, 2); + o += 2; + } + } else { + for (int64_t g = 0; g < G; ++g) { + const uint32_t lo = (u32(*qzp, g * (Np / 8) + n / 8) >> (4 * nib(cn))) & 15u; + const uint32_t h = pc->pbits == 5 ? (u32(*qzhp, g * (Np / 32) + n / 32) >> (n % 32)) & 1u : 0u; + *o++ = (uint8_t)(lo | (h << 4)); + } + } + } + base += Np; + } + return RAD_OK; + } + if (w.paro && std::strncmp(w.enc.plane[k].role, "t.", 2) == 0) { /* 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 diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 7548e5ad..ee522ca0 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -56,6 +56,13 @@ struct SrcTensor { * the K columns one row of its scale tensor covers. 0 for any other tensor. */ int32_t gptq_bits = 0; int64_t gptq_group = 0; + /* ParoQuant's int5-bitplane (Import::ParoI5): `data` is the AWQ-packed low nibbles qweight + * [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit + * plane qweight_hi [K, N/32], and the zero points qzeros [G, N/8] and qzeros_hi [G, N/32]. + * z-lab's int4 (Import::ParoI4) is the same without the fifth-bit planes (aux[0], aux[2] null). */ + bool int5 = false; + int pbits = 0; /* 5 for int5-bitplane, 4 for z-lab's plain AWQ-packed int4 */ + const SrcTensor* aux[3] = { nullptr, nullptr, nullptr }; int64_t numel() const { int64_t n = 1; @@ -133,7 +140,7 @@ public: * 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, ParoMx }; + enum class Import { None, Gptq, QuarkMx, ParoMx, ParoI5, ParoI4 }; Import imports() const { return import_; } const std::string& import_refusal() const { return import_why_; } diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index 0f8a9488..1968e8aa 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -834,3 +834,101 @@ TEST(a_paroquant_mxfp4_weight_carries_its_rotations_as_parts) { } remove_checkpoint(dir); } + +/* PAROQUANT INT5-BITPLANE: the low nibbles AWQ-packed along N (qweight [K, N/8], eight columns a + * 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 of the zero points. The logical [N, K] weight comes out as u5 codes (a bit + * stream along K), an f16 scale and a u8 zero a 128 of K, plus the rotation as `givens` tables. */ +TEST(a_paroquant_int5_weight_is_relaid_row_by_row) { + const int64_t N = 64, K = 256, G = K / 128; + uint32_t rng = 777; + auto next = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; }; + std::vector code((size_t)(N * K)), zero((size_t)(N * G)); + for (auto& c : code) c = (int)(next() % 32); + for (auto& z : zero) z = (int)(next() % 32); + static const int kOrder[8] = { 0, 2, 4, 6, 1, 3, 5, 7 }; + auto pack_awq = [&](const std::vector& v, int64_t rows) { // v[n * rows + r] -> [rows, N/8] + T t{ "", "I32", { rows, N / 8 }, {} }; + t.bytes.assign((size_t)(rows * N / 8 * 4), 0); + for (int64_t r = 0; r < rows; ++r) + for (int64_t n = 0; n < N; ++n) { + int j = 0; + while (kOrder[j] != n % 8) ++j; + uint32_t w; + uint8_t* p = t.bytes.data() + (r * (N / 8) + n / 8) * 4; + std::memcpy(&w, p, 4); + w |= (uint32_t)(v[(size_t)(n * rows + r)] & 15) << (4 * j); + std::memcpy(p, &w, 4); + } + return t; + }; + auto pack_hi = [&](const std::vector& v, int64_t rows) { + T t{ "", "I32", { rows, N / 32 }, {} }; + t.bytes.assign((size_t)(rows * N / 32 * 4), 0); + for (int64_t r = 0; r < rows; ++r) + for (int64_t n = 0; n < N; ++n) { + uint32_t w; + uint8_t* p = t.bytes.data() + (r * (N / 32) + n / 32) * 4; + std::memcpy(&w, p, 4); + w |= (uint32_t)((v[(size_t)(n * rows + r)] >> 4) & 1) << (n % 32); + std::memcpy(p, &w, 4); + } + return t; + }; + T qw = pack_awq(code, K), qwh = pack_hi(code, K), qz = pack_awq(zero, G), qzh = pack_hi(zero, G); + qw.name = "q.qweight"; qwh.name = "q.qweight_hi"; qz.name = "q.qzeros"; qzh.name = "q.qzeros_hi"; + T sc{ "q.scales", "F16", { G, N }, {} }; + for (int64_t i = 0; i < G * N; ++i) { + const uint16_t h = rad_f32_to_f16(0.01f * (float)(1 + next() % 50)); + sc.bytes.push_back((uint8_t)(h & 0xff)); + sc.bytes.push_back((uint8_t)(h >> 8)); + } + T pr{ "q.pairs", "I16", { 2, K }, {} }; + for (int64_t s = 0; s < 2; ++s) + for (int64_t i = 0; i < K; ++i) { + const int16_t v = (int16_t)(i % 128 ^ 1); // adjacent swap: a pairing + pr.bytes.push_back((uint8_t)(v & 0xff)); + pr.bytes.push_back((uint8_t)(v >> 8)); + } + T th{ "q.theta", "F16", { 2, K / 2 }, {} }, cs{ "q.channel_scales", "F16", { 1, K }, {} }; + for (int64_t i = 0; i < 2 * K / 2; ++i) { const uint16_t h = rad_f32_to_f16(0.3f); th.bytes.push_back(h & 0xff); th.bytes.push_back(h >> 8); } + for (int64_t i = 0; i < K; ++i) { const uint16_t h = rad_f32_to_f16(1.5f); cs.bytes.push_back(h & 0xff); cs.bytes.push_back(h >> 8); } + const std::string dir = write_checkpoint( + { qw, qwh, qz, qzh, sc, pr, th, cs }, + "{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":\"paroquant\"," + "\"bits\":5,\"group_size\":128,\"krot\":2,\"format\":\"int5-bitplane\"}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK(ck.imports() == Checkpoint::Import::ParoI5); + Program prog; + prog.name_map.push_back(map("w", RAD_MAP_COPY, { "q.weight" })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "w", false, &w, &why), RAD_OK); + REQUIRE(w.paro && w.imported); + CHECK_EQ(w.rows, N); + CHECK_EQ(w.cols, K); + REQUIRE(rad_enc_valid(&w.enc)); + CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_U5); + CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_F16); + CHECK_EQ(w.enc.plane[2].dtype, (uint32_t)RAD_U8); + 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].assign((size_t)(pr_ * rad_enc_row_bytes(w.enc.plane[k].dtype, pc)) + 8, 0); + REQUIRE_EQ(ckpt_plane_rows(w, k, 0, pr_, pl[(size_t)k].data(), &why), RAD_OK); + } + const int64_t rb = rad_enc_row_bytes(RAD_U5, K); + int bad = 0; + for (int64_t n = 0; n < N; ++n) { + for (int64_t k = 0; k < K; ++k) + if ((int)rad_load_f32(pl[0].data() + n * rb, RAD_U5, k) != code[(size_t)(n * K + k)]) ++bad; + for (int64_t g = 0; g < G; ++g) { + if (pl[2][(size_t)(n * G + g)] != zero[(size_t)(n * G + g)]) ++bad; + if (std::memcmp(pl[1].data() + (n * G + g) * 2, sc.bytes.data() + (g * N + n) * 2, 2) != 0) ++bad; + } + } + CHECK_EQ(bad, 0); + remove_checkpoint(dir); +} From ffa235bf0fa02bdc76a4df0ade0bedf9e80b0c7b Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 06:50:50 +0000 Subject: [PATCH 07/17] libref: givens_rotate (the rotation without the quantiser, f16 out) --- libref/ref_ops.h | 2 ++ libref/ref_quant.cpp | 18 ++++++++++++++---- libref/ref_registry.cpp | 9 +++++++++ libref/ref_shapes.cpp | 4 ++++ tests/ref_test.cpp | 2 +- 5 files changed, 30 insertions(+), 5 deletions(-) diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 1c91d3eb..25d21468 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -101,6 +101,7 @@ int ref_had_quant_act_i8 (const RadArgs*, RadStream); int ref_quant_act_fp8 (const RadArgs*, RadStream); int ref_had_quant_act_fp8 (const RadArgs*, RadStream); int ref_givens_quant_act_fp8(const RadArgs*, RadStream); +int ref_givens_rotate(const RadArgs*, RadStream); int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); int ref_gated_quant_fp8 (const RadArgs*, RadStream); int ref_gemm_nt_q_gated (const RadArgs*, RadStream); @@ -230,6 +231,7 @@ REF_SHAPE_FN(ref_had_quant_act_i8); REF_SHAPE_FN(ref_quant_act_fp8); REF_SHAPE_FN(ref_had_quant_act_fp8); REF_SHAPE_FN(ref_givens_quant_act_fp8); +REF_SHAPE_FN(ref_givens_rotate); REF_SHAPE_FN(ref_rmsnorm_quant_fp8); REF_SHAPE_FN(ref_gated_quant_fp8); REF_SHAPE_FN(ref_gemm_nt_q_gated); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 666126f9..8c79cf04 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -427,10 +427,10 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { * stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32, then amax/448 per group. Not * bit-identical to the device on the angle: cos and sin of an f32 differ by an ulp between libm * and the GPU's. */ -int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { - if (!have(a, 6)) return RAD_E_INVAL; +static int givens_body(const RadArgs* a, bool quant) { + if (!have(a, quant ? 6 : 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3]; - const RadTensor *q = &a->t[4], *s = &a->t[5]; + const RadTensor *q = &a->t[4], *s = quant ? &a->t[5] : nullptr; const int64_t n = p_int(a, "n", 0), S = p_int(a, "stages", 0), P = p_int(a, "parts", 1); int64_t g = p_int(a, "group", 0); if (n <= 0 || S <= 0 || P <= 0 || (n & 1)) return RAD_E_SHAPE; @@ -438,7 +438,7 @@ int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { if (numel(pr) < P * S * n || numel(an) < P * S * (n / 2) || numel(sc) < P * n) return RAD_E_SHAPE; const int64_t rows = numel(x) / n; const int64_t ngrp = n / g; - if (rows <= 0 || numel(q) < rows * P * n || numel(s) < rows * P * ngrp) return RAD_E_SHAPE; + if (rows <= 0 || numel(q) < rows * P * n || (quant && numel(s) < rows * P * ngrp)) return RAD_E_SHAPE; // validated before the loop, because an OpenMP body cannot return for (int64_t i = 0; i < P * S * n; ++i) { @@ -464,6 +464,10 @@ int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { buf[(size_t)ib] = vb * c - va * sn; } } + if (!quant) { // givens_rotate: the rotated row, in q's dtype + for (int64_t k = 0; k < n; ++k) st_dt(q->dtype, q->data, qb + (p * n + k) * qs, buf[(size_t)k]); + continue; + } for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g; float amax = 0.0f; @@ -486,6 +490,12 @@ int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { return RAD_OK; } +int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { return givens_body(a, true); } + +/* The same channel scale and rotations with NO quantiser: y = the rotated row in y's dtype, `parts` + * copies side by side. For a weight whose GEMM reads a 16-bit activation (w5a16). */ +int ref_givens_rotate(const RadArgs* a, RadStream) { return givens_body(a, false); } + /* ---------------------------------------------------------------- the Gram accumulator * * h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the DEQUANTISED E4M3 input, or diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 17b4d554..eb83a176 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -206,6 +206,8 @@ static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; * resolved, moved and placed with the weight they belong to. */ static const RadParamSpec pGivensQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INT("stages"), P_INT("parts") }; +static const RadOperandSpec oGivensRotate[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), + OUT("y") }; static const RadOperandSpec oGivensQuant[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), OUT("q"), OUT("scale") }; @@ -809,6 +811,10 @@ static const RadOpSchema kSchemas[] = { "stages) of `pairs` and `angle` and row p of `rscale`: a fused projection's pieces were each " "rotated on their own. Only a weight stored with the \"givens\" transform reads the result; " "it is NOT quant_act_fp8's output in either direction." }, +{ "givens_rotate", ARR(pGivensQuant), ARR(oGivensRotate), + "givens_quant_act_fp8 without the quantiser: y = x / rscale rotated by `stages` rounds of Givens " + "pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight whose GEMM " + "reads a 16-bit activation. `group` is the width a pair stays inside." }, { "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "A Walsh-Hadamard rotation of width `group` along n, then symmetric E4M3 per group: scale = " "amax(rotated) / 448, shaped [M, n/group] in f32. n must be a multiple of `group` -- a rotation " @@ -1171,6 +1177,9 @@ SIMPLE("ref_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm", SIMPLE("ref_dflash_select", "dflash_select", "draft", "DFlash2's greedy walk over the candidate lattice", "i32 candidates, bf16 codebooks, i32 tokens out", ref_dflash_select), +SIMPLE("ref_givens_rotate", "givens_rotate", "quant", + "channel scale and Givens rotations per part, in the output's dtype", + "float in, float out; int32 pairs, f32 angles and channel scales", ref_givens_rotate), SIMPLE("ref_givens_quant_act_fp8", "givens_quant_act_fp8", "quant", "channel scale and Givens rotations per part, then the block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; int32 pairs, f32 angles and channel scales", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index f06563bb..7aa5d46c 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -836,6 +836,10 @@ int ref_givens_quant_act_fp8_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; } +int ref_givens_rotate_shape(const RadParam*, int, int, RadOpdDesc*) { + return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ +} + int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 40cad408..df1fab70 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -261,7 +261,7 @@ TEST(op_vocabulary) { "embed_lookup_q", "cast", "scale_rows", "softmax", - "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "had_quant_act_i8", + "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "givens_rotate", "had_quant_act_i8", "gram_accum", /* The fused fp8 forms. A host run needs EVERY op covered, so these are what stands * between a host-backend run and "site 'host' is unavailable for this band". */ From 9e9fce3aca6fdf4209511ca6bd1c4ba1b29016d8 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 06:50:50 +0000 Subject: [PATCH 08/17] libr4d: w5a16 / w4a16_asym GEMM (5- and 4-bit asymmetric, any M, parts), givens_rotate kernel, layouts, selftest --- docs/GUIDE.md | 7 +- docs/OPS.md | 3 +- libr4d/CMakeLists.txt | 1 + libr4d/r4d_gemm_w5a16_nt_m64.hip | 376 ++++++++++++++++++++++++++++ libr4d/r4d_givens_quant_act_fp8.hip | 55 ++-- libr4d/r4d_layout.cpp | 96 ++++++- libr4d/r4d_plugin.h | 8 + libr4d/r4d_rows.cpp | 51 ++++ libr4d/r4d_selftest.cpp | 148 ++++++++++- 9 files changed, 722 insertions(+), 23 deletions(-) create mode 100644 libr4d/r4d_gemm_w5a16_nt_m64.hip diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 414d3e98..66e2126a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -344,13 +344,14 @@ that points each name at its copy. A name two shards hold that no index entry se The conversions of record live in `scripts/convfn.sh` and `scripts/convdspark.sh`, with their recipes in `data/recipes/`. -**A release someone else already quantised is read as it ships.** Three forms are imported weight +**A release someone else already quantised is read as it ships.** Four forms are imported weight by weight, so their quantised linears need no recipe rule: | `quantization_config` | read as | | |---|---|---| | `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) | | `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_quant_act_fp8` and the ordinary MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule | +| `paroquant`, `format int5-bitplane` (bits 5, group 128) and z-lab's plain `paroquant` (bits 4, group 128) | `u5*f16[1x128]-u8[1x128]/givens` and `u4*f16[1x128]-u8[1x128]/givens` | the AWQ-packed low nibbles (plus the fifth-bit plane) re-laid as a code bit stream along K, the f16 scales and the integer zero points transposed to `[N, K/128]`, and the rotation as the `givens` tables above. Convert-time only; served by `givens_rotate` and `gemm_nt_q` at `w5a16` / `w4a16_asym` over an f16 activation (docs/OPS.md) | | `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped | The width is read per tensor, so a release mixing int4 experts with int8 projections imports both. @@ -371,6 +372,10 @@ rad-convert ~/models/amd/Qwen3.8-27B-Quark-AWQ-MXFP4 --draft-model ~/models/z-la rad-convert ~/models/MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \ --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe -o q38-27b-paro-mxfp4-df2.rad +# ParoQuant int5 (Launch80/Qwen3.8-27B-PARO-int5) and z-lab's int4 (z-lab/Qwen3.8-27B-PARO): same recipe +rad-convert ~/models/Launch80/Qwen3.8-27B-PARO-int5 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \ + --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe -o q38-27b-paro-int5-df2.rad + # An AutoRound int4 Qwen3.8-Flash-Next: its experts imported, its int4 projections made int8 rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \ --recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe -o swift-autoround.rad diff --git a/docs/OPS.md b/docs/OPS.md index 31cfd85a..8fd23617 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -363,6 +363,7 @@ spelling of `act`, not the vocabulary's. | `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `givens_quant_act_fp8` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | +| `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` | | `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | @@ -385,7 +386,7 @@ copies of the activation, written side by side -- `q` is `[M, parts * n]`, `scal `[M, parts * n / group]` -- and `pairs` and `angle` stack the parts' `stages` rows each, `rscale` one row a part. `gemm_nt_q` then takes `pb1` and `pb2`, the row bounds of the weight's parts: its rows `[0, pb1)`, `[pb1, pb2)` and `[pb2, N)` meet copy 0, 1 and 2, and `a`/`a_scale` are the wide -planes. `pb1` absent is one part; `pb2` absent ends the second part at `N`. Only the `mxfp4a8` rows +planes. `givens_rotate` is the same rotation with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` (ParoQuant int5: u5 codes, an f16 scale and a u8 zero point a 128 of K) and `w4a16_asym` (z-lab's int4, the same at 4 bits); their GEMM serves any `M` (rows past 64 run as chunks of 64). `pb1` absent is one part; `pb2` absent ends the second part at `N`. Only the `mxfp4a8` rows read them, and the host rows that do not (`libavx`) refuse a call that names one rather than contract against the wrong copy. diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index b37c6bab..ff6a9ced 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -107,6 +107,7 @@ set(R4D_UNITS "r4d_gemm_bf16_nt_m64|" "r4d_gemm_bf16_nt_tiled|" "r4d_gemm_w4a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" + "r4d_gemm_w5a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w8a16_nt_m64|-DR4D_GEMM_W8_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w2a8_nt|-DR4D_GEMM_W2A8_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w4a8_nt_m64|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}" diff --git a/libr4d/r4d_gemm_w5a16_nt_m64.hip b/libr4d/r4d_gemm_w5a16_nt_m64.hip new file mode 100644 index 00000000..548d9b56 --- /dev/null +++ b/libr4d/r4d_gemm_w5a16_nt_m64.hip @@ -0,0 +1,376 @@ +// r4d_gemm_w5a16_nt_m64.hip - r4d_gemm_w5a16_nt_m64: 5-bit-weight skinny GEMM for M up to 64, +// gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate. +// +// r4d_gemm_w4a16_nt_m64 with a fifth bit per weight, for ParoQuant's int5 (asymmetric, an f16 scale +// and a 5-bit integer zero per 128 of K, the rotation done on the activation in front of it). The +// reading of that kernel's header holds word for word -- weight-streaming, memory-bound, f16 +// because 1024 + n is exact -- and this file only says what the fifth bit changes. +// +// THE WEIGHT BLOB IS TWO PLANES. The low four bits of every code are w4's fragment order exactly +// (offset binary here: the nibble is q & 15, no sign flip). The fifth bits follow as a second +// plane of 32-bit words, ONE A (n-tile, 64-wide k block, lane): +// +// hi[(t * (K/64) + kb) * 32 + lane] byte s = k step s of the block, bit e = element e +// +// element e of a lane's fragment being the same one nibble 2e / 2(e-4)+1 of dword s holds. So a +// lane's 16 bytes of nibbles and its 4 bytes of fifth bits cover the same 32 weights, and the +// second load is one dword a block. +// +// THE UNPACK ADDS TWO MULTIPLIES TO w4's. The even elements' fifth bits are the byte's low nibble, +// the odd elements' its high one; a 4-bit mask n becomes one bit a byte by n * 0x00204081 (bit j +// lands at 8j and nothing else lands on a multiple of eight below bit 32), masked with 0x01010101 +// and shifted to the 16s place of the nibble's byte. The 5-bit code is then 0..31, 1024 + q is +// exact in f16, and the zero point -- an integer 0..31 in the scale dword's high half as +// -(1024 + zero) -- subtracts exactly. +// +// The dispatcher takes M past 64 as chunks of 64 rows (the weight is re-read per chunk, which at a +// 2048-row prefill chunk is near the compute bound of the f16 matrix instruction anyway), and +// partitioned weights (ParoQuant's gate|up: `pb1`/`pb2`, see r4d_gemm_args.h) as one launch per +// part over windows of the planes. +#include "r4d.h" +#include "r4d_gemm_args.h" +#include "r4d_gdn_wmma.h" +#include +#include +#include +#include +#include + +#define R4D_GEMM_W4_MAX_M 64 +#ifndef R4D_GEMM_W4_GROUP +#define R4D_GEMM_W4_GROUP 128 // K per (scale, zero) pair +#endif +#define R4D_GEMM_W4_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane +#define WAVE32 32 + +typedef _Float16 v8h __attribute__((ext_vector_type(8))); +typedef unsigned uint4v __attribute__((ext_vector_type(4))); + +// NT reads the weight non-temporally. The weight is streamed once per step and never reused, while +// the activation is re-read once per column tile and wants to stay resident, so telling the cache +// not to keep the weight decides which of the two occupies the last level. It is a gain at M=8 and +// M=16 and a LOSS from M=24 up on the shapes with the longest K, so it is per-call, like every +// other geometry parameter, and the table in radiance_w4.py carries the value per M band. +// +// One copy of any of these weights fits this part's 64 MiB last level, so a bench that streams a +// SINGLE buffer in a loop measures a cache-resident machine and cannot see this effect at all; a +// pooled working set is what makes the difference visible. + +// NPW (column tiles per WAVE) is a template parameter because it sizes the accumulator array, and a +// launch argument because the right value is a property of M: at M=8 the kernel is at the DRAM +// roofline and NPW>1 only costs blocks, while at M=64 the activation re-read is four times the +// weight and NPW=4 is what claws it back. Instantiated only for the two values that win in +// practice; anything else is rejected rather than silently rounded. + +// Address-space-qualified so the loads stay global_load rather than flat_load: on gfx12 a flat +// load increments dscnt as well as loadcnt, so a later LDS wait would also wait on HBM. See the +// same declaration in r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar there. +typedef __attribute__((address_space(1))) const uint4v* r4d_gw4; +typedef __attribute__((address_space(1))) const unsigned long long* r4d_gu2; +typedef __attribute__((address_space(1))) const unsigned* r4d_gu1; + +__device__ __forceinline__ v8h fragA(r4d_gu2 p, int u) { + union { unsigned long long w[2]; v8h f; } x; + x.w[0] = p[4 * u]; + x.w[1] = p[4 * u + 2]; + return x.f; +} + +// One dword of eight nibbles -> one 16x16x16 f16 B fragment, minus the zero point. +// t0/t1 split the even and odd nibbles into bytes; each v_perm_b32 pairs two of those bytes with +// the constant high byte 0x64, which is the f16 exponent field for 1024. nz carries +// -(1024 + zero) in BOTH halves so one v_pk_add_f16 corrects a pair. +// The unpack is under a percent of this kernel at M=8, where it is at the DRAM roofline and the +// arithmetic hides in the load latency. It is a real fraction at M=64, but that band belongs to +// r4d_gemm_w4a8_nt_m64 -- and with no dequant at all the f16 form still trails the int8 one there, +// because the gap is the matrix instruction and not the dequant. Nothing here is worth a knob. +#ifndef R4D_GEMM_W4_TWOS +#define R4D_GEMM_W4_TWOS 1 +#endif + +// DO NOT FOLD THE GROUP SCALE INTO THE B FRAGMENT. One v_pk_mul_f16 per pair on the finished +// integer q is exact in f16, removes the second accumulator array entirely and takes the M=64 shape +// from 192 VGPRs to 135 -- and it is SLOWER on most of the drafter's shapes. The multiply lands +// inside the per-fragment dependent chain between the unpack and the WMMA, where the per-group +// epilogue it replaces sits outside it; this kernel is stall-bound, not register-bound. + +__device__ __forceinline__ v8h dequant(unsigned w, __half2 nz) { + const unsigned K64 = 0x64646464u; +#if R4D_GEMM_W4_TWOS + // The stored nibble is a 4-bit TWO'S COMPLEMENT code, because that is what + // r4d_gemm_w4a8_nt_m64 needs -- it shifts the nibble into the byte's high half and reads the + // byte signed. This kernel wants OFFSET BINARY, so that 1024 + n minus the constant 1024 + 8 + // is the value. The two differ by bit 3 of the nibble, so one XOR per spread dword converts, + // and the zero point is then pinned to 8 for every group. Two instructions per fragment, on + // the kernel whose whole unpack is a fraction of a percent of its time at M=8 -- which is why + // the conversion lives here and not in the int8 kernel, where the unpack is three instructions + // and does matter. One quantised weight, two kernels, dispatched on M. + const unsigned t0 = (w & 0x0F0F0F0Fu) ^ 0x08080808u; + const unsigned t1 = ((w >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; +#else + const unsigned t0 = w & 0x0F0F0F0Fu; + const unsigned t1 = (w >> 4) & 0x0F0F0F0Fu; +#endif + union { unsigned u[4]; __half2 h2[4]; v8h f; } x; + x.u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // nibbles 0, 2 + x.u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // nibbles 4, 6 + x.u[2] = __builtin_amdgcn_perm(K64, t1, 0x05010400u); // nibbles 1, 3 + x.u[3] = __builtin_amdgcn_perm(K64, t1, 0x05030402u); // nibbles 5, 7 +#pragma unroll + for (int i = 0; i < 4; i++) x.h2[i] = __hadd2(x.h2[i], nz); + return x.f; +} + +// One dword of eight nibbles plus the byte of their fifth bits -> one 16x16x16 f16 B fragment, +// minus the zero point. Nibble 2e (e < 4) / 2(e-4)+1 is fragment element e, so bits 0..3 of `hb` +// are the fifth bits of the even nibbles' elements and bits 4..7 the odd nibbles'. +__device__ __forceinline__ unsigned spread16(unsigned n) { // 4 bits -> bit 4 of each byte + return ((n * 0x00204081u) & 0x01010101u) << 4; +} +__device__ __forceinline__ v8h dequant5(unsigned w, unsigned hb, __half2 nz) { + const unsigned K64 = 0x64646464u; + const unsigned t0 = (w & 0x0F0F0F0Fu) | spread16(hb & 15u); + const unsigned t1 = ((w >> 4) & 0x0F0F0F0Fu) | spread16(hb >> 4); + union { unsigned u[4]; __half2 h2[4]; v8h f; } x; + x.u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // elements 0, 1 + x.u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // elements 2, 3 + x.u[2] = __builtin_amdgcn_perm(K64, t1, 0x05010400u); // elements 4, 5 + x.u[3] = __builtin_amdgcn_perm(K64, t1, 0x05030402u); // elements 6, 7 +#pragma unroll + for (int i = 0; i < 4; i++) x.h2[i] = __hadd2(x.h2[i], nz); + return x.f; +} + +__device__ __forceinline__ v8f mmah(v8h a, v8h b, v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +} + +// MT = row tiles per BLOCK, as in the bf16 kernel: more of them amortise the weight fragment and +// its unpack over more WMMA, fewer put more blocks on the machine. +// HI false is the 4-bit asymmetric grid (z-lab's plain int4): the same kernel with no fifth-bit plane. +template +__global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel( + const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq, + const unsigned* __restrict__ Whi, const unsigned* __restrict__ Wsz, + __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK, int lda, int ldc) { + extern __shared__ float red[]; // WV*NPW*SK*256 floats: a 16x16 tile per (column, split) + const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32; + const int col_local = wave / SK, ksplit = wave % SK; + const int nt0 = (blockIdx.x * WV + col_local) * NPW; + const int n0 = nt0 * 16; + const int mt0 = blockIdx.y * MT; + const int Ks = K / SK; + const int groups = Ks / R4D_GEMM_W4_GROUP; // groups this split owns + const int kbase = ksplit * Ks; + + v8f acc[NPW][MT]; +#pragma unroll + for (int j = 0; j < NPW; j++) +#pragma unroll + for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f); + + if (n0 < N) { + // Activation: rows clamped, never masked -- a tile past M re-reads the last valid row and + // computes a result nobody stores. + unsigned aoff[MT]; +#pragma unroll + for (int i = 0; i < MT; i++) + aoff[i] = rowGo((unsigned)lda, (mt0 + i) * 16, M - 1, lane) + (unsigned)kbase; + r4d_gu2 pa[MT]; +#pragma unroll + for (int i = 0; i < MT; i++) pa[i] = (r4d_gu2)(const unsigned long long*)(A + aoff[i]); + + // Weight: one uint4 per lane per four k steps, tiles already permuted, so the whole k loop is + // global_load_b128 with a constant stride and no address arithmetic per step. + const int kpb = K / R4D_GEMM_W4_KPB; // packed blocks in a full row of tiles + const int nsz = K / R4D_GEMM_W4_GROUP; // (scale, zero) dwords per row of tiles + r4d_gw4 pw[NPW]; + r4d_gu1 ph[NPW]; + r4d_gu1 ps[NPW]; + const int ntlast = N / 16 - 1; +#pragma unroll + for (int j = 0; j < NPW; j++) { + // Clamped, like the row tiles: a wave whose last column tiles run past N re-reads the last + // real tile and computes a result the store discards, rather than reading memory it does not + // own or diverging the whole k loop on a mask. + const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast; + pw[j] = (r4d_gw4)(const uint4v*)(Wq) + + (size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane; + // Quantizer parameters: 16 distinct dwords per group, read by the 16 lanes that own the rows. + ph[j] = (r4d_gu1)(const unsigned*)(HI ? Whi : Wq) + + (size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane; + ps[j] = (r4d_gu1)(const unsigned*)(Wsz) + + (size_t)(t * nsz + kbase / R4D_GEMM_W4_GROUP) * 16 + (lane & 15); + } + + const int bpg = R4D_GEMM_W4_GROUP / R4D_GEMM_W4_KPB; // packed blocks per group + + for (int g = 0; g < groups; g++) { + float sc[NPW]; + __half2 nz[NPW]; +#pragma unroll + for (int j = 0; j < NPW; j++) { + const unsigned sz = ps[j][(size_t)g * 16]; + sc[j] = __half2float(__ushort_as_half((unsigned short)(sz & 0xFFFFu))); + nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16))); + } + + // The first WMMA of a group takes an inline zero for C, so the group accumulator costs no + // instruction to clear. + v8f g_acc[NPW][MT]; +#pragma unroll + for (int b = 0; b < bpg; b++) { + uint4v wv[NPW]; + unsigned hv[NPW]; +#pragma unroll + for (int j = 0; j < NPW; j++) { + const size_t o = (size_t)(g * bpg + b) * WAVE32; + wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o]; + hv[j] = HI ? (NT ? __builtin_nontemporal_load(&ph[j][o]) : ph[j][o]) : 0u; + } +#pragma unroll + for (int s = 0; s < 4; s++) { + const int u = b * 4 + s; + v8h afrag[MT]; +#pragma unroll + for (int i = 0; i < MT; i++) afrag[i] = fragA(pa[i], u); // loaded once, spent NPW times +#pragma unroll + for (int j = 0; j < NPW; j++) { + const v8h bfrag = dequant5(wv[j][s], (hv[j] >> (8 * s)) & 0xFFu, nz[j]); +#pragma unroll + for (int i = 0; i < MT; i++) + g_acc[j][i] = u == 0 ? mmah(afrag[i], bfrag, (v8f)(0.f)) + : mmah(afrag[i], bfrag, g_acc[j][i]); + } + } + } +#pragma unroll + for (int j = 0; j < NPW; j++) +#pragma unroll + for (int i = 0; i < MT; i++) +#pragma unroll + for (int e = 0; e < 8; e++) acc[j][i][e] = fmaf(g_acc[j][i][e], sc[j], acc[j][i][e]); +#pragma unroll + for (int i = 0; i < MT; i++) pa[i] += (R4D_GEMM_W4_GROUP / 16) * 4; + } + } + + // Split-K reduction and store: identical to r4d_gemm_bf16_nt_m64, one row tile at a time so the + // LDS is WV*SK KiB whatever MT is, and in a fixed order over splits so the result does not depend + // on how the waves were scheduled. + const int ncols = WV * NPW; + const int nthreads = WV * SK * WAVE32; +#pragma unroll + for (int i = 0; i < MT; i++) { + __syncthreads(); +#pragma unroll + for (int j = 0; j < NPW; j++) { + const int slot = ((col_local * NPW + j) * SK + ksplit) * 256; +#pragma unroll + for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[j][i][e]; + } + __syncthreads(); + for (int idx = tid; idx < ncols * 256; idx += nthreads) { + const int col = idx >> 8, off = idx & 255; + float v = 0.f; + for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off]; + const int l = off & 31; + const int n = (blockIdx.x * ncols + col) * 16 + (l & 15); + const int m = (mt0 + i) * 16 + 8 * (l >> 4) + (off >> 5); + if (n < N && m < M) C[(size_t)m * ldc + n] = (__hip_bfloat16)v; + } + } +} + +void r4d_gemm_w5a16_nt_m64(long a, long wq, long whi, long wsz, long c, int M, int K, int N, + int WV, int SK, int MB, int NPW, int NT, long stream, int lda, int ldc, + bool hi5) { + if (!lda) lda = K; + if (!ldc) ldc = N; + if (M < 1 || M > R4D_GEMM_W4_MAX_M) + throw std::runtime_error("r4d gemm_w4a16_nt_m64: M must be 1..64"); + if (N % 16) throw std::runtime_error("r4d gemm_w4a16_nt_m64: N must be a multiple of 16"); + if (K % (SK * R4D_GEMM_W4_GROUP)) + throw std::runtime_error("r4d gemm_w4a16_nt_m64: K must be divisible by SK*128"); + if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w4a16_nt_m64: threads/block > 1024"); + if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w4a16_nt_m64: MB must be 1..4"); + if (NPW != 1 && NPW != 4) throw std::runtime_error("r4d gemm_w4a16_nt_m64: NPW must be 1 or 4"); + const int ntiles = N / 16, mtiles = (M + 15) / 16; + const int ncols = WV * NPW; + dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32); + size_t smem = (size_t)ncols * SK * 256 * sizeof(float); + if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w4a16_nt_m64: WV*NPW*SK too large"); + auto Ap = (const unsigned short*)a; + auto Wp = (const unsigned*)wq; + auto Hp = (const unsigned*)whi; + auto Sp = (const unsigned*)wsz; + auto Cp = (__hip_bfloat16*)c; + hipStream_t st = (hipStream_t)stream; +#define LAUNCH(MT, NP, TT) do { \ + if (hi5) hipLaunchKernelGGL((r4d_gemm_w5a16_nt_m64_kernel), grid, block, smem, \ + st, Ap, Wp, Hp, Sp, Cp, M, K, N, WV, SK, lda, ldc); \ + else hipLaunchKernelGGL((r4d_gemm_w5a16_nt_m64_kernel), grid, block, smem, \ + st, Ap, Wp, Hp, Sp, Cp, M, K, N, WV, SK, lda, ldc); } while (0) +#define LAUNCH_MB(NP, TT) switch (MB) { \ + case 1: LAUNCH(1, NP, TT); break; \ + case 2: LAUNCH(2, NP, TT); break; \ + case 3: LAUNCH(3, NP, TT); break; \ + case 4: LAUNCH(4, NP, TT); break; \ + default: throw std::runtime_error("r4d gemm_w4a16_nt_m64: MB unsupported"); } + if (NPW == 1) { + if (NT) { LAUNCH_MB(1, true); } else { LAUNCH_MB(1, false); } + } else { + if (NT) { LAUNCH_MB(4, true); } else { LAUNCH_MB(4, false); } + } +#undef LAUNCH_MB +#undef LAUNCH +} + +int r4d_gemm_w5a16_nt_m64_max_m(void) { return R4D_GEMM_W4_MAX_M; } +int r4d_gemm_w5a16_nt_m64_group(void) { return R4D_GEMM_W4_GROUP; } + +// ============================================================== the plugin ABI entry points +// +// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there +// is no adapter directory between the core and these launches. +/* ------------------------------------------------------------------ f16-activation grids */ + +static int w5_dispatch(const RadArgs* a, RadStream s, bool hi5) { + GemmOps g; + int rc = gemm_ops(a, &g, 1); + if (rc != RAD_OK) return rc; + if (g.N % 16) return R4D_NO(RAD_E_SHAPE); + MxParts mp; + rc = mx_parts(a, &g, &mp); + if (rc != RAD_OK) return rc; + if (g.K % R4D_GEMM_W4_GROUP) return R4D_NO(RAD_E_SHAPE); + const int group = r4d_gemm_w5a16_nt_m64_group(); + // The row's M is the step's, not the kernel's: rows past 64 are chunks of 64, each its own pass + // over the weight, so a prefill chunk costs the weight's bytes once a 64 rows. + const long long mc = std::min(g.M, r4d_gemm_w5a16_nt_m64_max_m()); + Cfg c; + rc = cfg_for(a, g.K, mc, group, BR_FLAT, &c); + if (rc != RAD_OK) return rc; + const long long Ntot = g.N, K = g.K, lda = mp.lda ? mp.lda : g.K; + const long long nsz = K / R4D_GEMM_W4_GROUP; + for (int p = 0; p < mp.n; ++p) { + const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p]; + for (long long m0 = 0; m0 < g.M; m0 += mc) { + const long long mm = std::min(mc, g.M - m0); + R4D_TRY("gemm_w5a16_nt_m64", + r4d_gemm_w5a16_nt_m64( + r4d_addr(g.a) + (m0 * lda + p * K) * 2, + r4d_addr(g.b) + n0 * K / 2, /* the nibble plane */ + hi5 ? r4d_addr(g.b) + Ntot * K / 2 + n0 * K / 8 : 0L, /* the fifth-bit plane */ + r4d_addr(g.bscale) + (n0 / 16) * nsz * 16 * 4, + r4d_addr(g.y) + (m0 * Ntot + n0) * 2, + (int)mm, (int)K, (int)np, c.wv, c.sk, c.mb, c.npw, c.nt, (long)(uintptr_t)s, + (int)lda, (int)Ntot, hi5)); + } + } + return RAD_OK; +} + +extern "C" int r4d_rad_gemm_w5a16_m64(const RadArgs* a, RadStream s) { return w5_dispatch(a, s, true); } +/* ...and the plain 4-bit asymmetric grid (z-lab's int4), whose blob is the nibble plane alone. */ +extern "C" int r4d_rad_gemm_w4a16asym_m64(const RadArgs* a, RadStream s) { return w5_dispatch(a, s, false); } diff --git a/libr4d/r4d_givens_quant_act_fp8.hip b/libr4d/r4d_givens_quant_act_fp8.hip index a677f17a..b5bed570 100644 --- a/libr4d/r4d_givens_quant_act_fp8.hip +++ b/libr4d/r4d_givens_quant_act_fp8.hip @@ -32,6 +32,7 @@ #include "r4d_emit.h" #include "r4d_fp8_args.h" #include "r4d_fp8_wmma.h" +#include namespace { @@ -57,6 +58,9 @@ __device__ __forceinline__ void wave_sync() { // spreads a row's `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is // several blocks and a decode step of a few rows still fills the part. A wave that has no group // returns at once; nothing in the kernel is a block barrier. +// QUANT false is givens_rotate: the same rotation, no quantiser, the rotated row written as f16 into +// `q` (read as a uint16 plane, y_ld elements a row) for a GEMM that reads a 16-bit activation. +template __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs, const float* __restrict__ angle, const float* __restrict__ rscale, uint8_t* __restrict__ q, @@ -122,6 +126,15 @@ __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( const float4 r = *(const float4*)(buf + lane * 4u); float v[4] = { r.x, r.y, r.z, r.w }; + if constexpr (!QUANT) { + // f16 holds +-65504; a rotated post-norm row is orders below that, and the clamp keeps an + // outlier finite instead of inf + union { __half h[4]; uint2 u; } o; +#pragma unroll + for (int j = 0; j < 4; ++j) o.h[j] = __float2half(fminf(fmaxf(v[j], -65504.0f), 65504.0f)); + *(uint2*)((uint16_t*)q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = o.u; + return; + } float m = 0.0f; #pragma unroll for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); @@ -147,8 +160,8 @@ __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( // s [M][parts*K/128] f32 static int givens_quant_launch(long x, long pairs, long angle, long rscale, long q, long s, int M, int K, int parts, int stages, int x_ld, int q_ld, int s_ld, - const R4dSink& sk) { - if (!x || !pairs || !angle || !rscale || !q || !s) return -1; + const R4dSink& sk, bool quant = true) { + if (!x || !pairs || !angle || !rscale || !q || (quant && !s)) return -1; if (M <= 0 || K <= 0 || parts <= 0 || stages <= 0) return -2; if (K % (int)kGroup) return -3; // a rotation group cannot straddle the end of a row if (!x_ld) x_ld = K; @@ -156,11 +169,17 @@ static int givens_quant_launch(long x, long pairs, long angle, long rscale, long if (!q_ld) q_ld = parts * K; if (!s_ld) s_ld = parts * nkb; const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves; - const int rc = R4D_EMIT(sk, givens_quant_act_fp8_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, - (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, - (const float*)rscale, (uint8_t*)q, (float*)s, (uint32_t)K, - (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, (uint32_t)x_ld, - (uint32_t)q_ld, (uint32_t)s_ld); + const int rc = quant + ? R4D_EMIT(sk, givens_quant_act_fp8_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, + (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, + (const float*)rscale, (uint8_t*)q, (float*)s, (uint32_t)K, + (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, (uint32_t)x_ld, + (uint32_t)q_ld, (uint32_t)s_ld) + : R4D_EMIT(sk, givens_quant_act_fp8_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, + (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, + (const float*)rscale, (uint8_t*)q, (float*)s, (uint32_t)K, + (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, (uint32_t)x_ld, + (uint32_t)q_ld, (uint32_t)s_ld); if (rc != RAD_OK) return -4; return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0; } @@ -170,16 +189,17 @@ extern "C" int r4d_givens_quant_act_fp8_group(void) { return (int)kGroup; } // ============================================================== the plugin ABI entry point enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Q = 4, GV_S = 5 }; -static int rad_givens_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { +static int givens_body(const RadArgs* a, const R4dSink& sk, bool quant) { const RadTensor* x = r4d_opt(a, GV_X); const RadTensor* pr = r4d_opt(a, GV_PAIRS); const RadTensor* an = r4d_opt(a, GV_ANGLE); const RadTensor* rs = r4d_opt(a, GV_RSCALE); const RadTensor* q = r4d_opt(a, GV_Q); - const RadTensor* sc = r4d_opt(a, GV_S); - if (!x || !pr || !an || !rs || !q || !sc) return R4D_NO(RAD_E_INVAL); - if (x->rank < 2 || q->rank != 2 || sc->rank != 2 || pr->rank != 2 || an->rank != 2 || + const RadTensor* sc = quant ? r4d_opt(a, GV_S) : nullptr; + if (!x || !pr || !an || !rs || !q || (quant && !sc)) return R4D_NO(RAD_E_INVAL); + if (x->rank < 2 || q->rank != 2 || (quant && sc->rank != 2) || pr->rank != 2 || an->rank != 2 || rs->rank != 2) return R4D_NO(RAD_E_SHAPE); + if (!quant && q->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); // rows are dim 0 and everything after it is the row, as quant_act_fp8 reads them @@ -189,18 +209,25 @@ static int rad_givens_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { if (r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1) return R4D_NO(RAD_E_SHAPE); if (q->shape[0] != M || q->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE); - if (sc->shape[0] != M || sc->shape[1] != parts * nkb) return R4D_NO(RAD_E_SHAPE); + if (quant && (sc->shape[0] != M || sc->shape[1] != parts * nkb)) return R4D_NO(RAD_E_SHAPE); // the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE); if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE); if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(q->data, 4)) return R4D_NO(RAD_E_ALIGN); - const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); + const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = quant ? r4d_row_pitch(sc) : 0; if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); const int e = givens_quant_launch(r4d_addr(x), r4d_addr(pr), r4d_addr(an), r4d_addr(rs), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, (int)parts, - (int)stages, (int)xp, (int)qp, (int)sp, sk); + (int)stages, (int)xp, (int)qp, (int)sp, sk, quant); return e == 0 ? RAD_OK : RAD_E_SHAPE; } +static int rad_givens_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { + return givens_body(a, sk, true); +} +static int rad_givens_rotate_body(const RadArgs* a, const R4dSink& sk) { + return givens_body(a, sk, false); +} R4D_ENTRY(r4d_rad_givens_quant_act_fp8, rad_givens_quant_act_fp8_body) +R4D_ENTRY(r4d_rad_givens_rotate, rad_givens_rotate_body) diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 268639b2..f2d19202 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -342,6 +342,26 @@ void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym) } } +/* A ROTATED asymmetric grid (ParoQuant): codes of `codes` dtype, an f16 scale and a u8 zero point a + * group, then a `givens` transform and its tables -- the same bytes as the unrotated grid, the + * rotation being the activation's. */ +static bool paro_asym_enc(const RadEncoding* e, uint32_t codes, long long group) { + if (!e || !rad_enc_is(e, "affine") || e->n_planes < 3) return false; + const bool giv = std::strncmp(e->transform, "givens", RAD_ENC_STR) == 0; + if (!giv && e->transform[0]) return false; + if (!giv && e->n_planes != 3) return false; + if (giv && (!rad_enc_valid(e) || rad_enc_find(e, "t.pairs") < 0)) return false; + if (std::strncmp(e->plane[0].role, "codes", RAD_ENC_STR) != 0 || e->plane[0].dtype != codes || + e->plane[0].block[0] != 1 || e->plane[0].block[1] != 1) return false; + const int s = rad_enc_find(e, "scale"), z = rad_enc_find(e, "zero"); + if (s != 1 || z != 2) return false; + return e->plane[s].dtype == RAD_F16 && e->plane[s].kind == RAD_PLANE_TILED && + e->plane[s].block[0] == 1 && e->plane[s].block[1] == group && + (e->plane[z].dtype == RAD_U8 || e->plane[z].dtype == codes) && + e->plane[z].kind == RAD_PLANE_TILED && e->plane[z].block[0] == 1 && + e->plane[z].block[1] == group; +} + /* ---- w4: a symmetric grid is i4 codes with an f16 scale; `_asym` is u4 codes with a zero. */ int w4_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) { @@ -352,7 +372,8 @@ int w4_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en if (g.K % R4D_W4_KPB) return RAD_E_SHAPE; const bool asym = w4_asym(p, n_p); const bool ok = asym ? (r4d_enc::affine(enc, RAD_U4, RAD_F16, 1, g.group, RAD_U8) || - r4d_enc::affine(enc, RAD_U4, RAD_F16, 1, g.group, RAD_U4)) + r4d_enc::affine(enc, RAD_U4, RAD_F16, 1, g.group, RAD_U4) || + paro_asym_enc(enc, RAD_U4, g.group)) : r4d_enc::affine(enc, RAD_I4, RAD_F16, 1, g.group); if (!ok) return RAD_E_DTYPE; if (gout) *gout = g; @@ -437,6 +458,79 @@ extern "C" int r4d_rad_unrelayout_w4(const RadParam* p, int n_p, int operand, return RAD_OK; } +/* ---- w5: ParoQuant's int5, asymmetric: u5 codes, an f16 scale and a u8 zero point (0..31) a 128 of K. + * The blob is w4's fragment order for the low four bits of every code (offset binary, no sign flip) + * followed by a plane of 32-bit words holding the fifth bits, one a (n-tile, 64 of K, lane): byte s + * is k step s of the block and bit e the fragment element e -- the element whose nibble is + * 2e (e < 4) or 2(e-4)+1 in dword s of that lane's 16 bytes (r4d_gemm_w5a16_nt_m64.hip). The scale + * operand is w4u's (scale, zero) dword plane. A ROTATED weight (a `givens` transform and its + * tables beside the first three planes) is the same bytes: the rotation is the activation's. */ +namespace { +bool w5_enc(const RadEncoding* e, long long group) { return paro_asym_enc(e, RAD_U5, group); } + +int w5_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; + WGeom g; + int rc = wgeom(p, n_p, R4D_W4_GROUP, &g); + if (rc != RAD_OK) return rc; + if (g.K % R4D_W4_KPB) return RAD_E_SHAPE; + if (!w5_enc(enc, g.group)) return RAD_E_DTYPE; + if (gout) *gout = g; + if (operand == Q_BSCALE) + return sz_layout(g, enc, sel, pl, n, true, "r4d.w5.sz.g128", R4D_DT_W4_SZ, 4, out); + if (operand != Q_B) return RAD_E_UNSUPPORTED; + if (!selects(enc, sel, n, "codes") || !dims(pl[0], g.N, g.K)) return RAD_E_SHAPE; + fill(out, "r4d.w5.frag.g128", R4D_DT_W4_FRAG, g.N, g.K, g.N * g.K * 5 / 8); + return RAD_OK; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_w5(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* pl, int n, RadLayout* out) { + return w5_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr); +} + +extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + WGeom g; + const int rc = w5_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes) return RAD_E_SHAPE; + std::memset(dst, 0, (size_t)dst_bytes); + if (operand == Q_BSCALE) { + sz_write(g, pl, -1, (uint32_t*)dst); + return RAD_OK; + } + uint32_t* wq = (uint32_t*)dst; + uint32_t* hi = wq + g.N * g.K / 8; /* after the N*K/2 bytes of nibbles */ + const long long kpb = g.K / R4D_W4_KPB; + const long long rb = (g.K * 5 + 7) / 8; + for (long long nn = 0; nn < g.N; ++nn) { + const uint8_t* row = pdata(pl[0]) + nn * rb; + for (long long k = 0; k < g.K; ++k) { + const long long bit = k * 5; + uint32_t v = row[bit >> 3]; + if ((bit & 7) > 3) v |= (uint32_t)row[(bit >> 3) + 1] << 8; + const uint32_t q = (v >> (bit & 7)) & 31u; + long long w; + int nib; + w4_slot(g, nn, k, &w, &nib); + wq[w] |= (q & 15u) << (4 * nib); + /* the fifth bit: word (t, kb, lane) = w / 4 (w4_slot's dword index is that * 4 + s); + * byte s = w % 4, bit e from the nibble position */ + const long long hw = w / 4; + const int s = (int)(w % 4); + const int e = nib % 2 == 0 ? nib / 2 : 4 + nib / 2; /* nibble 2e / 2(e-4)+1 -> e */ + hi[hw] |= (q >> 4) << (8 * s + e); + } + } + (void)kpb; + return RAD_OK; +} + /* ---- w8: i8 codes, symmetric about zero, an f16 scale a group. The f16 kernel (a16) reads the * code offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed with a * bare f16 scale plane. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 87f3c96c..dec3ecf4 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -216,6 +216,8 @@ int r4d_rad_gemm_bf16_m16 (const RadArgs*, RadStream); int r4d_rad_gemm_bf16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_bf16_tiled (const RadArgs*, RadStream); int r4d_rad_gemm_w4a16_m64 (const RadArgs*, RadStream); +int r4d_rad_gemm_w5a16_m64 (const RadArgs*, RadStream); +int r4d_rad_gemm_w4a16asym_m64(const RadArgs*, RadStream); int r4d_rad_gemm_w8a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_tiled (const RadArgs*, RadStream); @@ -319,6 +321,8 @@ int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_had_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +int r4d_rad_givens_rotate (const RadArgs*, RadStream); +int r4d_rad_givens_rotate_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_givens_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_givens_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream); @@ -387,6 +391,10 @@ int r4d_rad_relayout_w8a16(const RadParam*, int, int, const RadEncoding*, const const RadTensor*, int, void*, int64_t); int r4d_rad_relayout_w8a8(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, void*, int64_t); +int r4d_rad_layout_w5(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_w5(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 92ad5970..1414c920 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1062,6 +1062,13 @@ static const RadParamSpec pGivensQuantAct[] = { { "stages", RAD_P_INT, RAD_REQUIRED }, { "parts", RAD_P_INT, RAD_REQUIRED }, }; +static const RadOperandSpec oGivensRotate[] = { + { "x", RAD_OPD_IN, 0 }, + { "pairs", RAD_OPD_WEIGHT, 0 }, + { "angle", RAD_OPD_WEIGHT, 0 }, + { "rscale", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; static const RadOperandSpec oGivensQuantAct[] = { { "x", RAD_OPD_IN, 0 }, { "pairs", RAD_OPD_WEIGHT, 0 }, @@ -2324,6 +2331,10 @@ static const RadOpSchema kSchemas[] = { SCHEMA("had_quant_act_i8g", pQuantActFp8, oQuantActFp8, "quant_act_i8g with a `group`-wide Hadamard along K first; pairs with an i8 weight stored " "rotated, its scale carrying the residual factor of `group`."), + SCHEMA("givens_rotate", pGivensQuantAct, oGivensRotate, + "givens_quant_act_fp8 without the quantiser: y = x / rscale rotated by `stages` rounds of " + "Givens pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight " + "whose GEMM reads a 16-bit activation. `group` is the width a pair stays inside."), SCHEMA("givens_quant_act_fp8", pGivensQuantAct, oGivensQuantAct, "ParoQuant's activation quantiser: x is divided by the channel scale `rscale`, rotated by " "`stages` rounds of disjoint Givens pairs (a' = a cos t + b sin t, b' = b cos t - a sin t, " @@ -2926,6 +2937,13 @@ static const RadConstraint cGemmNtTiled[] = { static const RadConstraint cGemmNtW4[] = { C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16"), }; +/* w5a16 serves any M: the dispatcher takes rows past 64 as chunks of 64. */ +static const RadConstraint cGemmNtW5[] = { + C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w5a16"), +}; +static const RadConstraint cGemmNtW4Asym[] = { + C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16_asym"), +}; static const RadConstraint cGemmNtW2A8[] = { C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w2a8"), }; @@ -4672,6 +4690,29 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_gemm_w4a16_m64, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, r4d_rad_unrelayout_w4 }, +{ "gemm_w5a16_nt_m64", "gemm_nt_q", "gemm", + "skinny GEMM with a 5-bit asymmetric weight (ParoQuant int5), 16x16x16 f16 WMMA, split-K reduced " + "in LDS; rows past 64 in chunks of 64, a partitioned weight (pb1/pb2) one launch a part", + "N a multiple of 16; K divisible by SK*128; weight pre-permuted into fragment order, a nibble " + "plane then a fifth-bit plane", + "f16 A (parts side by side), 5-bit W with an f16 scale and integer zero per 128 K, bf16 C, fp32 " + "accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, + ROW(cGemmNtW5), ROW(tGemmSkinny), r4d_tune_valid_gemm, + nullptr, nullptr, r4d_rad_gemm_w5a16_m64, nullptr, r4d_rad_layout_w5, r4d_rad_relayout_w5, + nullptr, nullptr }, + +{ "gemm_w4a16_asym_nt_m64", "gemm_nt_q", "gemm", + "skinny GEMM with a 4-bit ASYMMETRIC weight (z-lab's ParoQuant int4), the 5-bit row's kernel with " + "no fifth-bit plane; rows past 64 in chunks of 64, a partitioned weight (pb1/pb2) one launch a part", + "N a multiple of 16; K divisible by SK*128; weight pre-permuted into fragment order, unsigned nibbles", + "f16 A (parts side by side), 4-bit W with an f16 scale and integer zero per 128 K, bf16 C, fp32 " + "accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, + ROW(cGemmNtW4Asym), ROW(tGemmSkinny), r4d_tune_valid_gemm, + nullptr, nullptr, r4d_rad_gemm_w4a16asym_m64, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4, + nullptr, nullptr }, + { "gemm_w8a16_nt_m64", "gemm_nt_q", "gemm", "skinny GEMM with an 8-bit weight, 16x16x16 WMMA, split-K reduced in LDS", "M <= 64; N a multiple of 16; K divisible by SK*128; weight pre-permuted into fragment order, " @@ -5169,6 +5210,16 @@ static const RadKernelInfo kKernels[] = { r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, r4d_rad_givens_quant_act_fp8_describe }, +{ "givens_rotate", "givens_rotate", "quant", + "the channel scale and ParoQuant's Givens rotations, once for each rotated part, to f16", + "n a multiple of 128 and group 128: a rotation group cannot straddle the end of a row", + "bf16 in, f16 out, parts side by side; the tables are the weight's int32 pairs, f32 angles and " + "f32 channel scales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cHadQuantActFp8), NOTUNE, + nullptr, nullptr, r4d_rad_givens_rotate, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, r4d_rad_givens_rotate_describe }, + { "quant_act_i8g", "quant_act_i8g", "quant", "per-(row, 128-column) symmetric int8 quantisation of a bf16 activation", "quant_act_fp8's: n a multiple of 4, group 128, a ragged last group written zero-padded", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 64db78cf..ad46b242 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3740,8 +3740,9 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ * kernel's scale must match it to the rounding of its f32 sincos, and every dequantised element * must sit within the E4M3 grid of the reference (half a step at the top of the range is 1/16 of * the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */ -static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages) { - const char* row = "givens_quant_act_fp8"; +static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, + bool rot_only = false) { + const char* row = rot_only ? "givens_rotate" : "givens_quant_act_fp8"; if (!sel(row)) return; char nm[160]; std::snprintf(nm, sizeof nm, "%s numeric M=%lld K=%lld parts=%d stages=%d", row, (long long)M, @@ -3781,7 +3782,7 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in void* d_p = dalloc(pairs.size() * 4); void* d_a = dalloc(ang.size() * 4); void* d_r = dalloc(rs.size() * 4); - void* d_q = dalloc((size_t)(M * parts * K)); + void* d_q = dalloc((size_t)(M * parts * K) * (rot_only ? 2 : 1)); void* d_s = dalloc((size_t)(M * parts * ng) * 4); if (!d_x || !d_p || !d_a || !d_r || !d_q || !d_s) { ok(nm, false, "hipMalloc failed"); return; } st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice); @@ -3790,9 +3791,11 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in st_memcpy(d_r, rs.data(), rs.size() * 4, hipMemcpyHostToDevice); std::vector ts = { T(d_x, RAD_BF16, { M, K }), T(d_p, RAD_I32, { NPS, K }), T(d_a, RAD_F32, { NPS, K / 2 }), - T(d_r, RAD_F32, { (int64_t)parts, K }), T(d_q, RAD_F8E4M3, { M, parts * K }), + T(d_r, RAD_F32, { (int64_t)parts, K }), + T(d_q, rot_only ? (uint32_t)RAD_F16 : (uint32_t)RAD_F8E4M3, { M, parts * K }), T(d_s, RAD_F32, { M, parts * ng }), }; + if (rot_only) ts.pop_back(); std::vector ps = { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"), PI("stages", stages), PI("parts", parts) }; RadArgs a; @@ -3802,7 +3805,7 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in a.world_size = 1; const int rc = r->launch(&a, (RadStream) nullptr); if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { ok(nm, false, "rc=" + std::to_string(rc)); return; } - std::vector hq((size_t)(M * parts * K)); + std::vector hq((size_t)(M * parts * K) * (rot_only ? 2 : 1)); std::vector hs((size_t)(M * parts * ng)); st_memcpy(hq.data(), d_q, hq.size(), hipMemcpyDeviceToHost); st_memcpy(hs.data(), d_s, hs.size() * 4, hipMemcpyDeviceToHost); @@ -3824,6 +3827,13 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in for (int64_t g = 0; g < ng; ++g) { double amax = 0; for (int k = 0; k < G; ++k) amax = std::max(amax, std::fabs(b[(size_t)(g * G + k)])); + if (rot_only) { // f16: relative 2^-11 of the value, 1e-3 of the group max + for (int k = 0; k < G; ++k) { + const double y = rad_load_f32(hq.data(), RAD_F16, i * parts * K + p * K + g * G + k); + worst_val = std::max(worst_val, std::fabs(y - b[(size_t)(g * G + k)]) / (amax + 1e-30)); + } + continue; + } const double sc = hs[(size_t)(i * parts * ng + p * ng + g)]; worst_scale = std::max(worst_scale, std::fabs(sc - amax / 448.0) / (amax / 448.0 + 1e-30)); for (int k = 0; k < G; ++k) { @@ -3834,7 +3844,115 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in } char d[96]; std::snprintf(d, sizeof d, "scale rel %.2e, value/amax %.3f", worst_scale, worst_val); - ok(nm, worst_scale < 1e-4 && worst_val < 0.07, d); + ok(nm, rot_only ? worst_val < 1e-3 : (worst_scale < 1e-4 && worst_val < 0.07), d); +} + + +/* PARO'S 5-BIT SKINNY GEMM against what the planes mean: u5 codes (a bit stream along K), an f16 scale + * and a zero point 0..31 a 128 of K, an f16 activation, the weight stored through the row's hooks. + * `pb1`/`pb2` give a partitioned weight (the activation copies side by side). M past 64 runs the + * dispatcher's 64-row chunks. */ +static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int64_t pb1 = 0, + int64_t pb2 = 0) { + const char* row = "gemm_w5a16_nt_m64"; + if (!sel(row)) return; + const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; + const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + char nm[160]; + std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, + (long long)N, (long long)K, parts); + const RadKernelInfo* r = find(pl, row); + if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } + const int64_t G = K / 128; + Planes p; + p.enc = rad_enc_affine(RAD_U5, RAD_F16, 1, 128); + rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); + p.size(N, K); + const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); + const int64_t rb = p.row_bytes(ic); + for (int64_t n = 0; n < N; ++n) { + for (int64_t k = 0; k < K; ++k) { + const uint32_t q = st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & 31u; + const int64_t bit = k * 5; + uint8_t* b = p.data[(size_t)ic].data() + n * rb + (bit >> 3); + const uint32_t v = q << (bit & 7); + b[0] |= (uint8_t)(v & 0xFF); + if ((bit & 7) > 3) b[1] |= (uint8_t)(v >> 8); + } + for (int64_t g = 0; g < G; ++g) { + const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); + const float sc = 0.002f * (float)(1 + h % 40); + rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, sc); + p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)(8 + (h >> 8) % 20); + } + } + std::vector lp = { PI("N", N), PI("K", K), PI("group", 128) }; + std::vector wq, ws; + const int rw = stored(r, lp, 2, p, { "codes" }, &wq); + const int rs = stored(r, lp, 3, p, { "scale", "zero" }, &ws); + if (rw != RAD_OK || rs != RAD_OK) { + ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs)); + return; + } + const int64_t PK = parts * K; + std::vector ha((size_t)(M * PK)); + std::vector av((size_t)(M * PK)); + for (int64_t i = 0; i < M; ++i) + for (int64_t k = 0; k < PK; ++k) { + const uint32_t h = st_mix32((uint32_t)(i * 0x10001 + k) ^ 0x3cu); + const float v = (float)((int)(h % 401) - 200) * 0.01f; + rad_store_f32(&ha[(size_t)(i * PK + k)], RAD_F16, 0, v); + av[(size_t)(i * PK + k)] = rad_load_f32(&ha[(size_t)(i * PK + k)], RAD_F16, 0); + } + std::vector hy((size_t)(M * N), 0); + void* d_a = dalloc(ha.size() * 2); + void* d_w = dalloc(wq.size()); + void* d_s = dalloc(ws.size()); + void* d_y = dalloc(hy.size() * 2); + if (!d_a || !d_w || !d_s || !d_y) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_a, ha.data(), ha.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy(d_s, ws.data(), ws.size(), hipMemcpyHostToDevice); + std::vector ts = { + T(d_a, RAD_F16, { M, PK }), T(nullptr, RAD_F32, { 1 }), + T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_s, RAD_U8, { (int64_t)ws.size() }), + T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(nullptr, RAD_F32, { 1 }), + }; + absent(ts[1]); absent(ts[5]); absent(ts[6]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "w5a16") }; + if (pb1) ps.push_back(PI("pb1", pb1)); + if (pb2) ps.push_back(PI("pb2", pb2)); + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + const int rc = r->launch(&a, (RadStream) nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { ok(nm, false, "rc=" + std::to_string(rc)); return; } + st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost); + const int64_t nstep = N > 96 ? N / 96 : 1; + 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 = part_of(n); + double acc = 0; + for (int64_t k = 0; k < K; ++k) { + const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, RAD_U5, k); + const double z = p.data[(size_t)iz][(size_t)(n * G + k / 128)]; + const double sc = rad_load_f32(p.data[(size_t)is].data(), RAD_F16, n * G + k / 128); + acc += (double)av[(size_t)(i * PK + pt * K + k)] * (q - z) * sc; + } + const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc; + num += d * d; + den += acc * acc; + } + const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num); + char d[64]; + std::snprintf(d, sizeof d, "rel_l2 %.3e", rel); + ok(nm, rel < 1e-2, d); } @@ -12777,6 +12895,24 @@ static void device_phase(const Plugin& pl) { moe_w4_rot(pl); } + if (sel("gemm_w5a16_nt_m64")) { + if (!g_case) std::printf("\nParoQuant's 5-bit GEMM, against the planes' meaning\n"); + w5a16_numeric(pl, 8, 272, 640); + w5a16_numeric(pl, 64, 400, 2560); + w5a16_numeric(pl, 5, 400, 640, 144); + w5a16_numeric(pl, 40, 512, 2560, 128, 384); + w5a16_numeric(pl, 300, 400, 640, 192); + w5a16_numeric(pl, 4, 34816, 5120, 17408); + w5a16_numeric(pl, 150, 5120, 17408); + } + + if (sel("givens_rotate")) { + if (!g_case) std::printf("\nParoQuant's rotation to f16, against an f64 rotation\n"); + givens_numeric(pl, 3, 5120, 1, 8, true); + givens_numeric(pl, 5, 5120, 2, 8, true); + givens_numeric(pl, 300, 6144, 2, 8, true); + } + if (sel("givens_quant_act_fp8")) { if (!g_case) std::printf("\nParoQuant's rotate-and-quantise, against an f64 rotation\n"); givens_numeric(pl, 1, 128, 1, 8); From cfe03f8ad876e9dfa97a3361d5b195e40b4e0d87 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 06:50:50 +0000 Subject: [PATCH 09/17] qwen35_fp8: serve rotated 5-bit and 4-bit linears; keep the fp8 gated fold off them --- arch/common/rad_block_mlp_fp8.h | 4 +- arch/common/rad_fp8.h | 195 ++++++++++++++++++++++++-------- 2 files changed, 150 insertions(+), 49 deletions(-) diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index d0831af8..bca3fd5c 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -123,10 +123,10 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co /* The fold, over the same weights and into the same activation the pair writes. Not * RAD_ARCH_TRY: a plugin without the row is the ordinary case and the pair still runs. It * multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold -- and neither - * has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it. */ + * has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it (a rotated 5-bit one neither). */ { const int64_t hi = g.max_tok < 64 ? g.max_tok : 64; - if (hi > 0 && !gate_up.bf16 && !gate_up.mx) { + if (hi > 0 && !gate_up.bf16 && !gate_up.mx && !gate_up.paro5) { op_gated = rw(b, RAD_OP(b, "gemm_nt_q_gated", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", gate_up.N), RAD_INT("K", gate_up.K), diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 5f1ef819..e99c8e3f 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -698,6 +698,9 @@ struct LinearFP8 { * scale planes, `parts` copies side by side. The tables are views of the weight's own planes. * The GEMM takes the parts' row bounds as `pb1`/`pb2` and meets copy p with part p's rows. */ bool paro = false, probed_paro = false; + /* ...AND ITS 5-BIT SIBLING: the same rotation, to f16 (`rot_q` is then the f16 plane and there is no + * `rot_s`), then gemm_nt_q at w5a16 over a weight of u5 codes, an f16 scale and a zero point. */ + bool paro5 = false; rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0; rad_buf rot_q = 0, rot_s = 0; rad_op op_rot = 0; @@ -750,6 +753,14 @@ struct LinearFP8 { std::initializer_list row_parts = {}, int64_t span_lo = 0, int64_t span_hi = 0, std::initializer_list rot_part_rows = {}); + /* THE ROTATION OF A ROTATED WEIGHT, declared: its tables as views of the weight's own planes, its + * code planes (`givens_quant_act_fp8`: E4M3 and a scale) or, with `f16`, its single f16 plane + * (`givens_rotate`, for a GEMM that reads a 16-bit activation), and the op in front of the + * GEMM. `cut` is the rows of each rotated part; *pb1/*pb2 come back as the GEMM's part bounds. */ + int declare_rotation(RadBuilder* b, Names& nm, const Geom& g, const char* base, const char* wn, + const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp, + const ActFP8& a, int64_t max_rows, const std::vector& cut, + bool f16, int64_t* pb1, int64_t* pb2); void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; /* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale @@ -828,6 +839,17 @@ inline bool linear_is_paro_mxfp4(const RadEncoding& e) { pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32; } +/* ParoQuant's int5 (u5 codes) and z-lab's own int4 (u4 codes): u5 codes, an f16 scale and a u8 zero point a 128 of K (asymmetric), in the rotated + * basis, with the same rotation tables. Read by gemm_nt_q at dtype w5a16 over an f16 activation. */ +inline bool linear_is_paro_w5(const RadEncoding& e) { + if (!rad_enc_is(&e, "affine") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false; + if (!rad_enc_valid(&e) || e.n_planes < 6) return false; + const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero"); + return (e.plane[0].dtype == RAD_U5 || e.plane[0].dtype == RAD_U4) && sc && zp && sc->dtype == RAD_F16 && sc->block[0] == 1 && + sc->block[1] == RAD_FP8_BLOCK && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK && + rad_enc_find(&e, "t.pairs") > 0; +} + inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base, std::initializer_list src) { if (src.size() == 0) return RAD_E_INVAL; @@ -840,11 +862,76 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* enc.plane[0].dtype == RAD_BF16; probed_i8 = known && linear_is_w8(enc); /* A ROTATED weight rotates the bf16 plane itself: its quantiser is not the producer's. */ - probed_paro = known && linear_is_paro_mxfp4(enc); + probed_paro = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc)); reads_x = g.w_bf16 || plain || probed_i8 || probed_paro; return RAD_OK; } +inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const Geom& g, const char* base, + const char* wn, const RadEncoding& enc, int64_t N, int64_t K, + RadWeightGroup grp, const ActFP8& a, int64_t max_rows, + const std::vector& cut_in, bool f16, int64_t* pb1, + int64_t* pb2) { + /* THE PARTS, in rows, and the tables as weights of their own. The container records how many + * parts there are and not where they end -- a declaration has no plane bytes -- so the block + * says: `rot_part_rows`, or its row parts when those are the cut. */ + const int64_t P = rad_enc_givens_parts(&enc); + const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs"); + if (P < 1 || !tp || tp->extent[0] % P || tp->extent[1] != K) { + fprintf(stderr, "radiance: '%s' has rotation tables that do not fit %lld columns\n", + wn, (long long)K); + return RAD_E_SHAPE; + } + const int64_t S = tp->extent[0] / P; + std::vector cut = cut_in; + if (cut.empty() && P == 1) cut.push_back(N); + int64_t sum = 0; + for (int64_t p : cut) sum += p; + if ((int64_t)cut.size() != P || sum != N || P > 3) { + fprintf(stderr, "radiance: '%s' was rotated as %lld part(s) and is declared as %zu " + "rotated part(s) of %lld rows; the GEMM meets up to three copies " + "of the activation\n", wn, (long long)P, cut.size(), (long long)sum); + return RAD_E_SHAPE; + } + for (int64_t i = 0; i + 1 < P; ++i) if (cut[(size_t)i] % 128) { + fprintf(stderr, "radiance: '%s' rotation part of %lld rows is not whole 128s\n", + wn, (long long)cut[(size_t)i]); + return RAD_E_SHAPE; + } + rot_parts = P; + *pb1 = P > 1 ? cut[0] : 0; + *pb2 = P > 2 ? cut[0] + cut[1] : 0; + rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, + { P * S, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + rot_angle = decl_view(b, nm.f("%s.rot_angle", base), wn, "t.angle", RAD_F32, + { P * S, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + rot_scale = decl_view(b, nm.f("%s.rot_scale", base), wn, "t.scale", RAD_F32, + { P, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + if (!rot_pairs || !rot_angle || !rot_scale) return RAD_E_INVAL; + const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; + if (f16) { + rot_q = decl_b(b, nm.f("%s.rot_y", base), RAD_F16, { rows, P * K }); + if (!rot_q) return RAD_E_INVAL; + op_rot = rw(b, RAD_OP(b, "givens_rotate", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), + RAD_INT("stages", S), RAD_INT("parts", P)), + RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), + { a.x }, { rot_q }); + return op_rot ? RAD_OK : RAD_E_INVAL; + } + rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, P * K }); + rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, P * (K / RAD_FP8_BLOCK) }); + if (!rot_q || !rot_s) return RAD_E_INVAL; + op_rot = rw(b, RAD_OP(b, "givens_quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), + RAD_INT("stages", S), RAD_INT("parts", P)), + RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), + { a.x }, { rot_q, rot_s }); + return op_rot ? RAD_OK : RAD_E_INVAL; +} + inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, std::initializer_list src, @@ -963,6 +1050,57 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL; } + /* ---- A ROTATED 5-BIT (or plain asymmetric 4-bit) WEIGHT (ParoQuant int5; z-lab's int4): its input's bf16 plane rotated into this linear's + * own f16 planes, then the w5a16 GEMM. Two views of one stored weight: the codes, and the + * (scale, zero) pair as `b_scale`. */ + paro5 = known && linear_is_paro_w5(enc); + if (paro5) { + if (!a.x) { + fprintf(stderr, "radiance: '%s' is a rotated 5-bit weight, rotated 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 5-bit weight; its rotation is not cut by a " + "tensor-parallel shard (world %d)\n", wn, g.world); + return RAD_E_UNSUPPORTED; + } + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld; a 5-bit weight takes rows in 16s and K in " + "whole 128s\n", base, (long long)N, (long long)K); + return RAD_E_INVAL; + } + std::vector 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); + int64_t pb1 = 0, pb2 = 0; + RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, max_rows, cut, true, + &pb1, &pb2)); + const bool bits5 = enc.plane[0].dtype == RAD_U5; + w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN, + shard, grp); + ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, + RAD_ACCESS_PER_TOKEN, shard, grp); + if (!w || !ws) return RAD_E_INVAL; + const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; + op = rot_parts > 1 + ? rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", bits5 ? "w5a16" : "w4a16_asym"), + RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), + RAD_WEIGHTS(w, ws)), + { rot_q }, { y }) + : rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", bits5 ? "w5a16" : "w4a16_asym")), + RAD_WEIGHTS(w, ws)), + { rot_q }, { y }); + paro = false; + return op ? RAD_OK : RAD_E_INVAL; + } + /* An E4M3 weight reads the E4M3 pair, and an input the model feeds at int8 codes has none -- * a container whose trunk mixes the two formats, which the model's one probe did not see. */ if (a.q8_fed) { @@ -1017,55 +1155,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha } int64_t pb1 = 0, pb2 = 0; if (paro) { - /* THE PARTS, in rows, and the tables as weights of their own. The container records - * how many parts there are and not where they end -- a declaration has no plane bytes - * -- so the block says: `rot_part_rows`, or its row parts when those are the cut. */ - const int64_t P = rad_enc_givens_parts(&enc); - const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs"); - if (P < 1 || !tp || tp->extent[0] % P || tp->extent[1] != K) { - fprintf(stderr, "radiance: '%s' has rotation tables that do not fit %lld columns\n", - wn, (long long)K); - return RAD_E_SHAPE; - } - const int64_t S = tp->extent[0] / P; std::vector 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); - if (cut.empty() && P == 1) cut.push_back(N); - int64_t sum = 0; - for (int64_t p : cut) sum += p; - if ((int64_t)cut.size() != P || sum != N || P > 3) { - fprintf(stderr, "radiance: '%s' was rotated as %lld part(s) and is declared as %zu " - "rotated part(s) of %lld rows; the GEMM meets up to three copies " - "of the activation\n", wn, (long long)P, cut.size(), (long long)sum); - return RAD_E_SHAPE; - } - for (int64_t i = 0; i + 1 < P; ++i) if (cut[(size_t)i] % 128) { - fprintf(stderr, "radiance: '%s' rotation part of %lld rows is not whole 128s\n", - wn, (long long)cut[(size_t)i]); - return RAD_E_SHAPE; - } - rot_parts = P; - pb1 = P > 1 ? cut[0] : 0; - pb2 = P > 2 ? cut[0] + cut[1] : 0; - rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, - { P * S, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - rot_angle = decl_view(b, nm.f("%s.rot_angle", base), wn, "t.angle", RAD_F32, - { P * S, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - rot_scale = decl_view(b, nm.f("%s.rot_scale", base), wn, "t.scale", RAD_F32, - { P, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - if (!rot_pairs || !rot_angle || !rot_scale) return RAD_E_INVAL; - 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, P * K }); - rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, P * (K / RAD_FP8_BLOCK) }); - if (!rot_q || !rot_s) return RAD_E_INVAL; - op_rot = rw(b, RAD_OP(b, "givens_quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), - RAD_INT("stages", S), RAD_INT("parts", P)), - RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), - { a.x }, { rot_q, rot_s }); - if (!op_rot) return RAD_E_INVAL; + RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, max_rows, cut, + false, &pb1, &pb2)); } const char* sn = nm.f("%s.scale", base); const char* rn = nm.f("%s.ref", base); @@ -1201,6 +1295,13 @@ 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, r0, rows, N), RAD_NONE, RAD_NONE); return; } + if (paro5) { + RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), + RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K)); + RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), RAD_NONE, + RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + return; + } if (mx) { /* A rotated weight rotates its input first, into its own codes, `rot_parts` copies side * by side (one for a plain weight, which reads the producer's). */ From 60910399268bcf3f2bf6f59703ad7c33318f3b5a Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 13:21:38 +0000 Subject: [PATCH 10/17] libr4d: int8 prefill band for ParoQuant int4/int5 (gemm_w4a8i8/w5a8i8 tiled, givens_quant_act_i8g); LinearFP8 uses it above 64 rows --- arch/common/rad_fp8.h | 71 +++++-- core/format/checkpoint.cpp | 7 +- core/format/checkpoint.h | 3 +- docs/OPS.md | 1 + libr4d/CMakeLists.txt | 1 + libr4d/r4d_gemm_wpa8i8_tiled.hip | 280 ++++++++++++++++++++++++++++ libr4d/r4d_givens_quant_act_fp8.hip | 64 ++++--- libr4d/r4d_layout.cpp | 7 +- libr4d/r4d_plugin.h | 4 + libr4d/r4d_rows.cpp | 49 ++++- libr4d/r4d_selftest.cpp | 259 ++++++++++++++++++++++++- libref/ref_ops.h | 2 + libref/ref_quant.cpp | 11 +- libref/ref_registry.cpp | 8 + libref/ref_shapes.cpp | 4 + tests/ref_test.cpp | 2 +- 16 files changed, 709 insertions(+), 64 deletions(-) create mode 100644 libr4d/r4d_gemm_wpa8i8_tiled.hip diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index e99c8e3f..51ee97e6 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -697,10 +697,18 @@ struct LinearFP8 { * (gate|up, qkv|z: each piece was rotated on its own) -- into this linear's own code and * scale planes, `parts` copies side by side. The tables are views of the weight's own planes. * The GEMM takes the parts' row bounds as `pb1`/`pb2` and meets copy p with part p's rows. */ - bool paro = false, probed_paro = false; + bool paro = false; /* ...AND ITS 5-BIT SIBLING: the same rotation, to f16 (`rot_q` is then the f16 plane and there is no * `rot_s`), then gemm_nt_q at w5a16 over a weight of u5 codes, an f16 scale and a zero point. */ bool paro5 = false; + /* ...AND ITS PREFILL BAND (z-lab's int4 and the int5): above `rot_split` rows the f16 skinny kernel is + * bound by the slow f16 matrix instruction, so a second chain runs there -- the same rotation to + * int8 with a scale a (row, 128) into `rot_q2`/`rot_s2`, then the int8 tiled GEMM + * (`w4a8i8_asym` / `w5a8i8`), both reading the SAME weight views. At or below the split the f16 chain + * above runs. */ + int64_t rot_split = 0; + rad_buf rot_q2 = 0, rot_s2 = 0; + rad_op op_rot2 = 0, op2 = 0; rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0; rad_buf rot_q = 0, rot_s = 0; rad_op op_rot = 0; @@ -743,7 +751,7 @@ struct LinearFP8 { /* `span_lo`/`span_hi`, when hi is set, is this rank's uneven slice of the split dimension in * the model's units -- rows of each row part for RAD_SHARD_ROW, columns for RAD_SHARD_COL -- * and n_out / n_in is already its width; see rad_weight_shard_span. Whole scale blocks. */ - /* `rot_parts`: the rows of each independently rotated part of a ROTATED weight (probed_paro), + /* `rot_parts`: the rows of each independently rotated part of a ROTATED weight, * which `row_parts` is when the pieces and the shard parts are the same cut -- gate|up -- and * is not when they are not: the delta net's qkv|z is four shard parts and two rotated ones. */ int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, @@ -862,8 +870,8 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* enc.plane[0].dtype == RAD_BF16; probed_i8 = known && linear_is_w8(enc); /* A ROTATED weight rotates the bf16 plane itself: its quantiser is not the producer's. */ - probed_paro = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc)); - reads_x = g.w_bf16 || plain || probed_i8 || probed_paro; + const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc)); + reads_x = g.w_bf16 || plain || probed_i8 || rotated; return RAD_OK; } @@ -1074,31 +1082,63 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha for (int64_t p : rot_part_rows) cut.push_back(p); if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p); int64_t pb1 = 0, pb2 = 0; - RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, max_rows, cut, true, - &pb1, &pb2)); + const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; const bool bits5 = enc.plane[0].dtype == RAD_U5; + const int64_t kSplit = 64; /* the skinny kernel's M ceiling */ + const bool band = hi > kSplit; + RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, + band ? kSplit : max_rows, cut, true, &pb1, &pb2)); w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); if (!w || !ws) return RAD_E_INVAL; - const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; op = rot_parts > 1 ? rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_PARAMS(RAD_RANGE("M", 1, band ? kSplit : hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a16" : "w4a16_asym"), RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), RAD_WEIGHTS(w, ws)), { rot_q }, { y }) : rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_PARAMS(RAD_RANGE("M", 1, band ? kSplit : hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a16" : "w4a16_asym")), RAD_WEIGHTS(w, ws)), { rot_q }, { y }); - paro = false; - return op ? RAD_OK : RAD_E_INVAL; + if (!op) return RAD_E_INVAL; + if (band) { + /* THE PREFILL BAND: rows above the skinny kernel's ceiling rotate to int8 and meet the int8 + * tiled GEMM. Declared over the tables and weight views already made above. */ + const int64_t P = rot_parts; + rot_split = kSplit; + rot_q2 = decl_b(b, nm.f("%s.rot_q2", base), RAD_I8, { hi, P * K }); + rot_s2 = decl_b(b, nm.f("%s.rot_s2", base), RAD_F32, { hi, P * (K / RAD_FP8_BLOCK) }); + if (!rot_q2 || !rot_s2) return RAD_E_INVAL; + const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs"); + const int64_t S = tp->extent[0] / P; + op_rot2 = rw(b, RAD_OP(b, "givens_quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), + RAD_INT("stages", S), RAD_INT("parts", P)), + RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), + { a.x }, { rot_q2, rot_s2 }); + op2 = rot_parts > 1 + ? rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a8i8" : "w4a8i8_asym"), + RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), + RAD_WEIGHTS(w, ws)), + { rot_q2, rot_s2 }, { y }) + : rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a8i8" : "w4a8i8_asym")), + RAD_WEIGHTS(w, ws)), + { rot_q2, rot_s2 }, { y }); + if (!op_rot2 || !op2) return RAD_E_INVAL; + } + return RAD_OK; } /* An E4M3 weight reads the E4M3 pair, and an input the model feeds at int8 codes has none -- @@ -1295,6 +1335,15 @@ 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, r0, rows, N), RAD_NONE, RAD_NONE); return; } + if (paro5 && rot_split && rows > rot_split) { + RAD_ISSUE_N(c, op_rot2, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), + RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q2, r0, rows, rot_parts * K), + brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK))); + RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K), + brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)), + RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + return; + } if (paro5) { RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K)); diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 55d0c061..3f414b92 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -621,7 +621,6 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, c.name = name; c.rad_dtype = i5 ? RAD_U5 : RAD_U4; c.shape = { N, K }; - c.int5 = true; c.pbits = i5 ? 5 : 4; c.aux[0] = hi; c.aux[1] = qz; c.aux[2] = qzh; sliced_.push_back(std::move(c)); @@ -1047,11 +1046,11 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b (gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor"; } else if (!same) { out->why = "its pieces are stored in different dtypes"; - } else if (p0.int5) { + } else if (p0.pbits) { /* PARO int5-bitplane: u5 codes, an f16 scale and a u8 zero point a 128 of K, then the * rotation tables. Joined only along rows (gate|up), as every imported form is. */ bool fits = d == 0 || out->pieces.size() == 1; - for (const SrcTensor* pk : out->pieces) fits = fits && pk->int5 && pk->pbits == p0.pbits; + for (const SrcTensor* pk : out->pieces) fits = fits && pk->pbits == p0.pbits; if (!fits) { out->why = "its int5 pieces are joined along a column, across their groups"; } else { @@ -1389,7 +1388,7 @@ 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.paro && w.pieces[0]->int5 && k <= 2) { + if (w.paro && w.pieces[0]->pbits && k <= 2) { /* PARO int5-bitplane, RE-LAID a row of the logical [N, K] matrix at a time. The checkpoint * packs along N: qweight [K, N/8] holds eight low nibbles per word in AWQ order (word * column c of a group of eight sits in nibble j, ORDER[j] == c), and qweight_hi [K, N/32] diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index ee522ca0..f2eb8cd7 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -60,8 +60,7 @@ struct SrcTensor { * [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit * plane qweight_hi [K, N/32], and the zero points qzeros [G, N/8] and qzeros_hi [G, N/32]. * z-lab's int4 (Import::ParoI4) is the same without the fifth-bit planes (aux[0], aux[2] null). */ - bool int5 = false; - int pbits = 0; /* 5 for int5-bitplane, 4 for z-lab's plain AWQ-packed int4 */ + int pbits = 0; /* 5 for int5-bitplane, 4 for z-lab's plain AWQ-packed int4; 0 otherwise */ const SrcTensor* aux[3] = { nullptr, nullptr, nullptr }; int64_t numel() const { diff --git a/docs/OPS.md b/docs/OPS.md index 8fd23617..4c7ce457 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -363,6 +363,7 @@ spelling of `act`, not the vocabulary's. | `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `givens_quant_act_fp8` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | +| `givens_quant_act_i8g` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | | `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` | | `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index ff6a9ced..c901984c 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -108,6 +108,7 @@ set(R4D_UNITS "r4d_gemm_bf16_nt_tiled|" "r4d_gemm_w4a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w5a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" + "r4d_gemm_wpa8i8_tiled|" "r4d_gemm_w8a16_nt_m64|-DR4D_GEMM_W8_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w2a8_nt|-DR4D_GEMM_W2A8_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w4a8_nt_m64|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}" diff --git a/libr4d/r4d_gemm_wpa8i8_tiled.hip b/libr4d/r4d_gemm_wpa8i8_tiled.hip new file mode 100644 index 00000000..731ca882 --- /dev/null +++ b/libr4d/r4d_gemm_wpa8i8_tiled.hip @@ -0,0 +1,280 @@ +// r4d_gemm_wpa8i8_tiled.hip - r4d_gemm_w4a8i8_tiled / r4d_gemm_w5a8i8_tiled: the 4- and 5-bit ASYMMETRIC +// weight x int8 activation GEMM for PREFILL row counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with +// +// dequant(Wq)[n][k] = scale[n][k/128] * (code[n][k] - zero[n][k/128]), code in 0..15 or 0..31 +// +// -- ParoQuant's int4 (z-lab) and int5 once the activation has been rotated (givens_quant_act_i8g) -- in +// 16x16x16 int8 WMMA, which issues at the fp8 instruction's rate. The f16 skinny kernel these weights +// also serve (r4d_gemm_w5a16_nt_m64) is capped by the f16 matrix instruction at about 75 TF/s; this is the +// tall-tile form with no such ceiling, built on r4d_gemm_mxfp4a8_tiled.hip's arrangement: +// +// * a 256 x 64 tile (4 x 2 waves, 4 x 2 fragments each); the activation is re-tiled by +// r4d_mxfp4a8_tile_a into fragment order (one 16 x 16 fragment = 256 bytes) in the op's scratch and +// read straight into registers; the weight slab is staged through LDS; +// * a slab is one scale group (128 of K = 8 WMMA steps): the int32 accumulators start at zero each slab and +// are folded into the running float total as slab * (a_scale[row][g] * w_scale[col][g]), because the +// weight's f16 scale varies by column and so cannot ride inside the matrix instruction; +// * a partitioned weight (pb1/pb2) is one launch per part over windows of the planes. +// +// WHY INT8 AND NOT FP8. (code - zero) is -15..15 (int4) or -31..31 (int5); both are exact in an int8, +// so the weight needs no conversion at all -- the staging is a byte-wise subtract -- whereas e4m3's three +// mantissa bits stop at 16 and int5 would need two matrix issues a step. The activation is quantised to +// int8 with one scale a (row, 128 of K): after the rotation a group is flat, so 127 uniform levels of its +// maximum are finer than e4m3's relative 2^-4 for nearly every element (measured: ppl equal to the f16 +// path's, slightly better than the fp8 band's). The accumulators are int32 and exact: a slab is 128 +// products of at most 31 * 127. +// +// STAGING. A code byte c (0..31) minus the zero z (0..31): (c | 0x80) - z is 128 + (c - z), never below +// 97 and never carrying into the next byte, and XOR 0x80 turns it into the two's complement byte of +// (c - z). Three ALU ops a dword of four weights. +// +// THE WEIGHT BLOB is r4d_gemm_w5a16_nt_m64's (BITS 5): the nibble plane (w4's fragment order), then the +// fifth bits, one dword a (n-tile, 64 of K, lane): byte s = k step s of the block, bit e = element e. For +// BITS 4 it is the nibble plane alone. The scale operand is the f16 kernel's dword plane +// [N/16][K/128][16]: the f16 scale in the low half, -(1024 + zero) in the high. +#include "r4d.h" +#include "r4d_gemm_args.h" +#include "r4d_common.h" + +#include +#include +#include +#include +#include + +#define R4D_WPT_TM 4 // 16-row fragments per wave +#define R4D_WPT_TN 2 // 16-column fragments per wave +#define R4D_WPT_WM 4 // waves along M +#define R4D_WPT_WN 2 // waves along N +#define R4D_WPT_PAD 8 // LDS row pad: 16 lanes reading rows 136 B apart +#define R4D_WPT_NTHR (R4D_WPT_WM * R4D_WPT_WN * 32) +#define R4D_WPT_BMF (R4D_WPT_WM * R4D_WPT_TM * 16) +#define R4D_WPT_LBK 128 // one scale group a slab + +typedef int wpt_v2i __attribute__((ext_vector_type(2))); +typedef int wpt_v8i __attribute__((ext_vector_type(8))); +typedef unsigned wpt_u4 __attribute__((ext_vector_type(4))); + +// 4 bits -> bit 4 of each byte: the fifth bits of four elements, in the position above their nibbles +static __device__ __forceinline__ unsigned wpt_spread16(unsigned n) { + return ((n * 0x00204081u) & 0x01010101u) << 4; +} + +// four code bytes (0..31) and the zero point in every byte -> the four bytes of (code - zero), signed +static __device__ __forceinline__ unsigned wpt_sub_zero(unsigned codes4, unsigned zz) { + return ((codes4 | 0x80808080u) - zz) ^ 0x80808080u; +} + +template +__global__ __launch_bounds__(R4D_WPT_NTHR) void r4d_gemm_wpa8i8_tiled_kernel( + const unsigned char* __restrict__ AT, const float* __restrict__ As, + const unsigned* __restrict__ Wq, const unsigned* __restrict__ Whi, const unsigned* __restrict__ Wsz, + __hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs, int ldc) { + constexpr int TM = R4D_WPT_TM, TN = R4D_WPT_TN, WN = R4D_WPT_WN, NTHR = R4D_WPT_NTHR, BMF = R4D_WPT_BMF; + constexpr int LBK = R4D_WPT_LBK, NS = LBK / 16, STR = LBK + R4D_WPT_PAD, BNF = WN * TN * 16; + constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32; + // A thread stages one lane's 16 bytes of a 64-wide k block -- four k steps of one weight row, which + // is how the fragment-order plane is laid out (dword (t, kb, lane, s)) -- so a slab of two blocks + // over the block's tiles is TOT_SLOTS / 4 reads. + constexpr int NW = TOT_SLOTS / 4 / NTHR; + static_assert(NW * NTHR * 4 == TOT_SLOTS, "the W tile must split evenly over the block"); + __shared__ unsigned char sW[BNF * STR]; + + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int wm = wave / WN, wn = wave % WN; + const int col = lane & 15, kb8 = (lane >> 4) * 8; + const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF; + const int ksteps = K / 16, kpb = K / 64, Mt = (M + 15) >> 4, nsz = K / 128; + const int ntile_last = N / 16 - 1; + + const unsigned char* abase[TM]; +#pragma unroll + for (int i = 0; i < TM; ++i) { + int mt = (m0 >> 4) + wm * TM + i; + mt = mt < Mt - 1 ? mt : Mt - 1; + abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256); + } + const unsigned int aoff = (unsigned int)lane * 8; + + // The activation scales this lane folds with: one per M fragment, at the row its accumulators hold. + const float* __restrict__ arow[TM]; +#pragma unroll + for (int i = 0; i < TM; ++i) { + int m = m0 + wm * TM * 16 + i * 16 + col; + m = m < M ? m : M - 1; + arow[i] = As + (size_t)m * as_rs; + } + + // The W reads this thread makes, fixed across slabs: lane `wl` of n-tile `wt` (clamped to the last + // real tile), 64-wide k block `wkb` of the slab, staged to the LDS row `wrow` at half `whalf`. + int wrow[NW], wkb[NW], whalf[NW], wt[NW], wlane[NW]; +#pragma unroll + for (int it = 0; it < NW; ++it) { + const int idx = it * NTHR + tid; + wlane[it] = idx & 31; + wkb[it] = (idx >> 5) & 1; + const int ntl = (idx >> 5) >> 1; + wrow[it] = ntl * 16 + (wlane[it] & 15); + whalf[it] = wlane[it] >> 4; + const int t = (n0 >> 4) + ntl; + wt[it] = t < ntile_last ? t : ntile_last; + } + + float tot[TM][TN][8]; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) tot[i][j][e] = 0.f; + + for (int k0 = 0, g = 0; k0 < K; k0 += LBK, ++g) { + // A fragments for the slab, one clause, consumed only at the WMMAs. + wpt_v2i af[TM][NS]; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int st = 0; st < NS; ++st) + af[i][st] = *(const wpt_v2i*)(abase[i] + + (aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256))); + // The scales of this slab, issued ahead of the staging that hides their latency. + float sa[TM]; +#pragma unroll + for (int i = 0; i < TM; ++i) sa[i] = arow[i][g]; + float ws[TN][8]; +#pragma unroll + for (int j = 0; j < TN; ++j) { + int t = (n0 + wn * TN * 16 + j * 16) >> 4; + t = t < ntile_last ? t : ntile_last; + const wpt_u4* p = (const wpt_u4*)(Wsz + ((size_t)t * nsz + g) * 16 + kb8); + const wpt_u4 v0 = p[0], v1 = p[1]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + ws[j][e] = __half2float(__ushort_as_half((unsigned short)(v0[e] & 0xFFFFu))); + ws[j][4 + e] = __half2float(__ushort_as_half((unsigned short)(v1[e] & 0xFFFFu))); + } + } + // W slab -> LDS as int8 (code - zero), by true k. A dword's element e is nibble 2e (e < 4) or + // 2(e-4)+1, and k = 8*(e>>2) + 4*(lane>>4) + (e&3): a lane writes its elements 0..3 at + // k = 4*(lane>>4) and 4..7 at +8, and the WMMA reads eight consecutive bytes. +#pragma unroll + for (int it = 0; it < NW; ++it) { + const size_t blk = (size_t)wt[it] * kpb + k0 / 64 + wkb[it]; + const wpt_u4 wv = *(const wpt_u4*)&Wq[blk * 128 + wlane[it] * 4]; + unsigned hb4 = 0; + if constexpr (BITS == 5) hb4 = Whi[blk * 32 + wlane[it]]; // byte s: the fifth bits of k step s + const unsigned sz = Wsz[((size_t)wt[it] * nsz + g) * 16 + (wlane[it] & 15)]; + const unsigned zz = ((sz >> 16) & 0x1Fu) * 0x01010101u; // high half is -(1024 + zero) in f16 +#pragma unroll + for (int s_ = 0; s_ < 4; ++s_) { + const unsigned w = wv[s_]; + unsigned cl = w & 0x0F0F0F0Fu, ch = (w >> 4) & 0x0F0F0F0Fu; // elements 0..3, 4..7 + if constexpr (BITS == 5) { + const unsigned hb = (hb4 >> (8 * s_)) & 0xFFu; + cl |= wpt_spread16(hb & 15u); + ch |= wpt_spread16(hb >> 4); + } + unsigned char* d = &sW[wrow[it] * STR + (wkb[it] * 4 + s_) * 16 + whalf[it] * 4]; + *(unsigned*)d = wpt_sub_zero(cl, zz); + *(unsigned*)(d + 8) = wpt_sub_zero(ch, zz); + } + } + lds_barrier(); + + wpt_v8i gacc[TM][TN]; +#pragma unroll + for (int step = 0; step < NS; ++step) { + const int kk = step * 16 + kb8; + wpt_v2i wf[TN]; +#pragma unroll + for (int j = 0; j < TN; ++j) { + const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk]; + wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4); + } + __builtin_amdgcn_sched_barrier(0); +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) + gacc[i][j] = step == 0 + ? __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, wf[j], true, af[i][step], (wpt_v8i)(0), false) + : __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, wf[j], true, af[i][step], gacc[i][j], false); + } +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) tot[i][j][e] = fmaf((float)gacc[i][j][e], sa[i] * ws[j][e], tot[i][j][e]); + lds_barrier(); + } + +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int nb = n0 + wn * TN * 16 + j * 16 + kb8; + if (nb >= N) continue; +#pragma unroll + for (int i = 0; i < TM; ++i) { + const int m = m0 + wm * TM * 16 + i * 16 + col; + if (m >= M) continue; + union { __hip_bfloat16 h[8]; wpt_u4 v; } o; +#pragma unroll + for (int e = 0; e < 8; ++e) o.h[e] = (__hip_bfloat16)tot[i][j][e]; + *(wpt_u4*)(C + (size_t)m * ldc + nb) = o.v; + } + } +} + +template +static void wpa8i8_launch(long at, long ascale, long wq, long whi, long wsz, long c, int M, int K, int N, + int as_rs, long stream, int ldc) { + if (M < 1) throw std::runtime_error("r4d gemm_wpa8i8_tiled: M must be >= 1"); + if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_wpa8i8_tiled: N must be a multiple of 16"); + if (K % R4D_WPT_LBK) throw std::runtime_error("r4d gemm_wpa8i8_tiled: K must be a multiple of 128"); + const int bnf = R4D_WPT_WN * R4D_WPT_TN * 16; + dim3 grid((N + bnf - 1) / bnf, (M + R4D_WPT_BMF - 1) / R4D_WPT_BMF), block(R4D_WPT_NTHR); + hipLaunchKernelGGL((r4d_gemm_wpa8i8_tiled_kernel), grid, block, 0, (hipStream_t)stream, + (const unsigned char*)at, (const float*)ascale, (const unsigned*)wq, + (const unsigned*)whi, (const unsigned*)wsz, (__hip_bfloat16*)c, M, K, N, as_rs, ldc); +} + +// ============================================================== the plugin ABI entry points +// The row-major int8 activation is re-tiled into the op's scratch (one slab a part), then the GEMM +// reads it from there -- mxfp4a8_tiled's arrangement exactly, including a partitioned weight as +// one launch per part over windows of the planes. +template +static int wpa8i8_dispatch(const RadArgs* a, RadStream s) { + GemmOps g; + int rc = gemm_ops(a, &g, 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); + MxParts mp; + rc = mx_parts(a, &g, &mp); + if (rc != RAD_OK) return rc; + if (g.K % R4D_WPT_LBK) return R4D_NO(RAD_E_SHAPE); + int as_group = 0, as_rs = 1; + rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n); + if (rc != RAD_OK) return rc; + if (as_group != 128) return R4D_NO(RAD_E_SHAPE); // one scale a (row, 128): the slab + const long long slab = r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K); + if (!a->scratch || a->scratch_bytes < slab * mp.n) return R4D_NO(RAD_E_INVAL); + const long long kb = g.K / 128; + for (int p = 0; p < mp.n; ++p) { + const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p]; + const long at = (long)(uintptr_t)a->scratch + (long)(p * slab); + R4D_TRY("gemm_wpa8i8_tiled", + r4d_mxfp4a8_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)); + wpa8i8_launch(at, r4d_addr(g.ascale) + p * kb * 4, + r4d_addr(g.b) + n0 * g.K / 2, + BITS == 5 ? r4d_addr(g.b) + g.N * g.K / 2 + n0 * g.K / 8 : 0L, + r4d_addr(g.bscale) + (n0 / 16) * kb * 16 * 4, + r4d_addr(g.y) + n0 * 2, (int)g.M, (int)g.K, (int)np, as_rs, + (long)(uintptr_t)s, (int)g.N)); + } + return RAD_OK; +} + +extern "C" int r4d_rad_gemm_w4a8i8_tiled(const RadArgs* a, RadStream s) { return wpa8i8_dispatch<4>(a, s); } +extern "C" int r4d_rad_gemm_w5a8i8_tiled(const RadArgs* a, RadStream s) { return wpa8i8_dispatch<5>(a, s); } diff --git a/libr4d/r4d_givens_quant_act_fp8.hip b/libr4d/r4d_givens_quant_act_fp8.hip index b5bed570..58208f4c 100644 --- a/libr4d/r4d_givens_quant_act_fp8.hip +++ b/libr4d/r4d_givens_quant_act_fp8.hip @@ -26,12 +26,17 @@ // quantiser's rounding to E4M3 then swallows nearly all of the difference, and rad-kbench-style // comparisons against the reference allow one code of disagreement per element. // +// givens_quant_act_i8g is the same producer with an int8 output (scale amax / 127, round to nearest) for +// the int8 prefill GEMMs: after the rotation a group is flat, and 127 uniform levels beat e4m3's three +// mantissa bits for nearly every element. +// // Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" #include "r4d_emit.h" #include "r4d_fp8_args.h" #include "r4d_fp8_wmma.h" +#include "r4d_q8.h" #include namespace { @@ -58,14 +63,18 @@ __device__ __forceinline__ void wave_sync() { // spreads a row's `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is // several blocks and a decode step of a few rows still fills the part. A wave that has no group // returns at once; nothing in the kernel is a block barrier. -// QUANT false is givens_rotate: the same rotation, no quantiser, the rotated row written as f16 into +// Rotate is givens_rotate: the same rotation, no quantiser, the rotated row written as f16 into // `q` (read as a uint16 plane, y_ld elements a row) for a GEMM that reads a 16-bit activation. -template +// Fp8 and I8 are the two quantisers (r4d_q8.h: E4M3 with scale amax/448, int8 with amax/127). +enum class GvMode { Rotate, Fp8, I8 }; + +template __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs, const float* __restrict__ angle, const float* __restrict__ rscale, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) { + constexpr bool I8 = MODE == GvMode::I8; __shared__ float sbuf[kWaves][kGroup]; const uint32_t row = blockIdx.x; const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; @@ -126,7 +135,7 @@ __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( const float4 r = *(const float4*)(buf + lane * 4u); float v[4] = { r.x, r.y, r.z, r.w }; - if constexpr (!QUANT) { + if constexpr (MODE == GvMode::Rotate) { // f16 holds +-65504; a rotated post-norm row is orders below that, and the clamp keeps an // outlier finite instead of inf union { __half h[4]; uint2 u; } o; @@ -139,15 +148,10 @@ __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( #pragma unroll for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); m = r4d_wave_max(m); - const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f; + const float sc = m > 0.0f ? m * (1.0f / q8_top()) : 1.0f; if (lane == 0) s[(size_t)row * s_ld + (size_t)part * nkb + g] = sc; - const float inv = 1.0f / sc; - int pk = 0; - pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f), - fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false); - pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f), - fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true); - *(uint32_t*)(q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = (uint32_t)pk; + *(uint32_t*)(q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = + q8_pack4(v[0], v[1], v[2], v[3], 1.0f / sc); } } // namespace @@ -160,8 +164,8 @@ __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( // s [M][parts*K/128] f32 static int givens_quant_launch(long x, long pairs, long angle, long rscale, long q, long s, int M, int K, int parts, int stages, int x_ld, int q_ld, int s_ld, - const R4dSink& sk, bool quant = true) { - if (!x || !pairs || !angle || !rscale || !q || (quant && !s)) return -1; + const R4dSink& sk, GvMode mode = GvMode::Fp8) { + if (!x || !pairs || !angle || !rscale || !q || (mode != GvMode::Rotate && !s)) return -1; if (M <= 0 || K <= 0 || parts <= 0 || stages <= 0) return -2; if (K % (int)kGroup) return -3; // a rotation group cannot straddle the end of a row if (!x_ld) x_ld = K; @@ -169,17 +173,13 @@ static int givens_quant_launch(long x, long pairs, long angle, long rscale, long if (!q_ld) q_ld = parts * K; if (!s_ld) s_ld = parts * nkb; const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves; - const int rc = quant - ? R4D_EMIT(sk, givens_quant_act_fp8_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, - (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, - (const float*)rscale, (uint8_t*)q, (float*)s, (uint32_t)K, - (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, (uint32_t)x_ld, - (uint32_t)q_ld, (uint32_t)s_ld) - : R4D_EMIT(sk, givens_quant_act_fp8_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, - (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, - (const float*)rscale, (uint8_t*)q, (float*)s, (uint32_t)K, - (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, (uint32_t)x_ld, - (uint32_t)q_ld, (uint32_t)s_ld); +#define GV_EMIT(M_) R4D_EMIT(sk, (givens_quant_act_fp8_kernel), dim3((uint32_t)M, gy), dim3(kThreads), 0, \ + (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, (const float*)rscale, \ + (uint8_t*)q, (float*)s, (uint32_t)K, (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, \ + (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) + const int rc = mode == GvMode::I8 ? GV_EMIT(GvMode::I8) + : mode == GvMode::Fp8 ? GV_EMIT(GvMode::Fp8) : GV_EMIT(GvMode::Rotate); +#undef GV_EMIT if (rc != RAD_OK) return -4; return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0; } @@ -189,7 +189,8 @@ extern "C" int r4d_givens_quant_act_fp8_group(void) { return (int)kGroup; } // ============================================================== the plugin ABI entry point enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Q = 4, GV_S = 5 }; -static int givens_body(const RadArgs* a, const R4dSink& sk, bool quant) { +static int givens_body(const RadArgs* a, const R4dSink& sk, GvMode mode) { + const bool quant = mode != GvMode::Rotate; const RadTensor* x = r4d_opt(a, GV_X); const RadTensor* pr = r4d_opt(a, GV_PAIRS); const RadTensor* an = r4d_opt(a, GV_ANGLE); @@ -199,7 +200,8 @@ static int givens_body(const RadArgs* a, const R4dSink& sk, bool quant) { if (!x || !pr || !an || !rs || !q || (quant && !sc)) return R4D_NO(RAD_E_INVAL); if (x->rank < 2 || q->rank != 2 || (quant && sc->rank != 2) || pr->rank != 2 || an->rank != 2 || rs->rank != 2) return R4D_NO(RAD_E_SHAPE); - if (!quant && q->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); + if (mode == GvMode::Rotate && q->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); + if (mode == GvMode::I8 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE); if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); // rows are dim 0 and everything after it is the row, as quant_act_fp8 reads them @@ -220,14 +222,18 @@ static int givens_body(const RadArgs* a, const R4dSink& sk, bool quant) { if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); const int e = givens_quant_launch(r4d_addr(x), r4d_addr(pr), r4d_addr(an), r4d_addr(rs), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, (int)parts, - (int)stages, (int)xp, (int)qp, (int)sp, sk, quant); + (int)stages, (int)xp, (int)qp, (int)sp, sk, mode); return e == 0 ? RAD_OK : RAD_E_SHAPE; } static int rad_givens_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { - return givens_body(a, sk, true); + return givens_body(a, sk, GvMode::Fp8); +} +static int rad_givens_quant_act_i8g_body(const RadArgs* a, const R4dSink& sk) { + return givens_body(a, sk, GvMode::I8); } static int rad_givens_rotate_body(const RadArgs* a, const R4dSink& sk) { - return givens_body(a, sk, false); + return givens_body(a, sk, GvMode::Rotate); } R4D_ENTRY(r4d_rad_givens_quant_act_fp8, rad_givens_quant_act_fp8_body) R4D_ENTRY(r4d_rad_givens_rotate, rad_givens_rotate_body) +R4D_ENTRY(r4d_rad_givens_quant_act_i8g, rad_givens_quant_act_i8g_body) diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index f2d19202..ea31548c 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -506,15 +506,11 @@ extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, cons } uint32_t* wq = (uint32_t*)dst; uint32_t* hi = wq + g.N * g.K / 8; /* after the N*K/2 bytes of nibbles */ - const long long kpb = g.K / R4D_W4_KPB; const long long rb = (g.K * 5 + 7) / 8; for (long long nn = 0; nn < g.N; ++nn) { const uint8_t* row = pdata(pl[0]) + nn * rb; for (long long k = 0; k < g.K; ++k) { - const long long bit = k * 5; - uint32_t v = row[bit >> 3]; - if ((bit & 7) > 3) v |= (uint32_t)row[(bit >> 3) + 1] << 8; - const uint32_t q = (v >> (bit & 7)) & 31u; + const uint32_t q = rad_load_bits(row, 5, k); long long w; int nib; w4_slot(g, nn, k, &w, &nib); @@ -527,7 +523,6 @@ extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, cons hi[hw] |= (q >> 4) << (8 * s + e); } } - (void)kpb; return RAD_OK; } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index dec3ecf4..25f30698 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -218,6 +218,8 @@ int r4d_rad_gemm_bf16_tiled (const RadArgs*, RadStream); int r4d_rad_gemm_w4a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w5a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a16asym_m64(const RadArgs*, RadStream); +int r4d_rad_gemm_w4a8i8_tiled(const RadArgs*, RadStream); +int r4d_rad_gemm_w5a8i8_tiled(const RadArgs*, RadStream); int r4d_rad_gemm_w8a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_tiled (const RadArgs*, RadStream); @@ -325,6 +327,8 @@ int r4d_rad_givens_rotate (const RadArgs*, RadStream); int r4d_rad_givens_rotate_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_givens_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_givens_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +int r4d_rad_givens_quant_act_i8g (const RadArgs*, RadStream); +int r4d_rad_givens_quant_act_i8g_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 1414c920..ac838947 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -704,7 +704,8 @@ static const RadOperandSpec oGemmNt[] = { { "y", RAD_OPD_OUT, 0 }, }; -/* `pb1` and `pb2` are ParoQuant's, and the mxfp4a8 rows alone read them: the weight's rows +/* `pb1` and `pb2` are ParoQuant's, and the mxfp4a8 rows and the 4- and 5-bit asymmetric rows (w5a16, + * w4a16_asym, w4a8i8_asym, w5a8i8) read them: the weight's rows * [0, pb1), [pb1, pb2) and [pb2, N) each meet their own copy of the activation, side by side in a * row of `a` (so `a` is [M, parts * K]). 0 leaves a bound out. Optional, and absent from every * other grid: a fused projection whose pieces were not rotated apart has one activation. */ @@ -2345,6 +2346,10 @@ static const RadOpSchema kSchemas[] = { "fused projection's pieces were each rotated on their own. Only a weight stored with " "the \"givens\" transform reads the result; it is NOT quant_act_fp8's output in either " "direction."), + SCHEMA("givens_quant_act_i8g", pGivensQuantAct, oGivensQuantAct, + "givens_quant_act_fp8 with an int8 output: the same channel scale and rotations, then " + "quant_act_i8g's quantiser (scale = amax / 127 per `group`, round to nearest). For the int8 " + "prefill GEMMs of a weight stored with the \"givens\" transform."), SCHEMA("had_quant_act_fp8", pQuantActFp8, oQuantActFp8, "the same, with a `group`-wide Hadamard along K applied BEFORE the absmax. Pairs with " "an expert weight stored at dtype w4a8h, which carries the matching rotation and the " @@ -2944,6 +2949,12 @@ static const RadConstraint cGemmNtW5[] = { static const RadConstraint cGemmNtW4Asym[] = { C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16_asym"), }; +static const RadConstraint cGemmNtW4A8I8[] = { + C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a8i8_asym"), +}; +static const RadConstraint cGemmNtW5A8I8[] = { + C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w5a8i8"), +}; static const RadConstraint cGemmNtW2A8[] = { C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w2a8"), }; @@ -4713,6 +4724,30 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_gemm_w4a16asym_m64, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, nullptr }, +{ "gemm_w4a8i8_tiled", "gemm_nt_q", "gemm", + "the 4-bit ASYMMETRIC weight x int8 activation GEMM for prefill row counts (z-lab's ParoQuant int4): " + "int8 WMMA over (code - zero), the weight and activation scales folded per 128 of K", + "N a multiple of 16; K a multiple of 128; the activation scale per (row, 128 of K); weight in the " + "f16 kernel's fragment order; a partitioned weight (pb1/pb2) one launch a part", + "I8 A (parts side by side) with an f32 scale per (row, part, 128), 4-bit W with an f16 scale and " + "integer zero per 128 K, bf16 C, int32 accumulate per 128 of K", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, + ROW(cGemmNtW4A8I8), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_w4a8i8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, + r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, nullptr }, + +{ "gemm_w5a8i8_tiled", "gemm_nt_q", "gemm", + "the 5-bit ASYMMETRIC weight x int8 activation GEMM for prefill row counts (ParoQuant int5): int8 " + "WMMA over (code - zero), the weight and activation scales folded per 128 of K", + "N a multiple of 16; K a multiple of 128; the activation scale per (row, 128 of K); weight in the " + "int5 kernel's two planes (nibbles, then fifth bits); a partitioned weight (pb1/pb2) one launch a part", + "I8 A (parts side by side) with an f32 scale per (row, part, 128), 5-bit W with an f16 scale and " + "integer zero per 128 K, bf16 C, int32 accumulate per 128 of K", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, + ROW(cGemmNtW5A8I8), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_w5a8i8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, + r4d_rad_layout_w5, r4d_rad_relayout_w5, nullptr, nullptr }, + { "gemm_w8a16_nt_m64", "gemm_nt_q", "gemm", "skinny GEMM with an 8-bit weight, 16x16x16 WMMA, split-K reduced in LDS", "M <= 64; N a multiple of 16; K divisible by SK*128; weight pre-permuted into fragment order, " @@ -5210,6 +5245,18 @@ static const RadKernelInfo kKernels[] = { r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, r4d_rad_givens_quant_act_fp8_describe }, +{ "givens_quant_act_i8g", "givens_quant_act_i8g", "quant", + "the channel scale, ParoQuant's Givens rotations, then per-(row, 128-column) symmetric int8 " + "quantisation, once for each rotated part of a fused projection", + "n a multiple of 128 and group 128, as givens_quant_act_fp8's", + "bf16 in, int8 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale of amax/127 per " + "(row, part, 128 columns); the tables are the weight's int32 pairs, f32 angles and f32 channel " + "scales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cHadQuantActFp8), NOTUNE, + nullptr, nullptr, r4d_rad_givens_quant_act_i8g, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, r4d_rad_givens_quant_act_i8g_describe }, + { "givens_rotate", "givens_rotate", "quant", "the channel scale and ParoQuant's Givens rotations, once for each rotated part, to f16", "n a multiple of 128 and group 128: a rotation group cannot straddle the end of a row", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index ad46b242..2d18e012 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3741,8 +3741,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ * must sit within the E4M3 grid of the reference (half a step at the top of the range is 1/16 of * the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, - bool rot_only = false) { - const char* row = rot_only ? "givens_rotate" : "givens_quant_act_fp8"; + bool rot_only = false, bool i8 = false) { + const char* row = rot_only ? "givens_rotate" : i8 ? "givens_quant_act_i8g" : "givens_quant_act_fp8"; if (!sel(row)) return; char nm[160]; std::snprintf(nm, sizeof nm, "%s numeric M=%lld K=%lld parts=%d stages=%d", row, (long long)M, @@ -3792,7 +3792,7 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in std::vector ts = { T(d_x, RAD_BF16, { M, K }), T(d_p, RAD_I32, { NPS, K }), T(d_a, RAD_F32, { NPS, K / 2 }), T(d_r, RAD_F32, { (int64_t)parts, K }), - T(d_q, rot_only ? (uint32_t)RAD_F16 : (uint32_t)RAD_F8E4M3, { M, parts * K }), + T(d_q, rot_only ? (uint32_t)RAD_F16 : i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, { M, parts * K }), T(d_s, RAD_F32, { M, parts * ng }), }; if (rot_only) ts.pop_back(); @@ -3835,16 +3835,17 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in continue; } const double sc = hs[(size_t)(i * parts * ng + p * ng + g)]; - worst_scale = std::max(worst_scale, std::fabs(sc - amax / 448.0) / (amax / 448.0 + 1e-30)); + const double qmax = i8 ? 127.0 : 448.0; + worst_scale = std::max(worst_scale, std::fabs(sc - amax / qmax) / (amax / qmax + 1e-30)); for (int k = 0; k < G; ++k) { - const double deq = (double)rad_load_f32(hq.data(), RAD_F8E4M3, i * parts * K + p * K + g * G + k) * sc; + const double deq = (double)rad_load_f32(hq.data(), i8 ? RAD_I8 : RAD_F8E4M3, i * parts * K + p * K + g * G + k) * sc; worst_val = std::max(worst_val, std::fabs(deq - b[(size_t)(g * G + k)]) / (amax + 1e-30)); } } } char d[96]; std::snprintf(d, sizeof d, "scale rel %.2e, value/amax %.3f", worst_scale, worst_val); - ok(nm, rot_only ? worst_val < 1e-3 : (worst_scale < 1e-4 && worst_val < 0.07), d); + ok(nm, rot_only ? worst_val < 1e-3 : (worst_scale < 1e-4 && worst_val < (i8 ? 0.01 : 0.07)), d); } @@ -3956,6 +3957,226 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int } +/* TIMING OF THE 5/4-BIT GEMM AT ONE PREFILL CHUNK, over the row's tuned axes. `--case w5a16_perf` + * only (it is a measurement, not a check). One weight buffer is replicated past the last-level cache + * and walked in turn, as perf_row does, so the GB/s printed is the weight stream's. */ +static void w5a16_perf(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t K) { + if (!g_case || std::strcmp(g_case, "w5a16_perf")) return; + const char* row = bits == 5 ? "gemm_w5a16_nt_m64" : "gemm_w4a16_asym_nt_m64"; + const RadKernelInfo* r = find(pl, row); + if (!r) { std::printf("row absent\n"); return; } + const int64_t G = K / 128; + Planes p; + p.enc = rad_enc_affine(bits == 5 ? RAD_U5 : RAD_U4, RAD_F16, 1, 128); + rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); + p.size(N, K); + for (auto& d : p.data[0]) d = (uint8_t)st_mix32((uint32_t)(&d - p.data[0].data())); + for (int64_t i = 0; i < N * G; ++i) { + rad_store_f32(p.data[1].data(), RAD_F16, i, 0.01f); + p.data[2][(size_t)i] = 8; + } + std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", bits == 5 ? "w5a16" : "w4a16_asym") }; + std::vector wq, ws; + if (stored(r, lp, 2, p, { "codes" }, &wq) != RAD_OK || stored(r, lp, 3, p, { "scale", "zero" }, &ws) != RAD_OK) { + std::printf("relayout failed\n"); + return; + } + const size_t copies = std::max(2, (size_t)(256u << 20) / wq.size() + 1); + void* d_w = dalloc(wq.size() * copies); + void* d_s = dalloc(ws.size() * copies); + void* d_a = dalloc((size_t)(M * K * 2)); + void* d_y = dalloc((size_t)(M * N * 2)); + if (!d_w || !d_s || !d_a || !d_y) { std::printf("hipMalloc failed\n"); return; } + for (size_t c = 0; c < copies; ++c) { + st_memcpy((uint8_t*)d_w + c * wq.size(), wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy((uint8_t*)d_s + c * ws.size(), ws.data(), ws.size(), hipMemcpyHostToDevice); + } + std::printf("%s M=%lld N=%lld K=%lld (weight %.1f MiB)\n", row, (long long)M, (long long)N, + (long long)K, wq.size() / 1048576.0); + struct Cfg { int wv, sk, mb, npw, nt; }; + std::vector cfgs; + for (int sk : { 0, 1, 2, 4, 5, 8 }) + for (int mb : { 0, 1, 2, 4 }) + for (int npw : { 1, 4 }) + for (int wv : { 1, 2, 4 }) cfgs.push_back({ wv, sk, mb, npw, 1 }); + double best = 1e30; + Cfg bc{}; + for (const Cfg& c : cfgs) { + std::vector ts = { + T(d_a, RAD_F16, { M, K }), T(nullptr, RAD_F32, { 1 }), T(d_w, RAD_U8, { (int64_t)wq.size() }), + T(d_s, RAD_U8, { (int64_t)ws.size() }), T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), + T(nullptr, RAD_F32, { 1 }) }; + absent(ts[1]); absent(ts[5]); absent(ts[6]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", bits == 5 ? "w5a16" : "w4a16_asym"), + PI("wv", c.wv), PI("sk", c.sk), PI("mb", c.mb), PI("npw", c.npw), + PI("nt", c.nt) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + if (r->launch(&a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) continue; + hipEvent_t e0, e1; + st_ev_create(&e0); st_ev_create(&e1); + st_ev_record(e0, nullptr); + const int iters = 12; + for (int i = 0; i < iters; ++i) { + ts[2].data = (uint8_t*)d_w + (size_t)(i % copies) * wq.size(); + ts[3].data = (uint8_t*)d_s + (size_t)(i % copies) * ws.size(); + r->launch(&a, nullptr); + } + st_ev_record(e1, nullptr); + st_ev_sync(e1); + float ms = 0; + st_ev_elapsed(&ms, e0, e1); + st_ev_destroy(e0); st_ev_destroy(e1); + const double us = (double)ms * 1000.0 / iters; + const double tf = 2.0 * M * N * K / (us * 1e6); + std::printf(" wv=%d sk=%d mb=%d npw=%d %9.1f us %6.1f TF/s %6.1f GB/s\n", c.wv, c.sk, c.mb, + c.npw, us, tf, (double)wq.size() / (us * 1e3)); + if (us < best) { best = us; bc = c; } + } + std::printf("best wv=%d sk=%d mb=%d npw=%d: %.1f us\n", bc.wv, bc.sk, bc.mb, bc.npw, best); +} + + +/* THE 4/5-BIT ASYMMETRIC x INT8 PREFILL GEMM against what the planes mean: u4/u5 codes, an f16 scale and + * a u8 zero a 128 of K, an int8 activation with an f32 scale a (row, 128), parts side by side. */ +static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t K, int64_t pb1 = 0, + int64_t pb2 = 0) { + const char* row = bits == 4 ? "gemm_w4a8i8_tiled" : "gemm_w5a8i8_tiled"; + if (!sel(row)) return; + const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; + const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + char nm[160]; + std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, + (long long)N, (long long)K, parts); + const RadKernelInfo* r = find(pl, row); + if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } + const int64_t G = K / 128; + Planes p; + p.enc = rad_enc_affine(bits == 4 ? RAD_U4 : RAD_U5, RAD_F16, 1, 128); + rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); + p.size(N, K); + const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); + const int64_t rb = p.row_bytes(ic); + for (int64_t n = 0; n < N; ++n) { + for (int64_t k = 0; k < K; ++k) { + const uint32_t q = st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & ((1u << bits) - 1); + const int64_t bit = k * bits; + uint8_t* b = p.data[(size_t)ic].data() + n * rb + (bit >> 3); + const uint32_t v = q << (bit & 7); + b[0] |= (uint8_t)(v & 0xFF); + if ((bit & 7) > 3) b[1] |= (uint8_t)(v >> 8); + } + for (int64_t g = 0; g < G; ++g) { + const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); + rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, 0.002f * (float)(1 + h % 40)); + p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)((h >> 8) % (1u << bits)); + } + } + std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", bits == 4 ? "w4a8i8_asym" : "w5a8i8") }; + std::vector wq, ws; + const int rw = stored(r, lp, 2, p, { "codes" }, &wq); + const int rs = stored(r, lp, 3, p, { "scale", "zero" }, &ws); + if (rw != RAD_OK || rs != RAD_OK) { + ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs)); + return; + } + const int64_t PK = parts * K, PG = parts * G; + std::vector ha((size_t)(M * PK)); + std::vector av((size_t)(M * PK)), as((size_t)(M * PG)); + for (int64_t i = 0; i < M; ++i) { + for (int64_t c = 0; c < PG; ++c) + as[(size_t)(i * PG + c)] = 0.002f * (float)(1 + st_mix32((uint32_t)(i * PG + c) ^ 0xa5u) % 97); + for (int64_t k = 0; k < PK; ++k) { + const int q8 = (int)(st_mix32((uint32_t)(i * PK + k) ^ 0x3cu) % 255u) - 127; + ha[(size_t)(i * PK + k)] = (uint8_t)(int8_t)q8; + av[(size_t)(i * PK + k)] = (float)q8; + } + } + std::vector hy((size_t)(M * N), 0); + void* d_a = dalloc(ha.size()); + void* d_s = dalloc(as.size() * 4); + void* d_w = dalloc(wq.size()); + void* d_e = dalloc(ws.size()); + void* d_y = dalloc(hy.size() * 2); + if (!d_a || !d_s || !d_w || !d_e || !d_y) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice); + st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice); + std::vector ts = { + T(d_a, RAD_I8, { M, PK }), T(d_s, RAD_F32, { M, PG }), + 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(nullptr, RAD_F32, { 1 }), + }; + absent(ts[5]); absent(ts[6]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", bits == 4 ? "w4a8i8_asym" : "w5a8i8") }; + if (pb1) ps.push_back(PI("pb1", pb1)); + if (pb2) ps.push_back(PI("pb2", pb2)); + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + if (r->scratch) { + const int64_t sb = r->scratch(&a); + if (sb > 0) { a.scratch = dalloc((size_t)sb); a.scratch_bytes = sb; } + } + const int rc = r->launch(&a, (RadStream) nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { ok(nm, false, "rc=" + std::to_string(rc)); return; } + st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost); + const int64_t nstep = N > 96 ? N / 96 : 1; + double num = 0, den = 0; + for (int64_t i = 0; i < M; i += (M > 64 ? 3 : 1)) + for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) { + const int pt = part_of(n); + double acc = 0; + for (int64_t g = 0; g < G; ++g) { + double grp = 0; + const double z = p.data[(size_t)iz][(size_t)(n * G + g)]; + const double sc = rad_load_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g); + for (int64_t k = g * 128; k < (g + 1) * 128; ++k) { + const int64_t bit = k * bits; + const uint8_t* rowp = p.data[(size_t)ic].data() + n * rb; + uint32_t v = rowp[bit >> 3]; + if ((bit & 7) > 3) v |= (uint32_t)rowp[(bit >> 3) + 1] << 8; + const double q = (v >> (bit & 7)) & ((1u << bits) - 1); + grp += (double)av[(size_t)(i * PK + pt * K + k)] * (q - z); + } + acc += grp * sc * (double)as[(size_t)(i * PG + pt * G + g)]; + } + const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc; + num += d * d; + den += acc * acc; + } + const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num); + char d[96]; + std::snprintf(d, sizeof d, "rel_l2 %.3e", rel); + if (M >= 1024) { // a prefill chunk: say how fast it ran + hipEvent_t e0, e1; + st_ev_create(&e0); st_ev_create(&e1); + st_ev_record(e0, nullptr); + for (int i = 0; i < 10; ++i) r->launch(&a, nullptr); + st_ev_record(e1, nullptr); + st_ev_sync(e1); + float ms = 0; + st_ev_elapsed(&ms, e0, e1); + st_ev_destroy(e0); st_ev_destroy(e1); + std::snprintf(d, sizeof d, "rel_l2 %.3e, %.0f us, %.1f TF/s", rel, ms * 100.0, + 2.0 * M * N * K / ((double)ms * 100.0 * 1e6)); + std::printf(" %s\n", d); + } + ok(nm, rel < 1e-2, d); +} + + /* TWO DECODE GEMMS THE ENGINE MAY OVERLAP (gemm_mxfp4a8_decode is a concurrent row: its split partial * is the op's scratch and its arrival counters are keyed on the output). Each GEMM has its own * weights, activations and output and a DISJOINT slice of one scratch allocation, with a split @@ -12895,6 +13116,24 @@ static void device_phase(const Plugin& pl) { moe_w4_rot(pl); } + if (g_case && !std::strcmp(g_case, "w5a16_perf")) { + w5a16_perf(pl, 4, 64, 17408, 5120); + w5a16_perf(pl, 4, 64, 5120, 17408); + w5a16_perf(pl, 4, 16, 17408, 5120); + } + for (int bits : { 4, 5 }) { + const char* row = bits == 4 ? "gemm_w4a8i8_tiled" : "gemm_w5a8i8_tiled"; + if (!sel(row)) continue; + if (!g_case) std::printf("\nParoQuant int%d prefill GEMM (int8 WMMA), against the planes' meaning\n", bits); + wpa8i8_numeric(pl, bits, 300, 400, 640); + wpa8i8_numeric(pl, bits, 70, 272, 1280); + wpa8i8_numeric(pl, bits, 300, 400, 640, 192); + wpa8i8_numeric(pl, bits, 600, 512, 2560, 128, 384); + wpa8i8_numeric(pl, bits, 2100, 34816, 5120, 17408); + wpa8i8_numeric(pl, bits, 2048, 17408, 5120); + wpa8i8_numeric(pl, bits, 2048, 5120, 17408); + } + if (sel("gemm_w5a16_nt_m64")) { if (!g_case) std::printf("\nParoQuant's 5-bit GEMM, against the planes' meaning\n"); w5a16_numeric(pl, 8, 272, 640); @@ -12913,6 +13152,14 @@ static void device_phase(const Plugin& pl) { givens_numeric(pl, 300, 6144, 2, 8, true); } + if (sel("givens_quant_act_i8g")) { + if (!g_case) std::printf("\nParoQuant's rotated activation, int8 output, against libm's rotation\n"); + givens_numeric(pl, 1, 128, 1, 8, false, true); + givens_numeric(pl, 3, 5120, 1, 8, false, true); + givens_numeric(pl, 5, 5120, 2, 8, false, true); + givens_numeric(pl, 64, 17408, 1, 8, false, true); + givens_numeric(pl, 300, 6144, 2, 8, false, true); + } if (sel("givens_quant_act_fp8")) { if (!g_case) std::printf("\nParoQuant's rotate-and-quantise, against an f64 rotation\n"); givens_numeric(pl, 1, 128, 1, 8); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 25d21468..d1c03330 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -101,6 +101,7 @@ int ref_had_quant_act_i8 (const RadArgs*, RadStream); int ref_quant_act_fp8 (const RadArgs*, RadStream); int ref_had_quant_act_fp8 (const RadArgs*, RadStream); int ref_givens_quant_act_fp8(const RadArgs*, RadStream); +int ref_givens_quant_act_i8g(const RadArgs*, RadStream); int ref_givens_rotate(const RadArgs*, RadStream); int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); int ref_gated_quant_fp8 (const RadArgs*, RadStream); @@ -231,6 +232,7 @@ REF_SHAPE_FN(ref_had_quant_act_i8); REF_SHAPE_FN(ref_quant_act_fp8); REF_SHAPE_FN(ref_had_quant_act_fp8); REF_SHAPE_FN(ref_givens_quant_act_fp8); +REF_SHAPE_FN(ref_givens_quant_act_i8g); REF_SHAPE_FN(ref_givens_rotate); REF_SHAPE_FN(ref_rmsnorm_quant_fp8); REF_SHAPE_FN(ref_gated_quant_fp8); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 8c79cf04..f0e60573 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -427,7 +427,7 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { * stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32, then amax/448 per group. Not * bit-identical to the device on the angle: cos and sin of an f32 differ by an ulp between libm * and the GPU's. */ -static int givens_body(const RadArgs* a, bool quant) { +static int givens_body(const RadArgs* a, bool quant, bool i8 = false) { if (!have(a, quant ? 6 : 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3]; const RadTensor *q = &a->t[4], *s = quant ? &a->t[5] : nullptr; @@ -475,12 +475,14 @@ static int givens_body(const RadArgs* a, bool quant) { const float m = std::fabs(buf[(size_t)(k0 + i)]); if (m > amax) amax = m; } - const float scl = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; + const float qmax = i8 ? 127.0f : 448.0f; + const float scl = amax > 0.0f ? amax * (1.0f / qmax) : 1.0f; const float inv = 1.0f / scl; for (int64_t i = 0; i < g; ++i) { float v = buf[(size_t)(k0 + i)] * inv; - if (v > 448.0f) v = 448.0f; - if (v < -448.0f) v = -448.0f; + if (v > qmax) v = qmax; + if (v < -qmax) v = -qmax; + if (i8) v = std::nearbyint(v); st_dt(q->dtype, q->data, qb + (p * n + k0 + i) * qs, v); } stt(s, rowoff(s, r, P * ngrp) + (p * ngrp + gi) * laststride(s), scl); @@ -491,6 +493,7 @@ static int givens_body(const RadArgs* a, bool quant) { } int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { return givens_body(a, true); } +int ref_givens_quant_act_i8g(const RadArgs* a, RadStream) { return givens_body(a, true, true); } /* The same channel scale and rotations with NO quantiser: y = the rotated row in y's dtype, `parts` * copies side by side. For a weight whose GEMM reads a 16-bit activation (w5a16). */ diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index eb83a176..56debdd1 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -811,6 +811,10 @@ static const RadOpSchema kSchemas[] = { "stages) of `pairs` and `angle` and row p of `rscale`: a fused projection's pieces were each " "rotated on their own. Only a weight stored with the \"givens\" transform reads the result; " "it is NOT quant_act_fp8's output in either direction." }, +{ "givens_quant_act_i8g", ARR(pGivensQuant), ARR(oGivensQuant), + "givens_quant_act_fp8 with an int8 output: the same channel scale and rotations, then " + "quant_act_i8g's quantiser (scale = amax / 127 per `group`, round to nearest). For the int8 " + "prefill GEMMs of a weight stored with the \"givens\" transform." }, { "givens_rotate", ARR(pGivensQuant), ARR(oGivensRotate), "givens_quant_act_fp8 without the quantiser: y = x / rscale rotated by `stages` rounds of Givens " "pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight whose GEMM " @@ -1184,6 +1188,10 @@ SIMPLE("ref_givens_quant_act_fp8", "givens_quant_act_fp8", "quant", "channel scale and Givens rotations per part, then the block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; int32 pairs, f32 angles and channel scales", ref_givens_quant_act_fp8), +SIMPLE("ref_givens_quant_act_i8g", "givens_quant_act_i8g", "quant", + "channel scale and Givens rotations per part, then the block-scaled int8 quantiser", + "float in, int8 out, f32 scale per group; int32 pairs, f32 angles and channel scales", + ref_givens_quant_act_i8g), SIMPLE("ref_had_quant_act_fp8", "had_quant_act_fp8", "quant", "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; n a multiple of group", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 7aa5d46c..d631961b 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -836,6 +836,10 @@ int ref_givens_quant_act_fp8_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; } +int ref_givens_quant_act_i8g_shape(const RadParam*, int, int, RadOpdDesc*) { + return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ +} + int ref_givens_rotate_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ } diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index df1fab70..c33ab599 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -261,7 +261,7 @@ TEST(op_vocabulary) { "embed_lookup_q", "cast", "scale_rows", "softmax", - "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "givens_rotate", "had_quant_act_i8", + "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "givens_quant_act_i8g", "givens_rotate", "had_quant_act_i8", "gram_accum", /* The fused fp8 forms. A host run needs EVERY op covered, so these are what stands * between a host-backend run and "site 'host' is unavailable for this band". */ From 3491aca6fe72335a17ad72448675a6dbb8d487a7 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 20:32:48 +0200 Subject: [PATCH 11/17] ParoQuant int5/int4: the review fixes of PR 1 carried to the 5-/4-bit path * givens_rotate and givens_quant_act_i8g take the same checked `pairs` relayout as givens_quant_act_fp8. * gemm_w4a8i8/w5a8i8_tiled: one re-tile slab for every part, as gemm_mxfp4a8_tiled (they share its scratch hook, which is one slab now). * LinearFP8::decl_gemm_q: the one gemm_nt_q declaration, pb1/pb2 only with parts, for the MXFP4, the skinny 5-/4-bit and the int8 prefill GEMMs. --- arch/common/rad_fp8.h | 61 +++++++++++++------------------- libr4d/r4d_gemm_wpa8i8_tiled.hip | 6 ++-- libr4d/r4d_rows.cpp | 10 +++--- 3 files changed, 33 insertions(+), 44 deletions(-) diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 51ee97e6..5670b431 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -764,11 +764,16 @@ struct LinearFP8 { /* THE ROTATION OF A ROTATED WEIGHT, declared: its tables as views of the weight's own planes, its * code planes (`givens_quant_act_fp8`: E4M3 and a scale) or, with `f16`, its single f16 plane * (`givens_rotate`, for a GEMM that reads a 16-bit activation), and the op in front of the - * GEMM. `cut` is the rows of each rotated part; *pb1/*pb2 come back as the GEMM's part bounds. */ + * GEMM. `cut` is the rows of each rotated part; the GEMM's part bounds come back in pb1 and pb2. */ int declare_rotation(RadBuilder* b, Names& nm, const Geom& g, const char* base, const char* wn, const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp, const ActFP8& a, int64_t max_rows, const std::vector& cut, bool f16, int64_t* pb1, int64_t* pb2); + /* gemm_nt_q over this weight, M in [lo, hi]. `pb1`/`pb2` go only to a weight with rotated + * parts, so a one-part op keeps the plain op's geometry -- the key the tune cache is read by. */ + rad_op decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group, const char* dtype, + int64_t pb1, int64_t pb2, std::initializer_list wts, + std::initializer_list reads, rad_buf y) const; void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; /* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale @@ -875,6 +880,17 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* return RAD_OK; } +inline rad_op LinearFP8::decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group, + const char* dtype, int64_t pb1, int64_t pb2, + std::initializer_list wts, + std::initializer_list reads, rad_buf y) const { + const RadParam ps[] = { RAD_RANGE("M", lo, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", group), RAD_STR("dtype", dtype), + RAD_INT("pb1", pb1), RAD_INT("pb2", pb2) }; + const int n_ps = (int)(sizeof ps / sizeof ps[0]) - (rot_parts > 1 ? 0 : 2); + return rw(b, rad_decl_op(b, "gemm_nt_q", ps, n_ps, wts.begin(), (int)wts.size()), reads, { y }); +} + inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const Geom& g, const char* base, const char* wn, const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp, const ActFP8& a, int64_t max_rows, @@ -1093,20 +1109,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); if (!w || !ws) return RAD_E_INVAL; - op = rot_parts > 1 - ? rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, band ? kSplit : hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_FP8_BLOCK), - RAD_STR("dtype", bits5 ? "w5a16" : "w4a16_asym"), - RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), - RAD_WEIGHTS(w, ws)), - { rot_q }, { y }) - : rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, band ? kSplit : hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_FP8_BLOCK), - RAD_STR("dtype", bits5 ? "w5a16" : "w4a16_asym")), - RAD_WEIGHTS(w, ws)), - { rot_q }, { y }); + op = decl_gemm_q(b, 1, band ? kSplit : hi, RAD_FP8_BLOCK, bits5 ? "w5a16" : "w4a16_asym", + pb1, pb2, { w, ws }, { rot_q }, y); if (!op) return RAD_E_INVAL; if (band) { /* THE PREFILL BAND: rows above the skinny kernel's ceiling rotate to int8 and meet the int8 @@ -1124,18 +1128,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha RAD_INT("stages", S), RAD_INT("parts", P)), RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), { a.x }, { rot_q2, rot_s2 }); - op2 = rot_parts > 1 - ? rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a8i8" : "w4a8i8_asym"), - RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), - RAD_WEIGHTS(w, ws)), - { rot_q2, rot_s2 }, { y }) - : rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a8i8" : "w4a8i8_asym")), - RAD_WEIGHTS(w, ws)), - { rot_q2, rot_s2 }, { y }); + op2 = decl_gemm_q(b, kSplit + 1, hi, RAD_FP8_BLOCK, bits5 ? "w5a8i8" : "w4a8i8_asym", + pb1, pb2, { w, ws }, { rot_q2, rot_s2 }, y); if (!op_rot2 || !op2) return RAD_E_INVAL; } return RAD_OK; @@ -1224,16 +1218,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)); } - /* ONE GEMM for both: a rotated weight reads its own rotated pair, a plain one the - * producer's. `pb1`/`pb2` (the last two params) go only to a weight with parts, so a one-part - * op keeps the plain op's geometry -- the key the tune cache is read by. */ - const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; - const RadParam ps[] = { RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), - RAD_INT("pb1", pb1), RAD_INT("pb2", pb2) }; - const int n_ps = (int)(sizeof ps / sizeof ps[0]) - (rot_parts > 1 ? 0 : 2); - op = rw(b, rad_decl_op(b, "gemm_nt_q", ps, n_ps, RAD_WEIGHTS(w, ws, wref)), - { paro ? rot_q : a.q, paro ? rot_s : a.s }, { y }); + /* ONE GEMM for both: 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, "mxfp4a8", pb1, pb2, + { w, ws, wref }, { paro ? rot_q : a.q, paro ? rot_s : a.s }, y); return op ? RAD_OK : RAD_E_INVAL; } diff --git a/libr4d/r4d_gemm_wpa8i8_tiled.hip b/libr4d/r4d_gemm_wpa8i8_tiled.hip index 731ca882..b098f01e 100644 --- a/libr4d/r4d_gemm_wpa8i8_tiled.hip +++ b/libr4d/r4d_gemm_wpa8i8_tiled.hip @@ -239,7 +239,7 @@ static void wpa8i8_launch(long at, long ascale, long wq, long whi, long wsz, lon } // ============================================================== the plugin ABI entry points -// The row-major int8 activation is re-tiled into the op's scratch (one slab a part), then the GEMM +// The row-major int8 activation is re-tiled into the op's scratch (one slab, the parts in turn), then the GEMM // reads it from there -- mxfp4a8_tiled's arrangement exactly, including a partitioned weight as // one launch per part over windows of the planes. template @@ -258,11 +258,11 @@ static int wpa8i8_dispatch(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; if (as_group != 128) return R4D_NO(RAD_E_SHAPE); // one scale a (row, 128): the slab const long long slab = r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K); - if (!a->scratch || a->scratch_bytes < slab * mp.n) return R4D_NO(RAD_E_INVAL); + if (!a->scratch || a->scratch_bytes < slab) return R4D_NO(RAD_E_INVAL); const long long kb = g.K / 128; + const long at = (long)(uintptr_t)a->scratch; for (int p = 0; p < mp.n; ++p) { const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p]; - const long at = (long)(uintptr_t)a->scratch + (long)(p * slab); R4D_TRY("gemm_wpa8i8_tiled", r4d_mxfp4a8_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)); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index ac838947..96d82e1f 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -5254,8 +5254,9 @@ static const RadKernelInfo kKernels[] = { "scales", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHadQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_givens_quant_act_i8g, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_givens_quant_act_i8g_describe }, + nullptr, nullptr, r4d_rad_givens_quant_act_i8g, nullptr, r4d_rad_layout_givens_pairs, + r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, + r4d_rad_givens_quant_act_i8g_describe }, { "givens_rotate", "givens_rotate", "quant", "the channel scale and ParoQuant's Givens rotations, once for each rotated part, to f16", @@ -5264,8 +5265,9 @@ static const RadKernelInfo kKernels[] = { "f32 channel scales", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHadQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_givens_rotate, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr, r4d_rad_givens_rotate_describe }, + nullptr, nullptr, r4d_rad_givens_rotate, nullptr, r4d_rad_layout_givens_pairs, + r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, + r4d_rad_givens_rotate_describe }, { "quant_act_i8g", "quant_act_i8g", "quant", "per-(row, 128-column) symmetric int8 quantisation of a bf16 activation", From a19cbcae85dff7e9a517dd6241aff807a6bba13a Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 22:38:30 +0200 Subject: [PATCH 12/17] ParoQuant int5/int4: review fixes -- docs, the w5 layout pinned and inverted, zero points checked, int4 import tested * docs/OPS.md: the dtypes w5a16, w4a16_asym, w5a8i8, w4a8i8_asym, givens_quant_act_i8g, and which rows read pb1/pb2. * r4d_gemm_w5a16_nt_m64: drop the unused two's-complement dequant copied from w4; the errors name this kernel. * r4d_layout: r4d_rad_unrelayout_w5 (the inverse, wired to both w5 rows; the int4 rows take w4's); a zero point that is not a 4-/5-bit code is refused at load (the int8 prefill kernel reads five bits of it, the f16 one all). * rad_fp8.h: one linear_is_givens predicate (table dtypes checked for both formats, the zero plane's u8 too); declare_rotation declares the tables and rot_stages only, decl_rot_op the op in front of each GEMM. * tests: relayout_parity pins the w5 stored form and its refusal; checkpoint_test imports z-lab's int4 as a fused gate|up (two rotated parts); the selftest's asymmetric planes and part bounds come from one helper each. * checkpoint: the ParoQuant refusal names both readable forms. --- arch/common/rad_fp8.h | 129 +++++++++++++++---------------- core/format/checkpoint.cpp | 4 +- docs/OPS.md | 18 +++-- libr4d/r4d_gemm_w5a16_nt_m64.hip | 60 +++----------- libr4d/r4d_layout.cpp | 45 +++++++++++ libr4d/r4d_plugin.h | 2 + libr4d/r4d_rows.cpp | 8 +- libr4d/r4d_selftest.cpp | 107 ++++++++++++------------- tests/checkpoint_test.cpp | 97 +++++++++++++++++++++++ tests/relayout_parity_test.cpp | 29 +++++++ 10 files changed, 312 insertions(+), 187 deletions(-) diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 5670b431..51bce18e 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -712,7 +712,7 @@ struct LinearFP8 { rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0; rad_buf rot_q = 0, rot_s = 0; rad_op op_rot = 0; - int64_t rot_parts = 1; + int64_t rot_parts = 1, rot_stages = 0; /* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear * before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */ bool probed_i8 = false; @@ -761,14 +761,16 @@ struct LinearFP8 { std::initializer_list row_parts = {}, int64_t span_lo = 0, int64_t span_hi = 0, std::initializer_list rot_part_rows = {}); - /* THE ROTATION OF A ROTATED WEIGHT, declared: its tables as views of the weight's own planes, its - * code planes (`givens_quant_act_fp8`: E4M3 and a scale) or, with `f16`, its single f16 plane - * (`givens_rotate`, for a GEMM that reads a 16-bit activation), and the op in front of the - * GEMM. `cut` is the rows of each rotated part; the GEMM's part bounds come back in pb1 and pb2. */ - int declare_rotation(RadBuilder* b, Names& nm, const Geom& g, const char* base, const char* wn, + /* THE ROTATION TABLES OF A ROTATED WEIGHT, declared as views of the weight's own planes, with + * `rot_parts` and `rot_stages`. `cut` is the rows of each rotated part; the GEMM's part bounds + * come back in pb1 and pb2. */ + int declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp, - const ActFP8& a, int64_t max_rows, const std::vector& cut, - bool f16, int64_t* pb1, int64_t* pb2); + const std::vector& cut, int64_t* pb1, int64_t* pb2); + /* The op in front of the GEMM, over those tables: `op` is givens_rotate (f16 out) or a + * rotate-and-quantise (codes and a scale), for M in [lo, hi]. */ + rad_op decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* op, int64_t lo, + int64_t hi, std::initializer_list outs) const; /* gemm_nt_q over this weight, M in [lo, hi]. `pb1`/`pb2` go only to a weight with rotated * parts, so a one-part op keeps the plain op's geometry -- the key the tune cache is read by. */ rad_op decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group, const char* dtype, @@ -837,30 +839,33 @@ inline bool linear_is_mxfp4(const RadEncoding& e) { sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP; } -/* The ROTATED OCP-MXFP4 weight (ParoQuant): the same codes and E8M0 exponents, stored in the basis - * a "givens" transform names, with the rotation's tables as planes of their own (int32 column - * pairs, f32 angles, f32 channel scales, and for a fused projection one set a part). The GEMM - * reads it as the plain MXFP4 weight; the activation in front of it is rotated first. */ -inline bool linear_is_paro_mxfp4(const RadEncoding& e) { +/* A ROTATED weight (ParoQuant): an affine encoding stored in the basis a "givens" transform names, + * with the rotation's tables as planes of their own -- int32 column pairs, f32 angles, f32 channel + * scales, and for a fused projection one set a part. The GEMM reads the codes as stored; the + * activation in front of it is rotated first. */ +inline bool linear_is_givens(const RadEncoding& e) { if (!rad_enc_is(&e, "affine") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false; - if (!rad_enc_valid(&e) || e.n_planes < 5) return false; - const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + if (!rad_enc_valid(&e)) return false; const RadEncPlane *pr = rad_enc_plane(&e, "t.pairs"), *an = rad_enc_plane(&e, "t.angle"), *rs = rad_enc_plane(&e, "t.scale"); - return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc && - sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP && - pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32; + return pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32; } -/* ParoQuant's int5 (u5 codes) and z-lab's own int4 (u4 codes): u5 codes, an f16 scale and a u8 zero point a 128 of K (asymmetric), in the rotated - * basis, with the same rotation tables. Read by gemm_nt_q at dtype w5a16 over an f16 activation. */ +/* ...whose codes and E8M0 exponents are OCP-MXFP4's: read as the plain MXFP4 weight. */ +inline bool linear_is_paro_mxfp4(const RadEncoding& e) { + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return linear_is_givens(e) && e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc && + sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP; +} + +/* ...whose codes are ParoQuant's int5 (u5) or z-lab's int4 (u4), asymmetric: an f16 scale and a u8 + * zero point a 128 of K. Read by gemm_nt_q at w5a16 / w4a16_asym over an f16 activation, and at + * w5a8i8 / w4a8i8_asym over an int8 one. */ inline bool linear_is_paro_w5(const RadEncoding& e) { - if (!rad_enc_is(&e, "affine") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false; - if (!rad_enc_valid(&e) || e.n_planes < 6) return false; const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero"); - return (e.plane[0].dtype == RAD_U5 || e.plane[0].dtype == RAD_U4) && sc && zp && sc->dtype == RAD_F16 && sc->block[0] == 1 && - sc->block[1] == RAD_FP8_BLOCK && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK && - rad_enc_find(&e, "t.pairs") > 0; + return linear_is_givens(e) && (e.plane[0].dtype == RAD_U5 || e.plane[0].dtype == RAD_U4) && sc && + zp && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK && + zp->dtype == RAD_U8 && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK; } inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base, @@ -891,11 +896,10 @@ inline rad_op LinearFP8::decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int6 return rw(b, rad_decl_op(b, "gemm_nt_q", ps, n_ps, wts.begin(), (int)wts.size()), reads, { y }); } -inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const Geom& g, const char* base, - const char* wn, const RadEncoding& enc, int64_t N, int64_t K, - RadWeightGroup grp, const ActFP8& a, int64_t max_rows, - const std::vector& cut_in, bool f16, int64_t* pb1, - int64_t* pb2) { +inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn, + const RadEncoding& enc, int64_t N, int64_t K, + RadWeightGroup grp, const std::vector& cut_in, + int64_t* pb1, int64_t* pb2) { /* THE PARTS, in rows, and the tables as weights of their own. The container records how many * parts there are and not where they end -- a declaration has no plane bytes -- so the block * says: `rot_part_rows`, or its row parts when those are the cut. */ @@ -923,6 +927,7 @@ inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const Geom& g, return RAD_E_SHAPE; } rot_parts = P; + rot_stages = S; *pb1 = P > 1 ? cut[0] : 0; *pb2 = P > 2 ? cut[0] + cut[1] : 0; rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, @@ -931,29 +936,17 @@ inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const Geom& g, { P * S, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); rot_scale = decl_view(b, nm.f("%s.rot_scale", base), wn, "t.scale", RAD_F32, { P, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - if (!rot_pairs || !rot_angle || !rot_scale) return RAD_E_INVAL; - const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; - if (f16) { - rot_q = decl_b(b, nm.f("%s.rot_y", base), RAD_F16, { rows, P * K }); - if (!rot_q) return RAD_E_INVAL; - op_rot = rw(b, RAD_OP(b, "givens_rotate", - RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), - RAD_INT("stages", S), RAD_INT("parts", P)), - RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), - { a.x }, { rot_q }); - return op_rot ? RAD_OK : RAD_E_INVAL; - } - rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, P * K }); - rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, P * (K / RAD_FP8_BLOCK) }); - if (!rot_q || !rot_s) return RAD_E_INVAL; - op_rot = rw(b, RAD_OP(b, "givens_quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), - RAD_INT("stages", S), RAD_INT("parts", P)), - RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), - { a.x }, { rot_q, rot_s }); - return op_rot ? RAD_OK : RAD_E_INVAL; + return rot_pairs && rot_angle && rot_scale ? RAD_OK : RAD_E_INVAL; +} + +inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* op, + int64_t lo, int64_t hi, std::initializer_list outs) const { + return rw(b, RAD_OP(b, op, + RAD_PARAMS(RAD_RANGE("M", lo, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_INT("stages", rot_stages), + RAD_INT("parts", rot_parts)), + RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), + { a.x }, outs); } inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, @@ -1102,32 +1095,29 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha const bool bits5 = enc.plane[0].dtype == RAD_U5; const int64_t kSplit = 64; /* the skinny kernel's M ceiling */ const bool band = hi > kSplit; - RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, - band ? kSplit : max_rows, cut, true, &pb1, &pb2)); + const int64_t f16_hi = band ? kSplit : hi; /* the f16 chain's rows */ + RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2)); + const int64_t P = rot_parts; + rot_q = decl_b(b, nm.f("%s.rot_y", base), RAD_F16, { f16_hi, P * K }); + if (!rot_q) return RAD_E_INVAL; + op_rot = decl_rot_op(b, g, a, "givens_rotate", 1, f16_hi, { rot_q }); + if (!op_rot) return RAD_E_INVAL; w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); if (!w || !ws) return RAD_E_INVAL; - op = decl_gemm_q(b, 1, band ? kSplit : hi, RAD_FP8_BLOCK, bits5 ? "w5a16" : "w4a16_asym", + op = decl_gemm_q(b, 1, f16_hi, RAD_FP8_BLOCK, bits5 ? "w5a16" : "w4a16_asym", pb1, pb2, { w, ws }, { rot_q }, y); if (!op) return RAD_E_INVAL; if (band) { /* THE PREFILL BAND: rows above the skinny kernel's ceiling rotate to int8 and meet the int8 * tiled GEMM. Declared over the tables and weight views already made above. */ - const int64_t P = rot_parts; rot_split = kSplit; rot_q2 = decl_b(b, nm.f("%s.rot_q2", base), RAD_I8, { hi, P * K }); rot_s2 = decl_b(b, nm.f("%s.rot_s2", base), RAD_F32, { hi, P * (K / RAD_FP8_BLOCK) }); if (!rot_q2 || !rot_s2) return RAD_E_INVAL; - const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs"); - const int64_t S = tp->extent[0] / P; - op_rot2 = rw(b, RAD_OP(b, "givens_quant_act_i8g", - RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("n", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), - RAD_INT("stages", S), RAD_INT("parts", P)), - RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), - { a.x }, { rot_q2, rot_s2 }); + op_rot2 = decl_rot_op(b, g, a, "givens_quant_act_i8g", kSplit + 1, hi, { rot_q2, rot_s2 }); op2 = decl_gemm_q(b, kSplit + 1, hi, RAD_FP8_BLOCK, bits5 ? "w5a8i8" : "w4a8i8_asym", pb1, pb2, { w, ws }, { rot_q2, rot_s2 }, y); if (!op_rot2 || !op2) return RAD_E_INVAL; @@ -1192,8 +1182,13 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha std::vector 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, g, base, wn, enc, N, K, grp, a, max_rows, cut, - false, &pb1, &pb2)); + 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; + op_rot = decl_rot_op(b, g, a, "givens_quant_act_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); diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 3f414b92..3c10addb 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -552,8 +552,8 @@ void Checkpoint::detect_import() { else if (qc("format").empty() && qc("bits") == "4" && qc("group_size") == "128") import_ = Import::ParoI4; /* z-lab's own release: AWQ-packed int4, asymmetric */ else - import_why_ = "ParoQuant here is not the int5-bitplane format with 5-bit codes in groups " - "of 128, which is the one this reads"; + import_why_ = "ParoQuant here is neither the int5-bitplane format (5-bit codes) nor z-lab's " + "AWQ-packed int4, in groups of 128, which are the ones 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 diff --git a/docs/OPS.md b/docs/OPS.md index 4c7ce457..42f56a32 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -39,10 +39,13 @@ made knowingly. - `dtype` is always present and always a string. It names the **operand combination**, which is why a weight format and an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`, `fp8_e4m3`, `fp8a8`, `fp8a16`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`, `w8a16`, - `w2a8`, `mxfp4a8`. `w4a8h` is `w4a8` with a `group`-wide Walsh–Hadamard along K baked into the - stored weight (`docs/MOE-W4.md`), `w4a8_asym` the unsigned-nibble-minus-zero-point grid rather - than the symmetric one, and `fp8a8`/`fp8a16` say whether a block-scaled E4M3 weight is met by - an fp8 activation or a bf16 one. `q_dtype` and `kv_dtype` are the same key split in two where + `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`. `w4a8h` is `w4a8` with a + `group`-wide Walsh–Hadamard along K baked into the stored weight (`docs/MOE-W4.md`), `w4a8_asym` + the unsigned-nibble-minus-zero-point grid rather than the symmetric one, and `fp8a8`/`fp8a16` say + whether a block-scaled E4M3 weight is met by an fp8 activation or a bf16 one. `w5a16` and + `w4a16_asym` are ParoQuant's int5 and z-lab's int4 (u5 / u4 codes, an f16 scale and a u8 zero + point a 128 of K) against an f16 activation, and `w5a8i8` / `w4a8i8_asym` the same weights + against an int8 one with an f32 scale per (row, 128 of K). `q_dtype` and `kv_dtype` are the same key split in two where attention reads two formats at once. - `M` is the ranged parameter wherever a token count appears. **At most one ranged parameter per op** — that is what keeps `rad_issue` a single integer on the hot path. @@ -387,9 +390,10 @@ copies of the activation, written side by side -- `q` is `[M, parts * n]`, `scal `[M, parts * n / group]` -- and `pairs` and `angle` stack the parts' `stages` rows each, `rscale` one row a part. `gemm_nt_q` then takes `pb1` and `pb2`, the row bounds of the weight's parts: its rows `[0, pb1)`, `[pb1, pb2)` and `[pb2, N)` meet copy 0, 1 and 2, and `a`/`a_scale` are the wide -planes. `givens_rotate` is the same rotation with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` (ParoQuant int5: u5 codes, an f16 scale and a u8 zero point a 128 of K) and `w4a16_asym` (z-lab's int4, the same at 4 bits); their GEMM serves any `M` (rows past 64 run as chunks of 64). `pb1` absent is one part; `pb2` absent ends the second part at `N`. Only the `mxfp4a8` rows -read them, and the host rows that do not (`libavx`) refuse a call that names one rather than -contract against the wrong copy. +planes. `givens_rotate` is the same rotation with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`; their GEMM serves any `M` (rows past 64 run as chunks of 64). `givens_quant_act_i8g` is the rotation with `quant_act_i8g`'s quantiser (scale `amax / 127` per `group`), for `w5a8i8` / `w4a8i8_asym`. `pb1` absent is one part; `pb2` absent ends the second part at `N`. The `mxfp4a8` rows and the +asymmetric 4- and 5-bit rows (`w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`) read them, and the +host rows that do not (`libavx`) refuse a call that names one rather than contract against the +wrong copy. ### The int8 and gated fp8 fusions — device-only diff --git a/libr4d/r4d_gemm_w5a16_nt_m64.hip b/libr4d/r4d_gemm_w5a16_nt_m64.hip index 548d9b56..3a037dab 100644 --- a/libr4d/r4d_gemm_w5a16_nt_m64.hip +++ b/libr4d/r4d_gemm_w5a16_nt_m64.hip @@ -76,54 +76,18 @@ __device__ __forceinline__ v8h fragA(r4d_gu2 p, int u) { return x.f; } -// One dword of eight nibbles -> one 16x16x16 f16 B fragment, minus the zero point. -// t0/t1 split the even and odd nibbles into bytes; each v_perm_b32 pairs two of those bytes with -// the constant high byte 0x64, which is the f16 exponent field for 1024. nz carries -// -(1024 + zero) in BOTH halves so one v_pk_add_f16 corrects a pair. -// The unpack is under a percent of this kernel at M=8, where it is at the DRAM roofline and the -// arithmetic hides in the load latency. It is a real fraction at M=64, but that band belongs to -// r4d_gemm_w4a8_nt_m64 -- and with no dequant at all the f16 form still trails the int8 one there, -// because the gap is the matrix instruction and not the dequant. Nothing here is worth a knob. -#ifndef R4D_GEMM_W4_TWOS -#define R4D_GEMM_W4_TWOS 1 -#endif - // DO NOT FOLD THE GROUP SCALE INTO THE B FRAGMENT. One v_pk_mul_f16 per pair on the finished // integer q is exact in f16, removes the second accumulator array entirely and takes the M=64 shape // from 192 VGPRs to 135 -- and it is SLOWER on most of the drafter's shapes. The multiply lands // inside the per-fragment dependent chain between the unpack and the WMMA, where the per-group // epilogue it replaces sits outside it; this kernel is stall-bound, not register-bound. -__device__ __forceinline__ v8h dequant(unsigned w, __half2 nz) { - const unsigned K64 = 0x64646464u; -#if R4D_GEMM_W4_TWOS - // The stored nibble is a 4-bit TWO'S COMPLEMENT code, because that is what - // r4d_gemm_w4a8_nt_m64 needs -- it shifts the nibble into the byte's high half and reads the - // byte signed. This kernel wants OFFSET BINARY, so that 1024 + n minus the constant 1024 + 8 - // is the value. The two differ by bit 3 of the nibble, so one XOR per spread dword converts, - // and the zero point is then pinned to 8 for every group. Two instructions per fragment, on - // the kernel whose whole unpack is a fraction of a percent of its time at M=8 -- which is why - // the conversion lives here and not in the int8 kernel, where the unpack is three instructions - // and does matter. One quantised weight, two kernels, dispatched on M. - const unsigned t0 = (w & 0x0F0F0F0Fu) ^ 0x08080808u; - const unsigned t1 = ((w >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; -#else - const unsigned t0 = w & 0x0F0F0F0Fu; - const unsigned t1 = (w >> 4) & 0x0F0F0F0Fu; -#endif - union { unsigned u[4]; __half2 h2[4]; v8h f; } x; - x.u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // nibbles 0, 2 - x.u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // nibbles 4, 6 - x.u[2] = __builtin_amdgcn_perm(K64, t1, 0x05010400u); // nibbles 1, 3 - x.u[3] = __builtin_amdgcn_perm(K64, t1, 0x05030402u); // nibbles 5, 7 -#pragma unroll - for (int i = 0; i < 4; i++) x.h2[i] = __hadd2(x.h2[i], nz); - return x.f; -} - // One dword of eight nibbles plus the byte of their fifth bits -> one 16x16x16 f16 B fragment, // minus the zero point. Nibble 2e (e < 4) / 2(e-4)+1 is fragment element e, so bits 0..3 of `hb` -// are the fifth bits of the even nibbles' elements and bits 4..7 the odd nibbles'. +// are the fifth bits of the even nibbles' elements and bits 4..7 the odd nibbles'. Each v_perm_b32 +// pairs two code bytes with the constant high byte 0x64, the f16 exponent field for 1024, so a half +// is 1024 + code; nz carries -(1024 + zero) in BOTH halves, so one v_pk_add_f16 corrects a pair. +// The codes are offset binary (0..31, or 0..15 without the fifth bit): no sign flip. __device__ __forceinline__ unsigned spread16(unsigned n) { // 4 bits -> bit 4 of each byte return ((n * 0x00204081u) & 0x01010101u) << 4; } @@ -288,18 +252,18 @@ void r4d_gemm_w5a16_nt_m64(long a, long wq, long whi, long wsz, long c, int M, i if (!lda) lda = K; if (!ldc) ldc = N; if (M < 1 || M > R4D_GEMM_W4_MAX_M) - throw std::runtime_error("r4d gemm_w4a16_nt_m64: M must be 1..64"); - if (N % 16) throw std::runtime_error("r4d gemm_w4a16_nt_m64: N must be a multiple of 16"); + throw std::runtime_error("r4d gemm_w5a16_nt_m64: M must be 1..64"); + if (N % 16) throw std::runtime_error("r4d gemm_w5a16_nt_m64: N must be a multiple of 16"); if (K % (SK * R4D_GEMM_W4_GROUP)) - throw std::runtime_error("r4d gemm_w4a16_nt_m64: K must be divisible by SK*128"); - if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w4a16_nt_m64: threads/block > 1024"); - if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w4a16_nt_m64: MB must be 1..4"); - if (NPW != 1 && NPW != 4) throw std::runtime_error("r4d gemm_w4a16_nt_m64: NPW must be 1 or 4"); + throw std::runtime_error("r4d gemm_w5a16_nt_m64: K must be divisible by SK*128"); + if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w5a16_nt_m64: threads/block > 1024"); + if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w5a16_nt_m64: MB must be 1..4"); + if (NPW != 1 && NPW != 4) throw std::runtime_error("r4d gemm_w5a16_nt_m64: NPW must be 1 or 4"); const int ntiles = N / 16, mtiles = (M + 15) / 16; const int ncols = WV * NPW; dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32); size_t smem = (size_t)ncols * SK * 256 * sizeof(float); - if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w4a16_nt_m64: WV*NPW*SK too large"); + if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w5a16_nt_m64: WV*NPW*SK too large"); auto Ap = (const unsigned short*)a; auto Wp = (const unsigned*)wq; auto Hp = (const unsigned*)whi; @@ -316,7 +280,7 @@ void r4d_gemm_w5a16_nt_m64(long a, long wq, long whi, long wsz, long c, int M, i case 2: LAUNCH(2, NP, TT); break; \ case 3: LAUNCH(3, NP, TT); break; \ case 4: LAUNCH(4, NP, TT); break; \ - default: throw std::runtime_error("r4d gemm_w4a16_nt_m64: MB unsupported"); } + default: throw std::runtime_error("r4d gemm_w5a16_nt_m64: MB unsupported"); } if (NPW == 1) { if (NT) { LAUNCH_MB(1, true); } else { LAUNCH_MB(1, false); } } else { diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index ea31548c..17ba87e0 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -327,6 +327,18 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) { } } +/* Every zero point a code of `bits` bits: what an asymmetric grid's zero is, and what the int8 + * prefill kernel reads back out of the scale dword (r4d_gemm_wpa8i8_tiled.hip takes five bits of it, + * where the f16 kernel takes the whole value -- a larger zero would make the two disagree). */ +bool sz_zeros_fit(const WGeom& g, const RadTensor& zp, int bits) { + const long long nz = g.N * (g.K / g.group); + for (long long i = 0; i < nz; ++i) { + const int z = zero_at(zp, i); + if (z < 0 || z >= (1 << bits)) return false; + } + return true; +} + void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym) { const long long nt = g.N / R4D_NTILE, nsz = g.K / g.group; for (long long t = 0; t < nt; ++t) @@ -416,6 +428,9 @@ extern "C" int r4d_rad_relayout_w4(const RadParam* p, int n_p, int operand, cons if (dst_bytes != L.bytes) return RAD_E_SHAPE; std::memset(dst, 0, (size_t)dst_bytes); if (operand == Q_BSCALE) { + /* a ROTATED (ParoQuant) grid's zero is a 4-bit code */ + if (w4_asym(p, n_p) && std::strncmp(enc->transform, "givens", RAD_ENC_STR) == 0 && + !sz_zeros_fit(g, pl[1], 4)) return RAD_E_FORMAT; sz_write(g, pl, w4_asym(p, n_p) ? -1 : 8, (uint32_t*)dst); return RAD_OK; } @@ -501,6 +516,7 @@ extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, cons if (dst_bytes != L.bytes) return RAD_E_SHAPE; std::memset(dst, 0, (size_t)dst_bytes); if (operand == Q_BSCALE) { + if (!sz_zeros_fit(g, pl[1], 5)) return RAD_E_FORMAT; sz_write(g, pl, -1, (uint32_t*)dst); return RAD_OK; } @@ -526,6 +542,35 @@ extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, cons return RAD_OK; } +extern "C" int r4d_rad_unrelayout_w5(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + WGeom g; + const int rc = w5_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes) return RAD_E_SHAPE; + if (operand == Q_BSCALE) { + sz_read(g, (const uint32_t*)src, pl, true); + return RAD_OK; + } + const uint32_t* wq = (const uint32_t*)src; + const uint32_t* hi = wq + g.N * g.K / 8; + const long long rb = (g.K * 5 + 7) / 8; + uint8_t* d = (uint8_t*)pl[0].data; + std::memset(d, 0, (size_t)(g.N * rb)); + for (long long nn = 0; nn < g.N; ++nn) + for (long long k = 0; k < g.K; ++k) { + long long w; + int nib; + w4_slot(g, nn, k, &w, &nib); + const int e = nib % 2 == 0 ? nib / 2 : 4 + nib / 2; /* as r4d_rad_relayout_w5 */ + const uint32_t q = ((wq[w] >> (4 * nib)) & 15u) | (((hi[w / 4] >> (8 * (w % 4) + e)) & 1u) << 4); + rad_store_bits(d + nn * rb, 5, k, q); + } + return RAD_OK; +} + /* ---- w8: i8 codes, symmetric about zero, an f16 scale a group. The f16 kernel (a16) reads the * code offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed with a * bare f16 scale plane. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 25f30698..3609719f 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -399,6 +399,8 @@ int r4d_rad_layout_w5(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_w5(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, void*, int64_t); +int r4d_rad_unrelayout_w5(const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 96d82e1f..5b841e59 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4711,7 +4711,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, ROW(cGemmNtW5), ROW(tGemmSkinny), r4d_tune_valid_gemm, nullptr, nullptr, r4d_rad_gemm_w5a16_m64, nullptr, r4d_rad_layout_w5, r4d_rad_relayout_w5, - nullptr, nullptr }, + nullptr, r4d_rad_unrelayout_w5 }, { "gemm_w4a16_asym_nt_m64", "gemm_nt_q", "gemm", "skinny GEMM with a 4-bit ASYMMETRIC weight (z-lab's ParoQuant int4), the 5-bit row's kernel with " @@ -4722,7 +4722,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, ROW(cGemmNtW4Asym), ROW(tGemmSkinny), r4d_tune_valid_gemm, nullptr, nullptr, r4d_rad_gemm_w4a16asym_m64, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4, - nullptr, nullptr }, + nullptr, r4d_rad_unrelayout_w4 }, { "gemm_w4a8i8_tiled", "gemm_nt_q", "gemm", "the 4-bit ASYMMETRIC weight x int8 activation GEMM for prefill row counts (z-lab's ParoQuant int4): " @@ -4734,7 +4734,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, ROW(cGemmNtW4A8I8), NOTUNE, nullptr, nullptr, r4d_rad_gemm_w4a8i8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, - r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, nullptr }, + r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, r4d_rad_unrelayout_w4 }, { "gemm_w5a8i8_tiled", "gemm_nt_q", "gemm", "the 5-bit ASYMMETRIC weight x int8 activation GEMM for prefill row counts (ParoQuant int5): int8 " @@ -4746,7 +4746,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, ROW(cGemmNtW5A8I8), NOTUNE, nullptr, nullptr, r4d_rad_gemm_w5a8i8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, - r4d_rad_layout_w5, r4d_rad_relayout_w5, nullptr, nullptr }, + r4d_rad_layout_w5, r4d_rad_relayout_w5, nullptr, r4d_rad_unrelayout_w5 }, { "gemm_w8a16_nt_m64", "gemm_nt_q", "gemm", "skinny GEMM with an 8-bit weight, 16x16x16 WMMA, split-K reduced in LDS", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 2d18e012..c2f1f4f2 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -865,6 +865,42 @@ struct Planes { } }; +/* gemm_nt_q's `pb1`/`pb2` over N rows (ParoQuant): rows [0, e1), [e1, e2), [e2, N) meet copies 0, 1, + * 2 of the activation, side by side in a row; `parts` is how many copies there are. 0 leaves a + * bound out, as the kernels read it. */ +struct PartCut { + int64_t e1, e2; + int parts; + PartCut(int64_t N, int64_t pb1, int64_t pb2) + : e1(pb1 > 0 ? std::min(pb1, N) : N), + e2(pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N), + parts(e2 < N ? 3 : (e1 < N ? 2 : 1)) {} + int part_of(int64_t n) const { return (int)(n >= e1) + (int)(n >= e2); } +}; + +/* An ASYMMETRIC grid's planes for a [N, K] weight: `bits`-bit codes (a bit stream along K), an f16 + * scale and a u8 zero point 0 .. 2^bits - 1 a 128 of K, drawn through st_mix32 of their coordinates. */ +static Planes asym_planes(int bits, int64_t N, int64_t K) { + Planes p; + p.enc = rad_enc_affine(bits == 4 ? RAD_U4 : RAD_U5, RAD_F16, 1, 128); + rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); + p.size(N, K); + const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); + const int64_t rb = p.row_bytes(ic), G = K / 128; + const uint32_t top = (1u << bits) - 1; + for (int64_t n = 0; n < N; ++n) { + for (int64_t k = 0; k < K; ++k) + rad_store_code(p.data[(size_t)ic].data() + n * rb, p.enc.plane[ic].dtype, k, + (int)(st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & top)); + for (int64_t g = 0; g < G; ++g) { + const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); + rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, 0.002f * (float)(1 + h % 40)); + p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)((h >> 8) & top); + } + } + return p; +} + /* The unnormalised Sylvester Walsh-Hadamard transform of `n` values, in place: (a + b) to the lower * index and (a - b) to the upper, the transform an "fwhtN" encoding names. H_n H_n = n I. */ static void h_fwht(float* v, int64_t n) { @@ -3609,10 +3645,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ if (!sel(row)) return; /* PARTS (ParoQuant): the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy * of the activation, the copies side by side in a row. `K` is one copy's width. */ - const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; - const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; - const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); - auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + 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); @@ -3713,7 +3747,7 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ 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)) { double acc = 0; - const int pt = part_of(n); + const int pt = cut.part_of(n); for (int64_t k = 0; k < K; ++k) { const double w = (double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) * (double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32); @@ -3857,38 +3891,17 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int int64_t pb2 = 0) { const char* row = "gemm_w5a16_nt_m64"; if (!sel(row)) return; - const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; - const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; - const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); - auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + const PartCut cut(N, pb1, pb2); + const int parts = cut.parts; char nm[160]; std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, (long long)N, (long long)K, parts); const RadKernelInfo* r = find(pl, row); if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } const int64_t G = K / 128; - Planes p; - p.enc = rad_enc_affine(RAD_U5, RAD_F16, 1, 128); - rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); - p.size(N, K); + const Planes p = asym_planes(5, N, K); const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); const int64_t rb = p.row_bytes(ic); - for (int64_t n = 0; n < N; ++n) { - for (int64_t k = 0; k < K; ++k) { - const uint32_t q = st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & 31u; - const int64_t bit = k * 5; - uint8_t* b = p.data[(size_t)ic].data() + n * rb + (bit >> 3); - const uint32_t v = q << (bit & 7); - b[0] |= (uint8_t)(v & 0xFF); - if ((bit & 7) > 3) b[1] |= (uint8_t)(v >> 8); - } - for (int64_t g = 0; g < G; ++g) { - const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); - const float sc = 0.002f * (float)(1 + h % 40); - rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, sc); - p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)(8 + (h >> 8) % 20); - } - } std::vector lp = { PI("N", N), PI("K", K), PI("group", 128) }; std::vector wq, ws; const int rw = stored(r, lp, 2, p, { "codes" }, &wq); @@ -3938,7 +3951,7 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int 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 = part_of(n); + const int pt = cut.part_of(n); double acc = 0; for (int64_t k = 0; k < K; ++k) { const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, RAD_U5, k); @@ -4048,37 +4061,17 @@ static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int int64_t pb2 = 0) { const char* row = bits == 4 ? "gemm_w4a8i8_tiled" : "gemm_w5a8i8_tiled"; if (!sel(row)) return; - const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; - const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; - const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); - auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + const PartCut cut(N, pb1, pb2); + const int parts = cut.parts; char nm[160]; std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, (long long)N, (long long)K, parts); const RadKernelInfo* r = find(pl, row); if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } const int64_t G = K / 128; - Planes p; - p.enc = rad_enc_affine(bits == 4 ? RAD_U4 : RAD_U5, RAD_F16, 1, 128); - rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); - p.size(N, K); + const Planes p = asym_planes(bits, N, K); const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); const int64_t rb = p.row_bytes(ic); - for (int64_t n = 0; n < N; ++n) { - for (int64_t k = 0; k < K; ++k) { - const uint32_t q = st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & ((1u << bits) - 1); - const int64_t bit = k * bits; - uint8_t* b = p.data[(size_t)ic].data() + n * rb + (bit >> 3); - const uint32_t v = q << (bit & 7); - b[0] |= (uint8_t)(v & 0xFF); - if ((bit & 7) > 3) b[1] |= (uint8_t)(v >> 8); - } - for (int64_t g = 0; g < G; ++g) { - const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); - rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, 0.002f * (float)(1 + h % 40)); - p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)((h >> 8) % (1u << bits)); - } - } std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", bits == 4 ? "w4a8i8_asym" : "w5a8i8") }; std::vector wq, ws; const int rw = stored(r, lp, 2, p, { "codes" }, &wq); @@ -4136,18 +4129,14 @@ static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int double num = 0, den = 0; for (int64_t i = 0; i < M; i += (M > 64 ? 3 : 1)) for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) { - const int pt = part_of(n); + const int pt = cut.part_of(n); double acc = 0; for (int64_t g = 0; g < G; ++g) { double grp = 0; const double z = p.data[(size_t)iz][(size_t)(n * G + g)]; const double sc = rad_load_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g); for (int64_t k = g * 128; k < (g + 1) * 128; ++k) { - const int64_t bit = k * bits; - const uint8_t* rowp = p.data[(size_t)ic].data() + n * rb; - uint32_t v = rowp[bit >> 3]; - if ((bit & 7) > 3) v |= (uint32_t)rowp[(bit >> 3) + 1] << 8; - const double q = (v >> (bit & 7)) & ((1u << bits) - 1); + const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, p.enc.plane[ic].dtype, k); grp += (double)av[(size_t)(i * PK + pt * K + k)] * (q - z); } acc += grp * sc * (double)as[(size_t)(i * PG + pt * G + g)]; diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index 1968e8aa..dbc669f4 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -932,3 +932,100 @@ TEST(a_paroquant_int5_weight_is_relaid_row_by_row) { CHECK_EQ(bad, 0); remove_checkpoint(dir); } + +/* Z-LAB'S INT4 (`paroquant`, bits 4, no `format`): the int5 test's AWQ nibbles with no fifth-bit + * planes, here as a fused gate|up -- two pieces, each with its own rotation, so the weight carries + * two parts. Codes and zero points come out row by row per piece, and t.part ends each piece. */ +TEST(a_paroquant_int4_fused_weight_is_two_rotated_parts) { + const int64_t N = 32, K = 128, G = K / 128; + uint32_t rng = 4242; + auto next = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; }; + static const int kOrder[8] = { 0, 2, 4, 6, 1, 3, 5, 7 }; + auto pack_awq = [&](const std::string& name, const std::vector& v, int64_t rows) { + T t{ name, "I32", { rows, N / 8 }, {} }; + t.bytes.assign((size_t)(rows * N / 8 * 4), 0); + for (int64_t r = 0; r < rows; ++r) + for (int64_t n = 0; n < N; ++n) { + int j = 0; + while (kOrder[j] != n % 8) ++j; + uint32_t w; + uint8_t* p = t.bytes.data() + (r * (N / 8) + n / 8) * 4; + std::memcpy(&w, p, 4); + w |= (uint32_t)(v[(size_t)(n * rows + r)] & 15) << (4 * j); + std::memcpy(p, &w, 4); + } + return t; + }; + auto f16s = [&](const std::string& name, std::vector shape, float v) { + T t{ name, "F16", shape, {} }; + int64_t cnt = 1; + for (int64_t d : shape) cnt *= d; + const uint16_t h = rad_f32_to_f16(v); + for (int64_t i = 0; i < cnt; ++i) { t.bytes.push_back((uint8_t)(h & 0xff)); t.bytes.push_back((uint8_t)(h >> 8)); } + return t; + }; + auto pairs = [&](const std::string& name, int shift) { + T t{ name, "I16", { 1, K }, {} }; + for (int64_t i = 0; i < K; ++i) { + const int16_t v = (int16_t)((i ^ shift) % 128); + t.bytes.push_back((uint8_t)(v & 0xff)); + t.bytes.push_back((uint8_t)(v >> 8)); + } + return t; + }; + std::vector ts; + std::vector code[2], zero[2]; + const char* names[2] = { "g", "u" }; + for (int p = 0; p < 2; ++p) { + code[p].resize((size_t)(N * K)); + zero[p].resize((size_t)(N * G)); + for (auto& c : code[p]) c = (int)(next() % 16); + for (auto& z : zero[p]) z = (int)(next() % 16); + const std::string b = names[p]; + ts.push_back(pack_awq(b + ".qweight", code[p], K)); + ts.push_back(pack_awq(b + ".qzeros", zero[p], G)); + ts.push_back(f16s(b + ".scales", { G, N }, 0.01f * (float)(p + 1))); + ts.push_back(pairs(b + ".pairs", p + 1)); // adjacent / next-but-one swaps + ts.push_back(f16s(b + ".theta", { 1, K / 2 }, 0.2f)); + ts.push_back(f16s(b + ".channel_scales", { 1, K }, 1.25f)); + } + const std::string dir = write_checkpoint(ts, + "{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":\"paroquant\"," + "\"bits\":4,\"group_size\":128,\"krot\":1}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK(ck.imports() == Checkpoint::Import::ParoI4); + 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 && w.imported); + CHECK_EQ(w.rows, 2 * N); + CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_U4); + CHECK_EQ(rad_enc_givens_parts(&w.enc), (int64_t)2); + 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].assign((size_t)(pr_ * rad_enc_row_bytes(w.enc.plane[k].dtype, pc)) + 8, 0); + REQUIRE_EQ(ckpt_plane_rows(w, k, 0, pr_, pl[(size_t)k].data(), &why), RAD_OK); + } + const int64_t rb = rad_enc_row_bytes(RAD_U4, K); + int bad = 0; + for (int p = 0; p < 2; ++p) + for (int64_t n = 0; n < N; ++n) { + const int64_t r = p * N + n; + for (int64_t k = 0; k < K; ++k) + if ((int)rad_load_f32(pl[0].data() + r * rb, RAD_U4, k) != code[p][(size_t)(n * K + k)]) ++bad; + for (int64_t g = 0; g < G; ++g) + if (pl[2][(size_t)(r * G + g)] != zero[p][(size_t)(n * G + g)]) ++bad; + } + CHECK_EQ(bad, 0); + const int tpart = rad_enc_find(&w.enc, "t.part"); + REQUIRE(tpart > 0); + const int32_t* ends = (const int32_t*)pl[(size_t)tpart].data(); + CHECK_EQ(ends[0], (int32_t)N); + CHECK_EQ(ends[1], (int32_t)(2 * N)); + remove_checkpoint(dir); +} diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index d34b2801..11d93c50 100644 --- a/tests/relayout_parity_test.cpp +++ b/tests/relayout_parity_test.cpp @@ -166,6 +166,7 @@ const Hooks nHc { r4d_rad_layout_hc_e4m3, r4d_rad_relayout_hc_e4m3, const Hooks nMtp { r4d_rad_layout_mtp_e4m3, r4d_rad_relayout_mtp_e4m3, r4d_rad_unrelayout_mtp_e4m3 }; const Hooks nW4 { r4d_rad_layout_w4, r4d_rad_relayout_w4, r4d_rad_unrelayout_w4 }; +const Hooks nW5 { r4d_rad_layout_w5, r4d_rad_relayout_w5, r4d_rad_unrelayout_w5 }; const Hooks nW8a16 { r4d_rad_layout_w8a16, r4d_rad_relayout_w8a16, nullptr }; const Hooks nW8a8 { r4d_rad_layout_w8a8, r4d_rad_relayout_w8a8, nullptr }; const Hooks nW2 { r4d_rad_layout_w2a8, r4d_rad_relayout_w2a8, r4d_rad_unrelayout_w2a8 }; @@ -284,6 +285,34 @@ TEST(dense_int4_symmetric_and_asymmetric) { } } +/* ParoQuant's int5: u5 codes as w4's nibble plane plus a fifth-bit plane, the (scale, zero) dwords + * of the asymmetric w4 grid -- read back exactly; and a zero point that is not a 5-bit code refused, + * since the int8 prefill kernel reads five bits of it where the f16 one reads the whole value. */ +TEST(dense_int5_asymmetric) { + NEED_LIBQUANT(); + const int64_t N = 64, K = 256; + const std::vector w = weight(N, K, 19, 1, 128); + Opts kp, g; + kp.i("N", N).i("K", K).s("dtype", "w5a16"); + g.s("codes", "u5").s("zero", "u8").i("group", 128).s("scale", "f16"); + golden("w5", stored("w5", nW5, kp, "rtn", g, "blk.0.ffn_up.weight", N, K, w, + { { B, { "codes" } }, { BSCALE, { "scale", "zero" } } }), + 0xb0b1f9d187cbf267ull); + const Quantised q = quantise(quantizer("rtn"), g, "x", N, K, w); + REQUIRE_EQ(q.status, RAD_OK); + std::vector> bufs; + Selection s = select(q, N, K, { "scale", "zero" }, &bufs); + std::memcpy(bufs[0].data(), q.planes[(size_t)s.sel[0]].data(), bufs[0].size()); + std::memcpy(bufs[1].data(), q.planes[(size_t)s.sel[1]].data(), bufs[1].size()); + bufs[1][3] = 32; + RadLayout L{}; + REQUIRE_EQ(r4d_rad_layout_w5(kp.data(), kp.n(), BSCALE, &q.enc, s.sel.data(), s.t.data(), + (int)s.t.size(), &L), RAD_OK); + std::vector dst((size_t)L.bytes); + CHECK_EQ(r4d_rad_relayout_w5(kp.data(), kp.n(), BSCALE, &q.enc, s.sel.data(), s.t.data(), + (int)s.t.size(), dst.data(), L.bytes), RAD_E_FORMAT); +} + TEST(dense_int8_for_the_f16_and_the_int8_kernel) { NEED_LIBQUANT(); const int64_t N = 48, K = 256; From c17f5fdc899b017f68e0a2932b9758e5c4c29865 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 14:32:24 +0000 Subject: [PATCH 13/17] ParoQuant: dense per-group rotation (givens_dense_quant): composed 128x128 f16 matrices built at convert time, WMMA kernel with int8/fp8 epilogue; LinearFP8 uses it for the quantising rotation --- arch/common/rad_fp8.h | 83 +++++++++++++----- docs/OPS.md | 1 + libr4d/CMakeLists.txt | 1 + libr4d/r4d_givens_dense.hip | 168 ++++++++++++++++++++++++++++++++++++ libr4d/r4d_layout.cpp | 84 ++++++++++++++++++ libr4d/r4d_plugin.h | 6 ++ libr4d/r4d_rows.cpp | 42 +++++++++ libr4d/r4d_selftest.cpp | 69 +++++++++++++-- libref/ref_ops.h | 2 + libref/ref_quant.cpp | 46 ++++++++++ libref/ref_registry.cpp | 15 ++++ libref/ref_shapes.cpp | 4 + tests/ref_test.cpp | 2 +- 13 files changed, 493 insertions(+), 30 deletions(-) create mode 100644 libr4d/r4d_givens_dense.hip diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 51bce18e..eaffb755 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -709,7 +709,7 @@ struct LinearFP8 { int64_t rot_split = 0; rad_buf rot_q2 = 0, rot_s2 = 0; rad_op op_rot2 = 0, op2 = 0; - rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0; + rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0, rot_dense = 0; rad_buf rot_q = 0, rot_s = 0; rad_op op_rot = 0; int64_t rot_parts = 1, rot_stages = 0; @@ -761,21 +761,28 @@ struct LinearFP8 { std::initializer_list row_parts = {}, int64_t span_lo = 0, int64_t span_hi = 0, std::initializer_list rot_part_rows = {}); - /* THE ROTATION TABLES OF A ROTATED WEIGHT, declared as views of the weight's own planes, with - * `rot_parts` and `rot_stages`. `cut` is the rows of each rotated part; the GEMM's part bounds - * come back in pb1 and pb2. */ + /* THE ROTATION OF A ROTATED WEIGHT: its parts and stages (`rot_parts`, `rot_stages`) and its + * channel scale as a view of the weight's own plane. `cut` is the rows of each rotated part; the + * GEMM's part bounds come back in pb1 and pb2. */ int declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp, const std::vector& cut, int64_t* pb1, int64_t* pb2); - /* The op in front of the GEMM, over those tables: `op` is givens_rotate (f16 out) or a - * rotate-and-quantise (codes and a scale), for M in [lo, hi]. */ - rad_op decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* op, int64_t lo, - int64_t hi, std::initializer_list outs) const; + /* THE SEQUENTIAL NETWORK (decode: a few rows, where one network a row is cheap): the pairs and + * angles as views, and givens_rotate over them to f16, for M in [lo, hi]. */ + int decl_seq_tables(RadBuilder* b, Names& nm, const char* base, const char* wn, RadWeightGroup grp); + rad_op decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, int64_t lo, int64_t hi, + std::initializer_list outs) const; + /* THE DENSE ROTATION (rot_dense, decl_dense): givens_dense_quant to `out` ("fp8" or "i8") codes + * and a scale, for M in [lo, hi]. */ + rad_op decl_dense_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* out, int64_t lo, + int64_t hi, std::initializer_list outs) const; /* gemm_nt_q over this weight, M in [lo, hi]. `pb1`/`pb2` go only to a weight with rotated * parts, so a one-part op keeps the plain op's geometry -- the key the tune cache is read by. */ rad_op decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group, const char* dtype, int64_t pb1, int64_t pb2, std::initializer_list wts, std::initializer_list reads, rad_buf y) const; + rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, int64_t N, int64_t K, + RadWeightGroup grp); void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; /* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale @@ -930,18 +937,24 @@ inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const char* bas rot_stages = S; *pb1 = P > 1 ? cut[0] : 0; *pb2 = P > 2 ? cut[0] + cut[1] : 0; - rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, - { P * S, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - rot_angle = decl_view(b, nm.f("%s.rot_angle", base), wn, "t.angle", RAD_F32, - { P * S, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); rot_scale = decl_view(b, nm.f("%s.rot_scale", base), wn, "t.scale", RAD_F32, { P, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - return rot_pairs && rot_angle && rot_scale ? RAD_OK : RAD_E_INVAL; + return rot_scale ? RAD_OK : RAD_E_INVAL; } -inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* op, - int64_t lo, int64_t hi, std::initializer_list outs) const { - return rw(b, RAD_OP(b, op, +inline int LinearFP8::decl_seq_tables(RadBuilder* b, Names& nm, const char* base, const char* wn, + RadWeightGroup grp) { + const int64_t PS = rot_parts * rot_stages; + rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, + { PS, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + rot_angle = decl_view(b, nm.f("%s.rot_angle", base), wn, "t.angle", RAD_F32, + { PS, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + return rot_pairs && rot_angle ? RAD_OK : RAD_E_INVAL; +} + +inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, int64_t lo, + int64_t hi, std::initializer_list outs) const { + return rw(b, RAD_OP(b, "givens_rotate", RAD_PARAMS(RAD_RANGE("M", lo, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), RAD_INT("stages", rot_stages), RAD_INT("parts", rot_parts)), @@ -949,6 +962,25 @@ inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& { a.x }, outs); } +inline rad_op LinearFP8::decl_dense_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* out, + int64_t lo, int64_t hi, std::initializer_list outs) const { + return rw(b, RAD_OP(b, "givens_dense_quant", + RAD_PARAMS(RAD_RANGE("M", lo, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_INT("parts", rot_parts), + RAD_STR("out", out)), + RAD_WEIGHTS(rot_dense, rot_scale)), + { a.x }, outs); +} + +/* The dense rotation matrices of a rotated weight: a view of its two table planes, declared as several planes + * are -- at the first one's dtype (i32) and the weight's logical [N, K] -- that the op's layout hook + * (r4d_rad_layout_gdense) composes into [P * K, 128] f16. */ +inline rad_weight LinearFP8::decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, + int64_t N, int64_t K, RadWeightGroup grp) { + return decl_view(b, nm.f("%s.rot_dense", base), wn, "t.pairs,t.angle", RAD_I32, { N, K }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); +} + inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, std::initializer_list src, @@ -1097,10 +1129,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha const bool band = hi > kSplit; const int64_t f16_hi = band ? kSplit : hi; /* the f16 chain's rows */ RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2)); + RAD_ARCH_TRY(decl_seq_tables(b, nm, base, wn, grp)); const int64_t P = rot_parts; rot_q = decl_b(b, nm.f("%s.rot_y", base), RAD_F16, { f16_hi, P * K }); if (!rot_q) return RAD_E_INVAL; - op_rot = decl_rot_op(b, g, a, "givens_rotate", 1, f16_hi, { rot_q }); + op_rot = decl_rot_op(b, g, a, 1, f16_hi, { rot_q }); if (!op_rot) return RAD_E_INVAL; w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); @@ -1117,7 +1150,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha rot_q2 = decl_b(b, nm.f("%s.rot_q2", base), RAD_I8, { hi, P * K }); rot_s2 = decl_b(b, nm.f("%s.rot_s2", base), RAD_F32, { hi, P * (K / RAD_FP8_BLOCK) }); if (!rot_q2 || !rot_s2) return RAD_E_INVAL; - op_rot2 = decl_rot_op(b, g, a, "givens_quant_act_i8g", kSplit + 1, hi, { rot_q2, rot_s2 }); + rot_dense = decl_dense(b, nm, base, wn, N, K, grp); + if (!rot_dense) return RAD_E_INVAL; + op_rot2 = decl_dense_op(b, g, a, "i8", kSplit + 1, hi, { rot_q2, rot_s2 }); op2 = decl_gemm_q(b, kSplit + 1, hi, RAD_FP8_BLOCK, bits5 ? "w5a8i8" : "w4a8i8_asym", pb1, pb2, { w, ws }, { rot_q2, rot_s2 }, y); if (!op_rot2 || !op2) return RAD_E_INVAL; @@ -1187,7 +1222,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha 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; - op_rot = decl_rot_op(b, g, a, "givens_quant_act_fp8", 1, rows, { rot_q, rot_s }); + rot_dense = decl_dense(b, nm, base, wn, N, 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); @@ -1318,8 +1355,8 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in return; } if (paro5 && rot_split && rows > rot_split) { - RAD_ISSUE_N(c, op_rot2, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), - RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q2, r0, rows, rot_parts * K), + RAD_ISSUE_N(c, op_rot2, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_dense), + RAD_W(rot_scale), brow_slice(rot_q2, r0, rows, rot_parts * K), brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK))); RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K), brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)), @@ -1339,8 +1376,8 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s; const int64_t ak = rot_parts * K; if (paro) - RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), - RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(aq, r0, rows, ak), + RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_dense), + RAD_W(rot_scale), brow_slice(aq, r0, rows, ak), brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK)); RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak), brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK), diff --git a/docs/OPS.md b/docs/OPS.md index 42f56a32..75e73d3c 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -367,6 +367,7 @@ spelling of `act`, not the vocabulary's. | `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `givens_quant_act_fp8` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | | `givens_quant_act_i8g` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | +| `givens_dense_quant` | `M` `n` `group` `dtype` `parts` `out`:str | `x`, `tdense`w, `rscale`w → `q`, `scale` | | `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` | | `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index c901984c..c79bfa28 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -109,6 +109,7 @@ set(R4D_UNITS "r4d_gemm_w4a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w5a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" "r4d_gemm_wpa8i8_tiled|" + "r4d_givens_dense|" "r4d_gemm_w8a16_nt_m64|-DR4D_GEMM_W8_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w2a8_nt|-DR4D_GEMM_W2A8_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w4a8_nt_m64|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}" diff --git a/libr4d/r4d_givens_dense.hip b/libr4d/r4d_givens_dense.hip new file mode 100644 index 00000000..eb534220 --- /dev/null +++ b/libr4d/r4d_givens_dense.hip @@ -0,0 +1,168 @@ +// r4d_givens_dense.hip -- ParoQuant's rotation as a dense per-group matrix on the matrix cores. +// +// The Givens stages of a 128-column group compose to one orthogonal 128 x 128 matrix T, so +// y = T (x / D) is a small GEMM: out[m][j] = sum_i T[j][i] * (x[m][i] / D[i]). The sequential kernel +// (r4d_givens_quant_act_fp8.hip) does the same job in `stages` dependent LDS rounds a group and is +// latency bound (~100-130 GB/s of ~640); this one spends ~8x the multiply-adds on the f16 WMMA, which +// is 5 us of math for a 2048-row part, and quantises in the epilogue -- int8 (scale amax / 127, for the +// int8 prefill GEMMs) or E4M3 (amax / 448, for the mxfp4a8 GEMMs), the same scale grid as the +// sequential producer's. About 3x faster at prefill sizes and no slower at decode. +// +// THE MATRICES ARE THE WEIGHT: rad-convert composes them from the container's `t.pairs` / `t.angle` +// tables (r4d_layout.cpp, r4d.givens.dense) into [parts * K / 128][128 (j)][128 (i)] f16, so the +// serving side never walks a Givens network. The channel scale stays a separate table (`rscale`), a +// divide on the way in: folding 1/D into T would put entries of very different magnitude in one f16 +// matrix. +// +// ONE BLOCK A (part, group) x row chunk. The group's T (32 KiB of f16) is staged in LDS once and each +// of the block's four waves takes 16-row tiles: per k step one B fragment (the activation row's +// eight k, divided by D, as f16) meets the eight j tiles of T. The accumulators are C[j][m]: lane l +// holds column m = l & 15 and rows j = 8 * (l >> 4) + e, so a row's 128 outputs are split over lane m +// and lane m + 16 and its amax is a max over 64 registers and one xor-16 shuffle. +// +// WHAT MOVED THE TIME (selftest, 2048 rows x K 5120): the first version waited on one activation load a +// k step and spilled ~190 registers (186 us). A tile's eight loads are now issued together and the +// issue order is pinned per k step (sched_barrier), which is what keeps the A fragments from being +// hoisted whole into registers: 137 VGPRs, no spills, ~100 us. Double-buffering the next tile and +// coalescing the stores through LDS were tried and did not move it. +#include "r4d.h" +#include "r4d_emit.h" +#include "r4d_fp8_args.h" +#include "r4d_common.h" +#include "r4d_q8.h" +#include +#include +#include + +namespace { + +constexpr uint32_t kGroup = 128; +constexpr uint32_t kThreads = 128; +constexpr uint32_t kWaves = kThreads / 32; +constexpr uint32_t kTStride = kGroup + 8; // f16 per LDS row of T: 16 B pad, conflict-free b128 reads + +typedef _Float16 v8h_t __attribute__((ext_vector_type(8))); + +template +__global__ __launch_bounds__(kThreads) void givens_dense_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ tdense, const float* __restrict__ rscale, + uint8_t* __restrict__ q, float* __restrict__ s, uint32_t M, uint32_t K, uint32_t nkb, uint32_t x_ld, + uint32_t q_ld, uint32_t s_ld) { + __shared__ uint16_t Tl[kGroup * kTStride]; + __shared__ float invd[kGroup]; + const uint32_t gp = blockIdx.x, part = gp / nkb, g = gp % nkb; + const uint32_t tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + + // all sixteen loads in flight before the first LDS store: the staging is latency, not bandwidth + const uint4* tg = (const uint4*)(tdense + (size_t)gp * kGroup * kGroup); + constexpr uint32_t kStage = kGroup * kGroup / 8 / kThreads; + uint4 tv[kStage]; +#pragma unroll + for (uint32_t k = 0; k < kStage; ++k) tv[k] = tg[tid + k * kThreads]; +#pragma unroll + for (uint32_t k = 0; k < kStage; ++k) { + const uint32_t i = tid + k * kThreads, j = i / (kGroup / 8), c = i % (kGroup / 8); + *(uint4*)&Tl[j * kTStride + c * 8] = tv[k]; + } + invd[tid] = 1.0f / rscale[(size_t)part * K + g * kGroup + tid]; + __syncthreads(); + + const uint32_t h = lane >> 4, col = lane & 15; + const uint32_t Mt = (M + 15) >> 4; + const uint32_t step = gridDim.y * kWaves; + for (uint32_t tile = blockIdx.y * kWaves + wave; tile < Mt; tile += step) { + // The activation row a lane reads: lane (col, h) takes columns 8h .. 8h+7 of every 16-wide k step of + // row (tile * 16 + col). All eight k steps of a tile are loaded at once, so a tile costs one load + // latency and not eight. + uint32_t m = tile * 16 + col; + const bool live = m < M; + if (!live) m = M - 1; + const uint16_t* xr = x + (size_t)m * x_ld + g * kGroup + 8 * h; + uint4 raw[8]; +#pragma unroll + for (uint32_t ks = 0; ks < 8; ++ks) raw[ks] = *(const uint4*)(xr + ks * 16); + v8f acc[8]; +#pragma unroll + for (int jt = 0; jt < 8; ++jt) acc[jt] = (v8f)(0.f); +#pragma unroll + for (uint32_t ks = 0; ks < 8; ++ks) { + const uint32_t c0 = ks * 16 + 8 * h; + const uint32_t w[4] = { raw[ks].x, raw[ks].y, raw[ks].z, raw[ks].w }; + v8h_t bf; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const uint32_t b = (w[e >> 1] >> (16 * (e & 1))) & 0xFFFFu; + const float v = __uint_as_float(b << 16) * invd[c0 + e]; + bf[e] = (_Float16)fminf(fmaxf(v, -65504.0f), 65504.0f); + } +#pragma unroll + for (int jt = 0; jt < 8; ++jt) { + const v8h_t af = *(const v8h_t*)&Tl[(jt * 16 + col) * kTStride + c0]; + acc[jt] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(af, bf, acc[jt]); + } + __builtin_amdgcn_sched_barrier(0); // keep a k step's A fragments from being hoisted over the last + } + float amax = 0.0f; +#pragma unroll + for (int jt = 0; jt < 8; ++jt) +#pragma unroll + for (int e = 0; e < 8; ++e) amax = fmaxf(amax, fabsf(acc[jt][e])); + amax = fmaxf(amax, __shfl_xor(amax, 16)); + const float sc = amax > 0.0f ? amax * (1.0f / q8_top()) : 1.0f; + const float inv = 1.0f / sc; + if (!live) continue; + if (h == 0) s[(size_t)m * s_ld + (size_t)part * nkb + g] = sc; + uint8_t* qr = q + (size_t)m * q_ld + (size_t)part * K + g * kGroup + 8 * h; +#pragma unroll + for (int jt = 0; jt < 8; ++jt) { + const uint32_t lo = q8_pack4(acc[jt][0], acc[jt][1], acc[jt][2], acc[jt][3], inv); + const uint32_t hi = q8_pack4(acc[jt][4], acc[jt][5], acc[jt][6], acc[jt][7], inv); + *(uint2*)(qr + jt * 16) = make_uint2(lo, hi); + } + } +} + +} // namespace + +// x [M][K] bf16, `x_ld` elements a row (0 = K) +// tdense [parts * K/128][128][128] f16, T[j][i] of each (part, group), laid out by r4d_layout.cpp +// rscale [parts][K] f32, the factor the stored row was multiplied by +// q [M][parts * K] int8 or E4M3, `q_ld` elements a row (0 = parts * K) +// s [M][parts * K/128] f32, `s_ld` elements a row (0 = parts * K/128) +enum { GD_X = 0, GD_T = 1, GD_RSCALE = 2, GD_Q = 3, GD_S = 4 }; + +static int givens_dense_body(const RadArgs* a, const R4dSink& sk) { + const RadTensor* x = r4d_opt(a, GD_X); + const RadTensor* t = r4d_opt(a, GD_T); + const RadTensor* rs = r4d_opt(a, GD_RSCALE); + const RadTensor* q = r4d_opt(a, GD_Q); + const RadTensor* sc = r4d_opt(a, GD_S); + if (!x || !t || !rs || !q || !sc) return R4D_NO(RAD_E_INVAL); + if (x->rank < 2 || q->rank != 2 || sc->rank != 2 || t->rank != 2 || rs->rank != 2) + return R4D_NO(RAD_E_SHAPE); + if (t->dtype != RAD_F16 || rs->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + const bool i8 = q->dtype == RAD_I8; + if (!i8 && q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE); + const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); + const long long parts = r4d_geti_or(a, "parts", 1), nkb = K / kGroup; + if (r4d_geti_or(a, "group", kGroup) != kGroup || K % kGroup || parts < 1) return R4D_NO(RAD_E_SHAPE); + if (q->shape[0] != M || q->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE); + if (sc->shape[0] != M || sc->shape[1] != parts * nkb) return R4D_NO(RAD_E_SHAPE); + // tdense is a packed blob: its byte count is the layout hook's ([parts * K, 128] f16), not a shape to check + if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); + if (!r4d_aligned(t->data, 16) || !r4d_aligned(x->data, 16) || !r4d_aligned(q->data, 8)) + return R4D_NO(RAD_E_ALIGN); + const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); + if (xp < 0 || qp < 0 || sp < 0 || (xp * 2) % 16) return R4D_NO(RAD_E_STRIDE); + const long long mt = (M + 15) / 16; + const uint32_t gy = (uint32_t)std::max(1, (mt + 4 * kWaves - 1) / (4 * kWaves)); + const dim3 grid((uint32_t)(parts * nkb), gy); +#define GD_EMIT(I8_) R4D_EMIT(sk, (givens_dense_kernel), grid, dim3(kThreads), 0, \ + (const uint16_t*)x->data, (const uint16_t*)t->data, (const float*)rs->data, (uint8_t*)q->data, \ + (float*)sc->data, (uint32_t)M, (uint32_t)K, (uint32_t)nkb, (uint32_t)xp, (uint32_t)qp, (uint32_t)sp) + const int rc = i8 ? GD_EMIT(true) : GD_EMIT(false); +#undef GD_EMIT + if (rc != RAD_OK) return rc; + return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK; +} +R4D_ENTRY(r4d_rad_givens_dense_quant, givens_dense_body) diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 17ba87e0..02554bb3 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -571,6 +571,90 @@ extern "C" int r4d_rad_unrelayout_w5(const RadParam* p, int n_p, int operand, co return RAD_OK; } +/* ---- givens_dense: ParoQuant's rotation tables composed into one dense matrix a (part, group). + * + * A "givens" weight stores its rotation as pairs (i32 [P*S, K]) and angles (f32 [P*S, K/2]); the dense + * kernel (r4d_givens_dense.hip) applies it as T (x / D), T being the composition of the group's S + * stages. The blob is [P * K/128][128 (j)][128 (i)] f16, T[j][i] = output j of the network fed the unit + * vector e_i, so a (part, group) is 32 KiB the kernel stages whole. Composed in f32 in the order the + * stages are applied (stage 0 first), a' = a c + b s, b' = b c - a s -- libref's loop -- and rounded to + * f16 once. Operand 1 of givens_dense_quant; everything else stays as stored. */ +namespace { +constexpr int GD_OPERAND = 1; +constexpr long long GD_GROUP = 128; + +int gd_geom(const RadParam* p, int n_p, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, + long long* P, long long* S, long long* K) { + if (n != 2 || std::strncmp(r4d_enc::role(enc, sel, 0), "t.pairs", RAD_ENC_STR) != 0 || + std::strncmp(r4d_enc::role(enc, sel, 1), "t.angle", RAD_ENC_STR) != 0) return RAD_E_SHAPE; + *K = r4d_pgeti_or(p, n_p, "n", 0); + *P = r4d_pgeti_or(p, n_p, "parts", 1); + if (*K <= 0 || *K % GD_GROUP || *P < 1) return RAD_E_SHAPE; + if (pl[0].rank != 2 || pl[0].shape[1] != *K || pl[0].shape[0] % *P || pl[0].dtype != RAD_I32) + return RAD_E_SHAPE; + *S = pl[0].shape[0] / *P; + if (*S < 1 || !dims(pl[1], *P * *S, *K / 2) || pl[1].dtype != RAD_F32) return RAD_E_SHAPE; + return RAD_OK; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_gdense(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* pl, int n, RadLayout* out) { + if (!out || !pl) return RAD_E_INVAL; + if (operand != GD_OPERAND) return RAD_E_UNSUPPORTED; + long long P, S, K; + const int rc = gd_geom(p, n_p, enc, sel, pl, n, &P, &S, &K); + if (rc != RAD_OK) return rc; + fill(out, "r4d.givens.dense.g128", RAD_F16, P * K, GD_GROUP, P * K * GD_GROUP * 2); + return RAD_OK; +} + +extern "C" int r4d_rad_relayout_gdense(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + int rc = r4d_rad_layout_gdense(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes) return RAD_E_SHAPE; + long long P, S, K; + rc = gd_geom(p, n_p, enc, sel, pl, n, &P, &S, &K); + if (rc != RAD_OK) return rc; + const int32_t* pairs = (const int32_t*)pdata(pl[0]); + const float* ang = (const float*)pdata(pl[1]); + uint16_t* t = (uint16_t*)dst; + const long long nkb = K / GD_GROUP, half = GD_GROUP / 2; + std::vector ia((size_t)(S * half)), ib((size_t)(S * half)); + std::vector cs((size_t)(S * half)), sn((size_t)(S * half)); + std::vector v((size_t)GD_GROUP); + for (long long pt = 0; pt < P; ++pt) + for (long long g = 0; g < nkb; ++g) { + for (long long st = 0; st < S; ++st) + for (long long j = 0; j < half; ++j) { + const long long row = pt * S + st, o = (size_t)(st * half + j); + const long long a = pairs[row * K + g * GD_GROUP + 2 * j] - g * GD_GROUP; + const long long b = pairs[row * K + g * GD_GROUP + 2 * j + 1] - g * GD_GROUP; + if (a < 0 || a >= GD_GROUP || b < 0 || b >= GD_GROUP || a == b) return RAD_E_FORMAT; + ia[(size_t)o] = (int)a; + ib[(size_t)o] = (int)b; + const float th = ang[row * (K / 2) + g * half + j]; + cs[(size_t)o] = std::cos(th); + sn[(size_t)o] = std::sin(th); + } + uint16_t* tg = t + (size_t)(pt * nkb + g) * GD_GROUP * GD_GROUP; + for (long long i = 0; i < GD_GROUP; ++i) { + std::fill(v.begin(), v.end(), 0.0f); + v[(size_t)i] = 1.0f; + for (long long o = 0; o < S * half; ++o) { + const float va = v[(size_t)ia[(size_t)o]], vb = v[(size_t)ib[(size_t)o]]; + v[(size_t)ia[(size_t)o]] = va * cs[(size_t)o] + vb * sn[(size_t)o]; + v[(size_t)ib[(size_t)o]] = vb * cs[(size_t)o] - va * sn[(size_t)o]; + } + for (long long j = 0; j < GD_GROUP; ++j) tg[j * GD_GROUP + i] = f32_to_f16(v[(size_t)j]); + } + } + return RAD_OK; +} + /* ---- w8: i8 codes, symmetric about zero, an f16 scale a group. The f16 kernel (a16) reads the * code offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed with a * bare f16 scale plane. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 3609719f..abc57929 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -220,6 +220,8 @@ int r4d_rad_gemm_w5a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a16asym_m64(const RadArgs*, RadStream); int r4d_rad_gemm_w4a8i8_tiled(const RadArgs*, RadStream); int r4d_rad_gemm_w5a8i8_tiled(const RadArgs*, RadStream); +int r4d_rad_givens_dense_quant(const RadArgs*, RadStream); +int r4d_rad_givens_dense_quant_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gemm_w8a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_tiled (const RadArgs*, RadStream); @@ -401,6 +403,10 @@ int r4d_rad_relayout_w5(const RadParam*, int, int, const RadEncoding*, const int const RadTensor*, int, void*, int64_t); int r4d_rad_unrelayout_w5(const RadParam*, int, int, const RadEncoding*, const int*, const void*, int64_t, const RadTensor*, int); +int r4d_rad_layout_gdense(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_gdense(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 5b841e59..202bc1eb 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1079,6 +1079,26 @@ static const RadOperandSpec oGivensQuantAct[] = { { "scale", RAD_OPD_OUT, 0 }, }; +/* `givens_dense_quant` is givens_quant_act_fp8 with the rotation done by a dense per-group matrix on the + * matrix cores (r4d_givens_dense.hip). The matrices are the weight -- rad-convert composes them from the + * givens tables (r4d_rad_layout_gdense) -- so its tables are `tdense` and the channel scale `rscale`. + * `out` is the quantiser: "i8" (scale amax / 127) or "fp8" (E4M3, amax / 448), as q's dtype says. */ +static const RadParamSpec pGivensDense[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + { "group", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "parts", RAD_P_INT, RAD_REQUIRED }, + { "out", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec oGivensDense[] = { + { "x", RAD_OPD_IN, 0 }, + { "tdense", RAD_OPD_WEIGHT, 0 }, + { "rscale", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, +}; + /* `gram_accum` is a NEW OP and this plugin fixes its schema. It is the calibration half of GPTQ: * `h += x^T x` over an E4M3 activation, accumulated across every launch of a corpus. * @@ -2346,6 +2366,13 @@ static const RadOpSchema kSchemas[] = { "fused projection's pieces were each rotated on their own. Only a weight stored with " "the \"givens\" transform reads the result; it is NOT quant_act_fp8's output in either " "direction."), + SCHEMA("givens_dense_quant", pGivensDense, oGivensDense, + "ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / " + "rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column " + "group) that its Givens stages compose to, then the block-scaled quantiser `out` names " + "(\"i8\": scale amax / 127, round to nearest; \"fp8\": E4M3, amax / 448). q is [M, parts * n] " + "and scale [M, parts * n / group]; tdense is [parts * n, 128]. The same activation as " + "givens_quant_act_i8g / _fp8 up to the f16 rounding of T."), SCHEMA("givens_quant_act_i8g", pGivensQuantAct, oGivensQuantAct, "givens_quant_act_fp8 with an int8 output: the same channel scale and rotations, then " "quant_act_i8g's quantiser (scale = amax / 127 per `group`, round to nearest). For the int8 " @@ -3015,6 +3042,9 @@ static const RadConstraint cQuantActFp8[] = { * straddle the end of a row: the ragged tail the unrotated kernel writes zero-padded would mix * real values with padding inside one butterfly, and there is no weight block on the other side * that was rotated the same way. */ +static const RadConstraint cGivensDense[] = { + C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), C_IN("out", "i8 fp8"), +}; static const RadConstraint cHadQuantActFp8[] = { C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; @@ -5258,6 +5288,18 @@ static const RadKernelInfo kKernels[] = { r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, r4d_rad_givens_quant_act_i8g_describe }, +{ "givens_dense_quant", "givens_dense_quant", "quant", + "ParoQuant's rotation as a dense 128 x 128 f16 matrix a (part, group) on the matrix cores, then " + "per-(row, 128-column) symmetric quantisation to int8 or E4M3, once for each rotated part", + "n a multiple of 128 and group 128; the matrices are the weight, composed from the givens tables at " + "convert time", + "bf16 in, int8 or E4M3 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale (amax/127 " + "or amax/448) per (row, part, 128 columns); f16 matrices and f32 channel scales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGivensDense), NOTUNE, + nullptr, nullptr, r4d_rad_givens_dense_quant, nullptr, r4d_rad_layout_gdense, r4d_rad_relayout_gdense, + nullptr, nullptr, nullptr, r4d_rad_givens_dense_quant_describe }, + { "givens_rotate", "givens_rotate", "quant", "the channel scale and ParoQuant's Givens rotations, once for each rotated part, to f16", "n a multiple of 128 and group 128: a rotation group cannot straddle the end of a row", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index c2f1f4f2..4c46a3ef 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3775,12 +3775,13 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ * must sit within the E4M3 grid of the reference (half a step at the top of the range is 1/16 of * the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, - bool rot_only = false, bool i8 = false) { - const char* row = rot_only ? "givens_rotate" : i8 ? "givens_quant_act_i8g" : "givens_quant_act_fp8"; + bool rot_only = false, bool i8 = false, bool dense = false) { + const char* row = dense ? "givens_dense_quant" : rot_only ? "givens_rotate" + : i8 ? "givens_quant_act_i8g" : "givens_quant_act_fp8"; if (!sel(row)) return; char nm[160]; - std::snprintf(nm, sizeof nm, "%s numeric M=%lld K=%lld parts=%d stages=%d", row, (long long)M, - (long long)K, parts, stages); + std::snprintf(nm, sizeof nm, "%s %s numeric M=%lld K=%lld parts=%d stages=%d", row, + dense ? (i8 ? "i8" : "fp8") : "", (long long)M, (long long)K, parts, stages); const RadKernelInfo* r = find(pl, row); if (!r || !r->launch) { ok(nm, false, "row absent"); return; } const int64_t G = 128, ng = K / G; @@ -3818,6 +3819,7 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in void* d_r = dalloc(rs.size() * 4); void* d_q = dalloc((size_t)(M * parts * K) * (rot_only ? 2 : 1)); void* d_s = dalloc((size_t)(M * parts * ng) * 4); + void* d_t = nullptr; if (!d_x || !d_p || !d_a || !d_r || !d_q || !d_s) { ok(nm, false, "hipMalloc failed"); return; } st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_p, pairs.data(), pairs.size() * 4, hipMemcpyHostToDevice); @@ -3832,6 +3834,29 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in if (rot_only) ts.pop_back(); std::vector ps = { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"), PI("stages", stages), PI("parts", parts) }; + if (dense) { + // the matrices come out of the row's own layout hook, from the same tables, as rad-convert makes them + Planes pp; + pp.enc = rad_enc_plain(RAD_BF16); + rad_enc_add_table(&pp.enc, "t.pairs", RAD_I32, NPS, K); + rad_enc_add_table(&pp.enc, "t.angle", RAD_F32, NPS, K / 2); + pp.data.assign(3, {}); + pp.rows = { 0, NPS, NPS }; + pp.cols = { 0, K, K / 2 }; + pp.data[1].assign((const uint8_t*)pairs.data(), (const uint8_t*)(pairs.data() + pairs.size())); + pp.data[2].assign((const uint8_t*)ang.data(), (const uint8_t*)(ang.data() + ang.size())); + std::vector lp = { PI("n", K), PI("parts", parts) }; + std::vector blob; + const int rl = stored(r, lp, 1, pp, { "t.pairs", "t.angle" }, &blob); + if (rl != RAD_OK) { ok(nm, false, "relayout rc " + std::to_string(rl)); return; } + d_t = dalloc(blob.size()); + if (!d_t) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_t, blob.data(), blob.size(), hipMemcpyHostToDevice); + ts = { T(d_x, RAD_BF16, { M, K }), T(d_t, RAD_F16, { parts * K, 128 }), T(d_r, RAD_F32, { (int64_t)parts, K }), + T(d_q, i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, { M, parts * K }), T(d_s, RAD_F32, { M, parts * ng }) }; + ps = { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"), PI("parts", parts), + PS("out", i8 ? "i8" : "fp8") }; + } RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); @@ -3877,9 +3902,25 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in } } } - char d[96]; + char d[128]; std::snprintf(d, sizeof d, "scale rel %.2e, value/amax %.3f", worst_scale, worst_val); - ok(nm, rot_only ? worst_val < 1e-3 : (worst_scale < 1e-4 && worst_val < (i8 ? 0.01 : 0.07)), d); + if (M >= 1024) { // a prefill chunk: say how fast it ran + hipEvent_t e0, e1; + st_ev_create(&e0); st_ev_create(&e1); + for (int i = 0; i < 3; ++i) r->launch(&a, nullptr); + st_ev_record(e0, nullptr); + for (int i = 0; i < 20; ++i) r->launch(&a, nullptr); + st_ev_record(e1, nullptr); + st_ev_sync(e1); + float ms = 0; + st_ev_elapsed(&ms, e0, e1); + st_ev_destroy(e0); st_ev_destroy(e1); + std::printf(" %.1f us a launch (%s)\n", (double)ms * 50.0, d); + } + // the dense form carries f16 matrices: its scale reads ~1e-3 off the f32 network's, its values stay within the + // quantiser's own step + ok(nm, rot_only ? worst_val < 1e-3 + : (worst_scale < (dense ? 3e-3 : 1e-4) && worst_val < (i8 ? 0.01 : 0.07)), d); } @@ -13148,6 +13189,22 @@ static void device_phase(const Plugin& pl) { givens_numeric(pl, 5, 5120, 2, 8, false, true); givens_numeric(pl, 64, 17408, 1, 8, false, true); givens_numeric(pl, 300, 6144, 2, 8, false, true); + givens_numeric(pl, 2048, 5120, 1, 8, false, true); + givens_numeric(pl, 2048, 5120, 2, 8, false, true); + givens_numeric(pl, 2048, 17408, 1, 8, false, true); + } + if (sel("givens_dense_quant")) { + if (!g_case) std::printf("\nParoQuant's rotation as dense per-group matrices, int8 and E4M3 output, against libm's rotation\n"); + for (int i8 = 0; i8 < 2; ++i8) { + givens_numeric(pl, 1, 128, 1, 8, false, i8, true); + givens_numeric(pl, 5, 5120, 2, 8, false, i8, true); + givens_numeric(pl, 8, 5120, 2, 8, false, i8, true); + givens_numeric(pl, 16, 5120, 1, 8, false, i8, true); + givens_numeric(pl, 300, 6144, 2, 8, false, i8, true); + givens_numeric(pl, 2048, 5120, 1, 8, false, i8, true); + givens_numeric(pl, 2048, 5120, 2, 8, false, i8, true); + givens_numeric(pl, 2048, 17408, 1, 8, false, i8, true); + } } if (sel("givens_quant_act_fp8")) { if (!g_case) std::printf("\nParoQuant's rotate-and-quantise, against an f64 rotation\n"); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index d1c03330..560f55b4 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -102,6 +102,7 @@ int ref_quant_act_fp8 (const RadArgs*, RadStream); int ref_had_quant_act_fp8 (const RadArgs*, RadStream); int ref_givens_quant_act_fp8(const RadArgs*, RadStream); int ref_givens_quant_act_i8g(const RadArgs*, RadStream); +int ref_givens_dense_quant(const RadArgs*, RadStream); int ref_givens_rotate(const RadArgs*, RadStream); int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); int ref_gated_quant_fp8 (const RadArgs*, RadStream); @@ -233,6 +234,7 @@ REF_SHAPE_FN(ref_quant_act_fp8); REF_SHAPE_FN(ref_had_quant_act_fp8); REF_SHAPE_FN(ref_givens_quant_act_fp8); REF_SHAPE_FN(ref_givens_quant_act_i8g); +REF_SHAPE_FN(ref_givens_dense_quant); REF_SHAPE_FN(ref_givens_rotate); REF_SHAPE_FN(ref_rmsnorm_quant_fp8); REF_SHAPE_FN(ref_gated_quant_fp8); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index f0e60573..897b4894 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -495,6 +495,52 @@ static int givens_body(const RadArgs* a, bool quant, bool i8 = false) { int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { return givens_body(a, true); } int ref_givens_quant_act_i8g(const RadArgs* a, RadStream) { return givens_body(a, true, true); } +/* The same activation with the rotation applied as the dense matrix: y[j] = sum_i T[j][i] * x[i] / D[i] over + * each (part, 128-column group), then the quantiser `q`'s dtype names. T is the weight, f16, one [128, 128] + * matrix a (part, group) -- what r4d_rad_relayout_gdense composes from the givens tables. */ +int ref_givens_dense_quant(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *tm = &a->t[1], *sc = &a->t[2], *q = &a->t[3], *s = &a->t[4]; + const int64_t n = p_int(a, "n", 0), P = p_int(a, "parts", 1), g = p_int(a, "group", 0); + if (n <= 0 || P <= 0 || g != 128 || n % g != 0) return RAD_E_SHAPE; + const bool i8 = q->dtype == RAD_I8; + if (!i8 && q->dtype != RAD_F8E4M3) return RAD_E_DTYPE; + const int64_t rows = numel(x) / n, ngrp = n / g; + if (rows <= 0 || numel(tm) < P * n * g || numel(sc) < P * n || numel(q) < rows * P * n || + numel(s) < rows * P * ngrp) return RAD_E_SHAPE; + const float qmax = i8 ? 127.0f : 448.0f; + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n); + const int64_t xs = laststride(x), qs = laststride(q); + std::vector in((size_t)g), y((size_t)g); + for (int64_t p = 0; p < P; ++p) + for (int64_t gi = 0; gi < ngrp; ++gi) { + for (int64_t i = 0; i < g; ++i) + in[(size_t)i] = ldt(x, xb + (gi * g + i) * xs) / ldt(sc, p * n + gi * g + i); + float amax = 0.0f; + for (int64_t j = 0; j < g; ++j) { + double acc = 0.0; + for (int64_t i = 0; i < g; ++i) + acc += (double)ldt(tm, ((p * ngrp + gi) * g + j) * g + i) * (double)in[(size_t)i]; + y[(size_t)j] = (float)acc; + amax = std::max(amax, std::fabs(y[(size_t)j])); + } + const float scl = amax > 0.0f ? amax * (1.0f / qmax) : 1.0f; + const float inv = 1.0f / scl; + for (int64_t j = 0; j < g; ++j) { + float v = y[(size_t)j] * inv; + if (v > qmax) v = qmax; + if (v < -qmax) v = -qmax; + if (i8) v = std::nearbyint(v); + st_dt(q->dtype, q->data, qb + (p * n + gi * g + j) * qs, v); + } + stt(s, rowoff(s, r, P * ngrp) + (p * ngrp + gi) * laststride(s), scl); + } + } + return RAD_OK; +} + /* The same channel scale and rotations with NO quantiser: y = the rotated row in y's dtype, `parts` * copies side by side. For a weight whose GEMM reads a 16-bit activation (w5a16). */ int ref_givens_rotate(const RadArgs* a, RadStream) { return givens_body(a, false); } diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 56debdd1..30430f8a 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -206,6 +206,10 @@ static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; * resolved, moved and placed with the weight they belong to. */ static const RadParamSpec pGivensQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INT("stages"), P_INT("parts") }; +static const RadParamSpec pGivensDense[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), + P_INT("parts"), P_STR("out") }; +static const RadOperandSpec oGivensDense[] = { OPD("x"), WGT("tdense"), WGT("rscale"), OUT("q"), + OUT("scale") }; static const RadOperandSpec oGivensRotate[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), OUT("y") }; static const RadOperandSpec oGivensQuant[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), @@ -811,6 +815,13 @@ static const RadOpSchema kSchemas[] = { "stages) of `pairs` and `angle` and row p of `rscale`: a fused projection's pieces were each " "rotated on their own. Only a weight stored with the \"givens\" transform reads the result; " "it is NOT quant_act_fp8's output in either direction." }, +{ "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense), + "ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / " + "rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column " + "group) that its Givens stages compose to, then the block-scaled quantiser `out` names " + "(\"i8\": scale amax / 127, round to nearest; \"fp8\": E4M3, amax / 448). q is [M, parts * n] " + "and scale [M, parts * n / group]; tdense is [parts * n, 128]. The same activation as " + "givens_quant_act_i8g / _fp8 up to the f16 rounding of T." }, { "givens_quant_act_i8g", ARR(pGivensQuant), ARR(oGivensQuant), "givens_quant_act_fp8 with an int8 output: the same channel scale and rotations, then " "quant_act_i8g's quantiser (scale = amax / 127 per `group`, round to nearest). For the int8 " @@ -1188,6 +1199,10 @@ SIMPLE("ref_givens_quant_act_fp8", "givens_quant_act_fp8", "quant", "channel scale and Givens rotations per part, then the block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; int32 pairs, f32 angles and channel scales", ref_givens_quant_act_fp8), +SIMPLE("ref_givens_dense_quant", "givens_dense_quant", "quant", + "the rotation as a dense per-group matrix, then the block-scaled int8 or E4M3 quantiser", + "float in, int8 or fp8_e4m3 out, f32 scale per group; f16 matrices and f32 channel scales", + ref_givens_dense_quant), SIMPLE("ref_givens_quant_act_i8g", "givens_quant_act_i8g", "quant", "channel scale and Givens rotations per part, then the block-scaled int8 quantiser", "float in, int8 out, f32 scale per group; int32 pairs, f32 angles and channel scales", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index d631961b..f188cb1b 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -840,6 +840,10 @@ int ref_givens_quant_act_i8g_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ } +int ref_givens_dense_quant_shape(const RadParam*, int, int, RadOpdDesc*) { + return RAD_E_UNSUPPORTED; /* a composed rotation cannot be drawn: see givens_quant_act_fp8 */ +} + int ref_givens_rotate_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ } diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index c33ab599..5ca8af2d 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -261,7 +261,7 @@ TEST(op_vocabulary) { "embed_lookup_q", "cast", "scale_rows", "softmax", - "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "givens_quant_act_i8g", "givens_rotate", "had_quant_act_i8", + "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "givens_quant_act_i8g", "givens_dense_quant", "givens_rotate", "had_quant_act_i8", "gram_accum", /* The fused fp8 forms. A host run needs EVERY op covered, so these are what stands * between a host-backend run and "site 'host' is unavailable for this band". */ From ec65b8cbeb1c8cc28d931c95982d9e1eab880e68 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 15:36:31 +0000 Subject: [PATCH 14/17] ParoQuant: drop the sequential rotate-and-quantise ops (givens_quant_act_fp8 / givens_quant_act_i8g): givens_dense_quant replaces them; the rotate-only f16 kernel keeps its own file --- arch/common/rad_fp8.h | 4 +- data/recipes/q38-27b-paro-mxfp4-df2.recipe | 2 +- docs/GUIDE.md | 2 +- docs/OPS.md | 22 +- libr4d/CMakeLists.txt | 2 +- libr4d/r4d_gemm_wpa8i8_tiled.hip | 2 +- libr4d/r4d_givens_dense.hip | 2 +- libr4d/r4d_givens_quant_act_fp8.hip | 239 --------------------- libr4d/r4d_givens_rotate.hip | 174 +++++++++++++++ libr4d/r4d_layout.cpp | 2 +- libr4d/r4d_plugin.h | 4 - libr4d/r4d_rows.cpp | 69 +----- libr4d/r4d_selftest.cpp | 25 +-- libref/ref_ops.h | 4 - libref/ref_quant.cpp | 68 ++---- libref/ref_registry.cpp | 33 +-- libref/ref_shapes.cpp | 12 +- tests/ref_test.cpp | 138 +++++++----- 18 files changed, 318 insertions(+), 486 deletions(-) delete mode 100644 libr4d/r4d_givens_quant_act_fp8.hip create mode 100644 libr4d/r4d_givens_rotate.hip diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index eaffb755..2ae94681 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -692,8 +692,8 @@ struct LinearFP8 { bool mx = false; rad_weight wref = 0; /* ...ROTATED (ParoQuant), a variant of `mx`: the same GEMM over an activation that - * `givens_quant_act_fp8` made from the input's bf16 plane -- the channel scale, the Givens - * stages and the E4M3 quantiser in one pass, once for each rotated PART of a fused projection + * `givens_dense_quant` made from the input's bf16 plane -- the channel scale, the rotation (a + * dense per-group matrix) and the E4M3 quantiser in one pass, once for each rotated PART of a fused projection * (gate|up, qkv|z: each piece was rotated on its own) -- into this linear's own code and * scale planes, `parts` copies side by side. The tables are views of the weight's own planes. * The GEMM takes the parts' row bounds as `pb1`/`pb2` and meets copy p with part p's rows. */ diff --git a/data/recipes/q38-27b-paro-mxfp4-df2.recipe b/data/recipes/q38-27b-paro-mxfp4-df2.recipe index 2059d764..bf017745 100644 --- a/data/recipes/q38-27b-paro-mxfp4-df2.recipe +++ b/data/recipes/q38-27b-paro-mxfp4-df2.recipe @@ -10,7 +10,7 @@ # projection the Givens pairs and angles of 8 stages inside groups of 128 columns, and the channel # scales. A fused gate|up or qkv|z keeps one set of tables a checkpoint tensor (parts). rad-convert # writes them as planes of the weight; the GEMM is the plain MXFP4 one, and the activation is -# rotated in front of it (givens_quant_act_fp8) -- nothing is re-quantised, so the weights are the +# rotated in front of it (givens_dense_quant) -- nothing is re-quantised, so the weights are the # release's to the bit. # # What the checkpoint does NOT ship in a form the architecture declares gets a rule. The release is diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 66e2126a..3734a186 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -350,7 +350,7 @@ by weight, so their quantised linears need no recipe rule: | `quantization_config` | read as | | |---|---|---| | `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) | -| `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_quant_act_fp8` and the ordinary MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule | +| `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_dense_quant` and the ordinary MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule | | `paroquant`, `format int5-bitplane` (bits 5, group 128) and z-lab's plain `paroquant` (bits 4, group 128) | `u5*f16[1x128]-u8[1x128]/givens` and `u4*f16[1x128]-u8[1x128]/givens` | the AWQ-packed low nibbles (plus the fifth-bit plane) re-laid as a code bit stream along K, the f16 scales and the integer zero points transposed to `[N, K/128]`, and the rotation as the `givens` tables above. Convert-time only; served by `givens_rotate` and `gemm_nt_q` at `w5a16` / `w4a16_asym` over an f16 activation (docs/OPS.md) | | `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped | diff --git a/docs/OPS.md b/docs/OPS.md index 75e73d3c..cf285453 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -365,33 +365,35 @@ spelling of `act`, not the vocabulary's. |---|---|---| | `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | -| `givens_quant_act_fp8` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | -| `givens_quant_act_i8g` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | | `givens_dense_quant` | `M` `n` `group` `dtype` `parts` `out`:str | `x`, `tdense`w, `rscale`w → `q`, `scale` | | `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` | | `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | -### `givens_quant_act_fp8`: ParoQuant's rotated activation +### `givens_dense_quant`: ParoQuant's rotated activation A weight stored with the `givens` transform (`abi/rad_encoding.h`) is `v = w . D . G_1 ... G_S`: the channel scale `D` and `S` stages of disjoint pairwise rotations were applied to each row BEFORE it was quantised (ParoQuant, z-lab), so the product the GEMM contracts is `` with `x' = x . D^-1 . G_1 ... G_S` -- the activation takes the same rotation, forward, once a token. -`givens_quant_act_fp8` is that: `x / rscale`, then for each stage `a' = a cos t + b sin t, -b' = b cos t - a sin t` over its pairs, then `quant_act_fp8`'s quantiser (scale `amax / 448` per -`group` columns). The pairs are column indices of the row and each pair lies inside ONE scale group -(ParoQuant's are within groups of 128), so the kernel rotates a group at a time and the quantiser -sees the rotated group. The consumer is the plain `gemm_nt_q` at `mxfp4a8`; nothing in the weight's -codes or exponents changed. +`givens_dense_quant` is that: `x / rscale`, then the rotation, then a block-scaled quantiser (`out` +names it: `fp8` is `quant_act_fp8`'s, scale `amax / 448`; `i8` is `quant_act_i8g`'s, scale +`amax / 127`, round to nearest) per `group` columns. The rotation is applied as ONE dense 128 x 128 +f16 matrix a (part, group) -- `tdense`, `[parts * n, 128]` -- the composition of the group's `stages` +rounds `a' = a cos t + b sin t, b' = b cos t - a sin t` over its pairs. A weight's `pairs` and `angle` +tables are column indices and angles of the row and each pair lies inside ONE scale group (ParoQuant's +are within groups of 128), so the matrices are the weight's own: rad-convert's layout hook for this op +composes them from the tables (`r4d_rad_layout_gdense`). The consumers are `gemm_nt_q` at `mxfp4a8` +(`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out` i8); nothing in the weight's codes or exponents +changed. A fused projection (gate|up, qkv|z) was rotated PER CHECKPOINT TENSOR, so it has `parts` rotated copies of the activation, written side by side -- `q` is `[M, parts * n]`, `scale` `[M, parts * n / group]` -- and `pairs` and `angle` stack the parts' `stages` rows each, `rscale` one row a part. `gemm_nt_q` then takes `pb1` and `pb2`, the row bounds of the weight's parts: its rows `[0, pb1)`, `[pb1, pb2)` and `[pb2, N)` meet copy 0, 1 and 2, and `a`/`a_scale` are the wide -planes. `givens_rotate` is the same rotation with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`; their GEMM serves any `M` (rows past 64 run as chunks of 64). `givens_quant_act_i8g` is the rotation with `quant_act_i8g`'s quantiser (scale `amax / 127` per `group`), for `w5a8i8` / `w4a8i8_asym`. `pb1` absent is one part; `pb2` absent ends the second part at `N`. The `mxfp4a8` rows and the +planes. `givens_rotate` is the same rotation done stage by stage, with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`; their GEMM serves any `M` (rows past 64 run as chunks of 64). The int8 activation of `w5a8i8` / `w4a8i8_asym` is `givens_dense_quant`'s at `out` `i8`. `pb1` absent is one part; `pb2` absent ends the second part at `N`. The `mxfp4a8` rows and the asymmetric 4- and 5-bit rows (`w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`) read them, and the host rows that do not (`libavx`) refuse a call that names one rather than contract against the wrong copy. diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index c79bfa28..90e68a0b 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -126,7 +126,7 @@ set(R4D_UNITS "r4d_gemm_fp8a16_nt_m1|" "r4d_gemm_fp8a8|" "r4d_quant_act_fp8|" - "r4d_givens_quant_act_fp8|" + "r4d_givens_rotate|" "r4d_fused_quant_fp8|" "r4d_gram_accum_fp8|" "r4d_qsa_block_key_bf16|" diff --git a/libr4d/r4d_gemm_wpa8i8_tiled.hip b/libr4d/r4d_gemm_wpa8i8_tiled.hip index b098f01e..ec0fdda2 100644 --- a/libr4d/r4d_gemm_wpa8i8_tiled.hip +++ b/libr4d/r4d_gemm_wpa8i8_tiled.hip @@ -3,7 +3,7 @@ // // dequant(Wq)[n][k] = scale[n][k/128] * (code[n][k] - zero[n][k/128]), code in 0..15 or 0..31 // -// -- ParoQuant's int4 (z-lab) and int5 once the activation has been rotated (givens_quant_act_i8g) -- in +// -- ParoQuant's int4 (z-lab) and int5 once the activation has been rotated (givens_dense_quant) -- in // 16x16x16 int8 WMMA, which issues at the fp8 instruction's rate. The f16 skinny kernel these weights // also serve (r4d_gemm_w5a16_nt_m64) is capped by the f16 matrix instruction at about 75 TF/s; this is the // tall-tile form with no such ceiling, built on r4d_gemm_mxfp4a8_tiled.hip's arrangement: diff --git a/libr4d/r4d_givens_dense.hip b/libr4d/r4d_givens_dense.hip index eb534220..9d0a3f04 100644 --- a/libr4d/r4d_givens_dense.hip +++ b/libr4d/r4d_givens_dense.hip @@ -2,7 +2,7 @@ // // The Givens stages of a 128-column group compose to one orthogonal 128 x 128 matrix T, so // y = T (x / D) is a small GEMM: out[m][j] = sum_i T[j][i] * (x[m][i] / D[i]). The sequential kernel -// (r4d_givens_quant_act_fp8.hip) does the same job in `stages` dependent LDS rounds a group and is +// (r4d_givens_rotate.hip) does the same job in `stages` dependent LDS rounds a group and is // latency bound (~100-130 GB/s of ~640); this one spends ~8x the multiply-adds on the f16 WMMA, which // is 5 us of math for a 2048-row part, and quantises in the epilogue -- int8 (scale amax / 127, for the // int8 prefill GEMMs) or E4M3 (amax / 448, for the mxfp4a8 GEMMs), the same scale grid as the diff --git a/libr4d/r4d_givens_quant_act_fp8.hip b/libr4d/r4d_givens_quant_act_fp8.hip deleted file mode 100644 index 58208f4c..00000000 --- a/libr4d/r4d_givens_quant_act_fp8.hip +++ /dev/null @@ -1,239 +0,0 @@ -// ParoQuant's activation side: channel scale, Givens rotations, then the per-(row, 128-column) -// symmetric E4M3 quantiser of r4d_quant_act_fp8.hip. The weight it pairs with is stored as -// v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product with -// x' = x . D^-1 . G_1 ... G_S is : the rotation is the activation's to do, once a token, and -// the weight is read by the plain MXFP4 GEMM unchanged. -// -// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- -// that is how the checkpoint is trained, and the converter and the loader (r4d_rad_relayout_givens_pairs) -// refuse one that does -- so a group is a closed system: its 128 values are rotated by S stages of 64 disjoint pairs and then quantised -// with ONE scale. A wave owns a group. The values sit in LDS (128 floats a wave, no barrier -// needed: a wave's LDS accesses are in order, and the pairs of a stage are disjoint so no two lanes -// touch one address), each lane takes two pairs a stage, and the absmax is a wave reduction. The -// quantiser after it is quant_act_fp8's, byte for byte. -// -// PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row yields `parts` rotated -// copies, side by side: q is [M, parts * K] and scale [M, parts * K/128]. A (part, group) pair is -// one unit of work, one wave's (a row is several blocks, grid.y). The tables stack the parts -// as the "givens" encoding does -- stages rows each of pairs and angle, one row of channel scales. -// -// THE CHANNEL SCALE IS A DIVIDE, because the encoding's t.scale is the factor the stored row was -// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the -// reference (libref) divides in f32 too, so the two agree on this step exactly. -// -// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or -// two, which is also what libref's libm is. The rotation is a handful of FMAs on top of that; the -// quantiser's rounding to E4M3 then swallows nearly all of the difference, and rad-kbench-style -// comparisons against the reference allow one code of disagreement per element. -// -// givens_quant_act_i8g is the same producer with an int8 output (scale amax / 127, round to nearest) for -// the int8 prefill GEMMs: after the rotation a group is flat, and 127 uniform levels beat e4m3's three -// mantissa bits for nearly every element. -// -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. - -#include "r4d.h" -#include "r4d_emit.h" -#include "r4d_fp8_args.h" -#include "r4d_fp8_wmma.h" -#include "r4d_q8.h" -#include - -namespace { - -constexpr uint32_t kWave = 32; -constexpr uint32_t kThreads = 256; -constexpr uint32_t kWaves = kThreads / kWave; -constexpr uint32_t kGroup = 128; -constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2 - -// kPre stages' tables are loaded and their angles' sine and cosine taken BEFORE the first of them is -// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS -// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency -// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages. -constexpr uint32_t kPre = 8; - -__device__ __forceinline__ void wave_sync() { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); - __builtin_amdgcn_wave_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); -} - -// One wave rotates and quantises one (part, group) of one row: grid.x is the row, and grid.y -// spreads a row's `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is -// several blocks and a decode step of a few rows still fills the part. A wave that has no group -// returns at once; nothing in the kernel is a block barrier. -// Rotate is givens_rotate: the same rotation, no quantiser, the rotated row written as f16 into -// `q` (read as a uint16 plane, y_ld elements a row) for a GEMM that reads a 16-bit activation. -// Fp8 and I8 are the two quantisers (r4d_q8.h: E4M3 with scale amax/448, int8 with amax/127). -enum class GvMode { Rotate, Fp8, I8 }; - -template -__global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( - const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs, - const float* __restrict__ angle, const float* __restrict__ rscale, uint8_t* __restrict__ q, - float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages, - uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) { - constexpr bool I8 = MODE == GvMode::I8; - __shared__ float sbuf[kWaves][kGroup]; - const uint32_t row = blockIdx.x; - const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; - const uint32_t item = blockIdx.y * kWaves + wave; - if (item >= parts * nkb) return; - const uint32_t part = item / nkb, g = item % nkb; - const uint32_t c0 = g * kGroup; - const size_t xrow = (size_t)row * x_ld; - float* buf = sbuf[wave]; - - // channel scale: v = x / D, four consecutive columns a lane - { - const float4 d = *(const float4*)(rscale + (size_t)part * K + c0 + lane * 4u); - const uint32_t xc = c0 + lane * 4u; - const float v0 = __uint_as_float((uint32_t)x[xrow + xc + 0] << 16) / d.x; - const float v1 = __uint_as_float((uint32_t)x[xrow + xc + 1] << 16) / d.y; - const float v2 = __uint_as_float((uint32_t)x[xrow + xc + 2] << 16) / d.z; - const float v3 = __uint_as_float((uint32_t)x[xrow + xc + 3] << 16) / d.w; - *(float4*)(buf + lane * 4u) = make_float4(v0, v1, v2, v3); - } - - for (uint32_t st0 = 0; st0 < stages; st0 += kPre) { - const uint32_t nst = (stages - st0) < kPre ? (stages - st0) : kPre; - int2 ab[kPre][kPairsPerLane]; - float th[kPre][kPairsPerLane], cs[kPre][kPairsPerLane], sn[kPre][kPairsPerLane]; -#pragma unroll - for (uint32_t k = 0; k < kPre; ++k) - if (k < nst) { - const size_t trow = (size_t)part * stages + st0 + k; - const int32_t* pr = pairs + trow * K + c0; - const float* an = angle + trow * (K / 2u) + g * (kGroup / 2u); -#pragma unroll - for (uint32_t u = 0; u < kPairsPerLane; ++u) { - const uint32_t j = lane + u * kWave; - ab[k][u] = *(const int2*)(pr + 2u * j); - th[k][u] = an[j]; - } - } -#pragma unroll - for (uint32_t k = 0; k < kPre; ++k) - if (k < nst) -#pragma unroll - for (uint32_t u = 0; u < kPairsPerLane; ++u) sincosf(th[k][u], &sn[k][u], &cs[k][u]); - wave_sync(); // the scaled row (or the previous chunk's last stage) is in LDS -#pragma unroll - for (uint32_t k = 0; k < kPre; ++k) - if (k < nst) { -#pragma unroll - for (uint32_t u = 0; u < kPairsPerLane; ++u) { - const int ia = ab[k][u].x - (int)c0, ib = ab[k][u].y - (int)c0; - const float va = buf[ia], vb = buf[ib]; - buf[ia] = fmaf(cs[k][u], va, sn[k][u] * vb); - buf[ib] = fmaf(cs[k][u], vb, -sn[k][u] * va); - } - wave_sync(); - } - } - - const float4 r = *(const float4*)(buf + lane * 4u); - float v[4] = { r.x, r.y, r.z, r.w }; - if constexpr (MODE == GvMode::Rotate) { - // f16 holds +-65504; a rotated post-norm row is orders below that, and the clamp keeps an - // outlier finite instead of inf - union { __half h[4]; uint2 u; } o; -#pragma unroll - for (int j = 0; j < 4; ++j) o.h[j] = __float2half(fminf(fmaxf(v[j], -65504.0f), 65504.0f)); - *(uint2*)((uint16_t*)q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = o.u; - return; - } - float m = 0.0f; -#pragma unroll - for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); - m = r4d_wave_max(m); - const float sc = m > 0.0f ? m * (1.0f / q8_top()) : 1.0f; - if (lane == 0) s[(size_t)row * s_ld + (size_t)part * nkb + g] = sc; - *(uint32_t*)(q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = - q8_pack4(v[0], v[1], v[2], v[3], 1.0f / sc); -} - -} // namespace - -// x [M][K] bf16, `x_ld` elements a row (0 = K) -// pairs [parts*stages][K] int32 column indices; (pairs[2j], pairs[2j+1]) is pair j -// angle [parts*stages][K/2] f32 -// rscale [parts][K] f32, the factor the stored row was multiplied by -// q [M][parts*K] E4M3 -// s [M][parts*K/128] f32 -static int givens_quant_launch(long x, long pairs, long angle, long rscale, long q, long s, int M, - int K, int parts, int stages, int x_ld, int q_ld, int s_ld, - const R4dSink& sk, GvMode mode = GvMode::Fp8) { - if (!x || !pairs || !angle || !rscale || !q || (mode != GvMode::Rotate && !s)) return -1; - if (M <= 0 || K <= 0 || parts <= 0 || stages <= 0) return -2; - if (K % (int)kGroup) return -3; // a rotation group cannot straddle the end of a row - if (!x_ld) x_ld = K; - const int nkb = K / (int)kGroup; - if (!q_ld) q_ld = parts * K; - if (!s_ld) s_ld = parts * nkb; - const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves; -#define GV_EMIT(M_) R4D_EMIT(sk, (givens_quant_act_fp8_kernel), dim3((uint32_t)M, gy), dim3(kThreads), 0, \ - (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, (const float*)rscale, \ - (uint8_t*)q, (float*)s, (uint32_t)K, (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, \ - (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) - const int rc = mode == GvMode::I8 ? GV_EMIT(GvMode::I8) - : mode == GvMode::Fp8 ? GV_EMIT(GvMode::Fp8) : GV_EMIT(GvMode::Rotate); -#undef GV_EMIT - if (rc != RAD_OK) return -4; - return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0; -} - -extern "C" int r4d_givens_quant_act_fp8_group(void) { return (int)kGroup; } - -// ============================================================== the plugin ABI entry point -enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Q = 4, GV_S = 5 }; - -static int givens_body(const RadArgs* a, const R4dSink& sk, GvMode mode) { - const bool quant = mode != GvMode::Rotate; - const RadTensor* x = r4d_opt(a, GV_X); - const RadTensor* pr = r4d_opt(a, GV_PAIRS); - const RadTensor* an = r4d_opt(a, GV_ANGLE); - const RadTensor* rs = r4d_opt(a, GV_RSCALE); - const RadTensor* q = r4d_opt(a, GV_Q); - const RadTensor* sc = quant ? r4d_opt(a, GV_S) : nullptr; - if (!x || !pr || !an || !rs || !q || (quant && !sc)) return R4D_NO(RAD_E_INVAL); - if (x->rank < 2 || q->rank != 2 || (quant && sc->rank != 2) || pr->rank != 2 || an->rank != 2 || - rs->rank != 2) return R4D_NO(RAD_E_SHAPE); - if (mode == GvMode::Rotate && q->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); - if (mode == GvMode::I8 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE); - if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32) - return R4D_NO(RAD_E_DTYPE); - // rows are dim 0 and everything after it is the row, as quant_act_fp8 reads them - const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); - const long long grp = (long long)kGroup, nkb = K / grp; - const long long parts = r4d_geti_or(a, "parts", 1), stages = r4d_geti_or(a, "stages", 0); - if (r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1) - return R4D_NO(RAD_E_SHAPE); - if (q->shape[0] != M || q->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE); - if (quant && (sc->shape[0] != M || sc->shape[1] != parts * nkb)) return R4D_NO(RAD_E_SHAPE); - // the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles - if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE); - if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE); - if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); - if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(q->data, 4)) - return R4D_NO(RAD_E_ALIGN); - const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = quant ? r4d_row_pitch(sc) : 0; - if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); - const int e = givens_quant_launch(r4d_addr(x), r4d_addr(pr), r4d_addr(an), r4d_addr(rs), - r4d_addr(q), r4d_addr(sc), (int)M, (int)K, (int)parts, - (int)stages, (int)xp, (int)qp, (int)sp, sk, mode); - return e == 0 ? RAD_OK : RAD_E_SHAPE; -} -static int rad_givens_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { - return givens_body(a, sk, GvMode::Fp8); -} -static int rad_givens_quant_act_i8g_body(const RadArgs* a, const R4dSink& sk) { - return givens_body(a, sk, GvMode::I8); -} -static int rad_givens_rotate_body(const RadArgs* a, const R4dSink& sk) { - return givens_body(a, sk, GvMode::Rotate); -} -R4D_ENTRY(r4d_rad_givens_quant_act_fp8, rad_givens_quant_act_fp8_body) -R4D_ENTRY(r4d_rad_givens_rotate, rad_givens_rotate_body) -R4D_ENTRY(r4d_rad_givens_quant_act_i8g, rad_givens_quant_act_i8g_body) diff --git a/libr4d/r4d_givens_rotate.hip b/libr4d/r4d_givens_rotate.hip new file mode 100644 index 00000000..7266be9b --- /dev/null +++ b/libr4d/r4d_givens_rotate.hip @@ -0,0 +1,174 @@ +// ParoQuant's rotation, to f16: the channel scale and Givens stages applied to a bf16 activation, for the +// 16-bit-activation GEMMs (w5a16 / w4a16_asym, rows up to 64 -- decode). The weight it pairs with is stored +// as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product with +// x' = x . D^-1 . G_1 ... G_S is : the rotation is the activation's to do, once a token, and the +// weight is read by the GEMM unchanged. The quantising form, for prefill-sized rows and for MXFP4, is +// r4d_givens_dense.hip. +// +// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- that is +// how the checkpoint is trained, and the converter and the loader (r4d_rad_relayout_givens_pairs) refuse +// one that does -- so a group is a closed system: +// its 128 values are rotated by S stages of 64 disjoint pairs. A wave owns a group. The values sit in LDS +// (128 floats a wave, no barrier needed: a wave's LDS accesses are in order, and the pairs of a stage are +// disjoint so no two lanes touch one address) and each lane takes two pairs a stage. +// +// PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row yields `parts` rotated +// copies, side by side: y is [M, parts * K]. A (part, group) pair is one unit of work, one wave's (a row +// is several blocks, grid.y). The tables stack the parts as the "givens" encoding does -- stages rows each +// of pairs and angle, one row of channel scales. +// +// THE CHANNEL SCALE IS A DIVIDE, because the encoding's t.scale is the factor the stored row was +// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the +// reference (libref) divides in f32 too, so the two agree on this step exactly. +// +// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or two, +// which is also what libref's libm is. +// +// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. + +#include "r4d.h" +#include "r4d_emit.h" +#include "r4d_fp8_args.h" +#include + +namespace { + +constexpr uint32_t kWave = 32; +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr uint32_t kGroup = 128; +constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2 + +// kPre stages' tables are loaded and their angles' sine and cosine taken BEFORE the first of them is +// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS +// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency +// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages. +constexpr uint32_t kPre = 8; + +__device__ __forceinline__ void wave_sync() { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); + __builtin_amdgcn_wave_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); +} + +// One wave rotates one (part, group) of one row: grid.x is the row, and grid.y spreads a row's +// `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is several blocks and a +// decode step of a few rows still fills the part. A wave that has no group returns at once; nothing in +// the kernel is a block barrier. The rotated row is written as f16 into `y`, y_ld elements a row. +__global__ __launch_bounds__(kThreads) void givens_rotate_kernel( + const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs, + const float* __restrict__ angle, const float* __restrict__ rscale, uint16_t* __restrict__ y, + uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages, uint32_t x_ld, uint32_t y_ld) { + __shared__ float sbuf[kWaves][kGroup]; + const uint32_t row = blockIdx.x; + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + const uint32_t item = blockIdx.y * kWaves + wave; + if (item >= parts * nkb) return; + const uint32_t part = item / nkb, g = item % nkb; + const uint32_t c0 = g * kGroup; + const size_t xrow = (size_t)row * x_ld; + float* buf = sbuf[wave]; + + // channel scale: v = x / D, four consecutive columns a lane + { + const float4 d = *(const float4*)(rscale + (size_t)part * K + c0 + lane * 4u); + const uint32_t xc = c0 + lane * 4u; + const float v0 = __uint_as_float((uint32_t)x[xrow + xc + 0] << 16) / d.x; + const float v1 = __uint_as_float((uint32_t)x[xrow + xc + 1] << 16) / d.y; + const float v2 = __uint_as_float((uint32_t)x[xrow + xc + 2] << 16) / d.z; + const float v3 = __uint_as_float((uint32_t)x[xrow + xc + 3] << 16) / d.w; + *(float4*)(buf + lane * 4u) = make_float4(v0, v1, v2, v3); + } + + for (uint32_t st0 = 0; st0 < stages; st0 += kPre) { + const uint32_t nst = (stages - st0) < kPre ? (stages - st0) : kPre; + int2 ab[kPre][kPairsPerLane]; + float th[kPre][kPairsPerLane], cs[kPre][kPairsPerLane], sn[kPre][kPairsPerLane]; +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) { + const size_t trow = (size_t)part * stages + st0 + k; + const int32_t* pr = pairs + trow * K + c0; + const float* an = angle + trow * (K / 2u) + g * (kGroup / 2u); +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) { + const uint32_t j = lane + u * kWave; + ab[k][u] = *(const int2*)(pr + 2u * j); + th[k][u] = an[j]; + } + } +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) sincosf(th[k][u], &sn[k][u], &cs[k][u]); + wave_sync(); // the scaled row (or the previous chunk's last stage) is in LDS +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) { +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) { + const int ia = ab[k][u].x - (int)c0, ib = ab[k][u].y - (int)c0; + const float va = buf[ia], vb = buf[ib]; + buf[ia] = fmaf(cs[k][u], va, sn[k][u] * vb); + buf[ib] = fmaf(cs[k][u], vb, -sn[k][u] * va); + } + wave_sync(); + } + } + + const float4 r = *(const float4*)(buf + lane * 4u); + const float v[4] = { r.x, r.y, r.z, r.w }; + // f16 holds +-65504; a rotated post-norm row is orders below that, and the clamp keeps an outlier + // finite instead of inf + union { __half h[4]; uint2 u; } o; +#pragma unroll + for (int j = 0; j < 4; ++j) o.h[j] = __float2half(fminf(fmaxf(v[j], -65504.0f), 65504.0f)); + *(uint2*)(y + (size_t)row * y_ld + (size_t)part * K + c0 + lane * 4u) = o.u; +} + +} // namespace + +// x [M][K] bf16, `x_ld` elements a row (0 = K) +// pairs [parts*stages][K] int32 column indices; (pairs[2j], pairs[2j+1]) is pair j +// angle [parts*stages][K/2] f32 +// rscale [parts][K] f32, the factor the stored row was multiplied by +// y [M][parts*K] f16 +enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Y = 4 }; + +static int givens_rotate_body(const RadArgs* a, const R4dSink& sk) { + const RadTensor* x = r4d_opt(a, GV_X); + const RadTensor* pr = r4d_opt(a, GV_PAIRS); + const RadTensor* an = r4d_opt(a, GV_ANGLE); + const RadTensor* rs = r4d_opt(a, GV_RSCALE); + const RadTensor* y = r4d_opt(a, GV_Y); + if (!x || !pr || !an || !rs || !y) return R4D_NO(RAD_E_INVAL); + if (x->rank < 2 || y->rank != 2 || pr->rank != 2 || an->rank != 2 || rs->rank != 2) + return R4D_NO(RAD_E_SHAPE); + if (y->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); + if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32) + return R4D_NO(RAD_E_DTYPE); + // rows are dim 0 and everything after it is the row + const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); + const long long grp = (long long)kGroup, nkb = K / grp; + const long long parts = r4d_geti_or(a, "parts", 1), stages = r4d_geti_or(a, "stages", 0); + if (M <= 0 || r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1) + return R4D_NO(RAD_E_SHAPE); + if (y->shape[0] != M || y->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE); + // the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles + if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE); + if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE); + if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); + if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(y->data, 4)) + return R4D_NO(RAD_E_ALIGN); + const long long xp = r4d_row_pitch(x), yp = r4d_row_pitch(y); + if (xp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); + const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves; + const int rc = R4D_EMIT(sk, givens_rotate_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, + (const uint16_t*)x->data, (const int32_t*)pr->data, (const float*)an->data, + (const float*)rs->data, (uint16_t*)y->data, (uint32_t)K, (uint32_t)nkb, + (uint32_t)parts, (uint32_t)stages, (uint32_t)(xp ? xp : K), (uint32_t)(yp ? yp : parts * K)); + if (rc != RAD_OK) return rc; + return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK; +} +R4D_ENTRY(r4d_rad_givens_rotate, givens_rotate_body) diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 02554bb3..e5b2fde4 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -901,7 +901,7 @@ namespace { /* A ROTATED MXFP4 WEIGHT (ParoQuant): the same two planes -- e2m1 codes, an E8M0 exponent a 32 -- * stored in the basis the "givens" transform names, with the rotation's tables beside them. The * GEMM reads the codes and exponents exactly as it reads an unrotated weight; the rotation is the - * activation's (givens_quant_act_fp8), and the tables are separate weight operands of that op, so + * activation's (givens_dense_quant), and the tables are separate weight operands of that op, so * nothing here touches them. What is checked is that they are there and are the kind of * rotation the quantiser applies: a transform this library does not read would hand the kernel * codes that decode to other numbers. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index abc57929..8f7c33d2 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -327,10 +327,6 @@ int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_had_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_givens_rotate (const RadArgs*, RadStream); int r4d_rad_givens_rotate_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -int r4d_rad_givens_quant_act_fp8 (const RadArgs*, RadStream); -int r4d_rad_givens_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -int r4d_rad_givens_quant_act_i8g (const RadArgs*, RadStream); -int r4d_rad_givens_quant_act_i8g_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 202bc1eb..e4d51e77 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1052,10 +1052,10 @@ static const RadOperandSpec oQuantActFp8[] = { { "scale", RAD_OPD_OUT, 0 }, }; -/* `givens_quant_act_fp8` is ParoQuant's activation side, and libref declared this schema first - * (the loader refuses two that differ). The tables are the "givens" encoding's, as WEIGHT operands; - * see libref/ref_quant.cpp for the contract and r4d_givens_quant_act_fp8.hip for the kernel. */ -static const RadParamSpec pGivensQuantAct[] = { +/* `givens_rotate` is ParoQuant's activation side for the 16-bit GEMMs, and libref declared this schema + * first (the loader refuses two that differ). The tables are the "givens" encoding's, as WEIGHT + * operands; see libref/ref_quant.cpp for the contract and r4d_givens_rotate.hip for the kernel. */ +static const RadParamSpec pGivensRotate[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, { "group", RAD_P_INT, RAD_REQUIRED }, @@ -1070,16 +1070,8 @@ static const RadOperandSpec oGivensRotate[] = { { "rscale", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; -static const RadOperandSpec oGivensQuantAct[] = { - { "x", RAD_OPD_IN, 0 }, - { "pairs", RAD_OPD_WEIGHT, 0 }, - { "angle", RAD_OPD_WEIGHT, 0 }, - { "rscale", RAD_OPD_WEIGHT, 0 }, - { "q", RAD_OPD_OUT, 0 }, - { "scale", RAD_OPD_OUT, 0 }, -}; -/* `givens_dense_quant` is givens_quant_act_fp8 with the rotation done by a dense per-group matrix on the +/* `givens_dense_quant` is ParoQuant's activation quantiser, the rotation done by a dense per-group matrix on the * matrix cores (r4d_givens_dense.hip). The matrices are the weight -- rad-convert composes them from the * givens tables (r4d_rad_layout_gdense) -- so its tables are `tdense` and the channel scale `rscale`. * `out` is the quantiser: "i8" (scale amax / 127) or "fp8" (E4M3, amax / 448), as q's dtype says. */ @@ -2352,31 +2344,17 @@ static const RadOpSchema kSchemas[] = { SCHEMA("had_quant_act_i8g", pQuantActFp8, oQuantActFp8, "quant_act_i8g with a `group`-wide Hadamard along K first; pairs with an i8 weight stored " "rotated, its scale carrying the residual factor of `group`."), - SCHEMA("givens_rotate", pGivensQuantAct, oGivensRotate, - "givens_quant_act_fp8 without the quantiser: y = x / rscale rotated by `stages` rounds of " + SCHEMA("givens_rotate", pGivensRotate, oGivensRotate, + "ParoQuant's rotation without a quantiser: y = x / rscale rotated by `stages` rounds of " "Givens pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight " "whose GEMM reads a 16-bit activation. `group` is the width a pair stays inside."), - SCHEMA("givens_quant_act_fp8", pGivensQuantAct, oGivensQuantAct, - "ParoQuant's activation quantiser: x is divided by the channel scale `rscale`, rotated by " - "`stages` rounds of disjoint Givens pairs (a' = a cos t + b sin t, b' = b cos t - a sin t, " - "pairs as column indices of the row, each inside one scale group), then quantised as " - "quant_act_fp8 does: scale = amax / 448 per `group`. `parts` rotated copies are written " - "side by side -- q is [M, parts * n], scale [M, parts * n / group] -- part p from table " - "rows [p * stages, (p + 1) * stages) of `pairs` and `angle` and row p of `rscale`: a " - "fused projection's pieces were each rotated on their own. Only a weight stored with " - "the \"givens\" transform reads the result; it is NOT quant_act_fp8's output in either " - "direction."), SCHEMA("givens_dense_quant", pGivensDense, oGivensDense, "ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / " "rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column " "group) that its Givens stages compose to, then the block-scaled quantiser `out` names " "(\"i8\": scale amax / 127, round to nearest; \"fp8\": E4M3, amax / 448). q is [M, parts * n] " "and scale [M, parts * n / group]; tdense is [parts * n, 128]. The same activation as " - "givens_quant_act_i8g / _fp8 up to the f16 rounding of T."), - SCHEMA("givens_quant_act_i8g", pGivensQuantAct, oGivensQuantAct, - "givens_quant_act_fp8 with an int8 output: the same channel scale and rotations, then " - "quant_act_i8g's quantiser (scale = amax / 127 per `group`, round to nearest). For the int8 " - "prefill GEMMs of a weight stored with the \"givens\" transform."), + "the sequential rotation, up to the f16 rounding of T."), SCHEMA("had_quant_act_fp8", pQuantActFp8, oQuantActFp8, "the same, with a `group`-wide Hadamard along K applied BEFORE the absmax. Pairs with " "an expert weight stored at dtype w4a8h, which carries the matching rotation and the " @@ -5257,37 +5235,6 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_had_quant_act_fp8, nullptr, nullptr, nullptr, r4d_shape_quant_act_fp8, nullptr, nullptr, r4d_rad_had_quant_act_fp8_describe }, -/* ParoQuant's rotation and the quantiser in one pass, because the rotation changes the maximum the - * scale is taken over and so cannot be a separate launch ahead of quant_act_fp8 without writing - * and re-reading the rotated row. It exists for the MXFP4 weight stored rotated and for nothing - * else. */ -{ "givens_quant_act_fp8", "givens_quant_act_fp8", "quant", - "the channel scale, ParoQuant's Givens rotations, then per-(row, 128-column) symmetric E4M3 " - "quantisation, once for each rotated part of a fused projection", - "n a multiple of 128 -- a rotation group cannot straddle the end of a row -- and group 128, " - "which is both the rotation group and the weight scale's activation block", - "bf16 in, E4M3 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale per (row, part, " - "128 columns); the tables are the weight's int32 pairs (checked at load to pair each group's own " - "columns), f32 angles and f32 channel scales", - RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, - ROW(cHadQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_givens_quant_act_fp8, nullptr, r4d_rad_layout_givens_pairs, - r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, - r4d_rad_givens_quant_act_fp8_describe }, - -{ "givens_quant_act_i8g", "givens_quant_act_i8g", "quant", - "the channel scale, ParoQuant's Givens rotations, then per-(row, 128-column) symmetric int8 " - "quantisation, once for each rotated part of a fused projection", - "n a multiple of 128 and group 128, as givens_quant_act_fp8's", - "bf16 in, int8 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale of amax/127 per " - "(row, part, 128 columns); the tables are the weight's int32 pairs, f32 angles and f32 channel " - "scales", - RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, - ROW(cHadQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_givens_quant_act_i8g, nullptr, r4d_rad_layout_givens_pairs, - r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, - r4d_rad_givens_quant_act_i8g_describe }, - { "givens_dense_quant", "givens_dense_quant", "quant", "ParoQuant's rotation as a dense 128 x 128 f16 matrix a (part, group) on the matrix cores, then " "per-(row, 128-column) symmetric quantisation to int8 or E4M3, once for each rotated part", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 4c46a3ef..e68f2084 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3776,8 +3776,7 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ * the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, bool rot_only = false, bool i8 = false, bool dense = false) { - const char* row = dense ? "givens_dense_quant" : rot_only ? "givens_rotate" - : i8 ? "givens_quant_act_i8g" : "givens_quant_act_fp8"; + const char* row = dense ? "givens_dense_quant" : "givens_rotate"; if (!sel(row)) return; char nm[160]; std::snprintf(nm, sizeof nm, "%s %s numeric M=%lld K=%lld parts=%d stages=%d", row, @@ -13182,17 +13181,6 @@ static void device_phase(const Plugin& pl) { givens_numeric(pl, 300, 6144, 2, 8, true); } - if (sel("givens_quant_act_i8g")) { - if (!g_case) std::printf("\nParoQuant's rotated activation, int8 output, against libm's rotation\n"); - givens_numeric(pl, 1, 128, 1, 8, false, true); - givens_numeric(pl, 3, 5120, 1, 8, false, true); - givens_numeric(pl, 5, 5120, 2, 8, false, true); - givens_numeric(pl, 64, 17408, 1, 8, false, true); - givens_numeric(pl, 300, 6144, 2, 8, false, true); - givens_numeric(pl, 2048, 5120, 1, 8, false, true); - givens_numeric(pl, 2048, 5120, 2, 8, false, true); - givens_numeric(pl, 2048, 17408, 1, 8, false, true); - } if (sel("givens_dense_quant")) { if (!g_case) std::printf("\nParoQuant's rotation as dense per-group matrices, int8 and E4M3 output, against libm's rotation\n"); for (int i8 = 0; i8 < 2; ++i8) { @@ -13203,18 +13191,11 @@ static void device_phase(const Plugin& pl) { givens_numeric(pl, 300, 6144, 2, 8, false, i8, true); givens_numeric(pl, 2048, 5120, 1, 8, false, i8, true); givens_numeric(pl, 2048, 5120, 2, 8, false, i8, true); + givens_numeric(pl, 64, 17408, 1, 8, false, i8, true); givens_numeric(pl, 2048, 17408, 1, 8, false, i8, true); + givens_numeric(pl, 7, 5120, 3, 2, false, i8, true); } } - if (sel("givens_quant_act_fp8")) { - if (!g_case) std::printf("\nParoQuant's rotate-and-quantise, against an f64 rotation\n"); - givens_numeric(pl, 1, 128, 1, 8); - givens_numeric(pl, 3, 5120, 1, 8); - givens_numeric(pl, 5, 5120, 2, 8); - givens_numeric(pl, 64, 17408, 1, 8); - givens_numeric(pl, 300, 6144, 2, 8); - givens_numeric(pl, 7, 5120, 3, 2); - } if (sel("gram_accum")) { if (!g_case) std::printf("\nthe GPTQ calibration accumulator, against an f64 host Gram\n"); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 560f55b4..aaccbcb8 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -100,8 +100,6 @@ int ref_quant_act_i8 (const RadArgs*, RadStream); int ref_had_quant_act_i8 (const RadArgs*, RadStream); int ref_quant_act_fp8 (const RadArgs*, RadStream); int ref_had_quant_act_fp8 (const RadArgs*, RadStream); -int ref_givens_quant_act_fp8(const RadArgs*, RadStream); -int ref_givens_quant_act_i8g(const RadArgs*, RadStream); int ref_givens_dense_quant(const RadArgs*, RadStream); int ref_givens_rotate(const RadArgs*, RadStream); int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); @@ -232,8 +230,6 @@ REF_SHAPE_FN(ref_quant_act_i8); REF_SHAPE_FN(ref_had_quant_act_i8); REF_SHAPE_FN(ref_quant_act_fp8); REF_SHAPE_FN(ref_had_quant_act_fp8); -REF_SHAPE_FN(ref_givens_quant_act_fp8); -REF_SHAPE_FN(ref_givens_quant_act_i8g); REF_SHAPE_FN(ref_givens_dense_quant); REF_SHAPE_FN(ref_givens_rotate); REF_SHAPE_FN(ref_rmsnorm_quant_fp8); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 897b4894..ddbd46b3 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -410,35 +410,31 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { return RAD_OK; } -/* ------------------------------------------------------------- givens_quant_act_fp8 */ -/* ParoQuant's activation side: every row scaled by its channel factors, rotated by `stages` - * rounds of disjoint Givens pairs, then the same symmetric block-scaled E4M3 quantiser. A weight - * stored as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens") meets the activation - * x . D^-1 . G_1 ... G_S, because = and each G is orthogonal. +/* ------------------------------------------------------------- givens_rotate */ +/* ParoQuant's activation side: every row scaled by its channel factors and rotated by `stages` rounds of + * disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S + * (abi/rad_encoding.h, "givens") meets the activation x . D^-1 . G_1 ... G_S, because + * = and each G is orthogonal. For a weight whose GEMM reads a 16-bit + * activation (w5a16); the quantising form is givens_dense_quant, over the composed matrices. * * PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row has `parts` rotated - * copies, written side by side: q is [rows, parts * n] and scale [rows, parts * n/group], part p at - * columns [p*n, (p+1)*n). The tables stack the parts: pairs and angle `stages` rows each, scale one - * row, per part. A part's pairs address columns of the row, and a pair must stay inside one scale - * group (the checkpoint's are within groups of 128): the quantiser reads each group's rotated - * values after the stages and the device kernel rotates a group at a time. + * copies, written side by side: y is [rows, parts * n], part p at columns [p*n, (p+1)*n). The tables + * stack the parts: pairs and angle `stages` rows each, scale one row, per part. A part's pairs address + * columns of the row and stay inside one group of `group` (the checkpoint's are within groups of 128). * * The arithmetic is the device kernel's, restated: the divide by the channel scale, then for each - * stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32, then amax/448 per group. Not - * bit-identical to the device on the angle: cos and sin of an f32 differ by an ulp between libm - * and the GPU's. */ -static int givens_body(const RadArgs* a, bool quant, bool i8 = false) { - if (!have(a, quant ? 6 : 5)) return RAD_E_INVAL; - const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3]; - const RadTensor *q = &a->t[4], *s = quant ? &a->t[5] : nullptr; + * stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32. Not bit-identical to the device on the + * angle: cos and sin of an f32 differ by an ulp between libm and the GPU's. */ +int ref_givens_rotate(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3], *q = &a->t[4]; const int64_t n = p_int(a, "n", 0), S = p_int(a, "stages", 0), P = p_int(a, "parts", 1); - int64_t g = p_int(a, "group", 0); + const int64_t g = p_int(a, "group", 0); if (n <= 0 || S <= 0 || P <= 0 || (n & 1)) return RAD_E_SHAPE; if (g <= 0 || g > n || n % g != 0) return RAD_E_SHAPE; if (numel(pr) < P * S * n || numel(an) < P * S * (n / 2) || numel(sc) < P * n) return RAD_E_SHAPE; const int64_t rows = numel(x) / n; - const int64_t ngrp = n / g; - if (rows <= 0 || numel(q) < rows * P * n || (quant && numel(s) < rows * P * ngrp)) return RAD_E_SHAPE; + if (rows <= 0 || numel(q) < rows * P * n) return RAD_E_SHAPE; // validated before the loop, because an OpenMP body cannot return for (int64_t i = 0; i < P * S * n; ++i) { @@ -464,38 +460,13 @@ static int givens_body(const RadArgs* a, bool quant, bool i8 = false) { buf[(size_t)ib] = vb * c - va * sn; } } - if (!quant) { // givens_rotate: the rotated row, in q's dtype - for (int64_t k = 0; k < n; ++k) st_dt(q->dtype, q->data, qb + (p * n + k) * qs, buf[(size_t)k]); - continue; - } - for (int64_t gi = 0; gi < ngrp; ++gi) { - const int64_t k0 = gi * g; - float amax = 0.0f; - for (int64_t i = 0; i < g; ++i) { - const float m = std::fabs(buf[(size_t)(k0 + i)]); - if (m > amax) amax = m; - } - const float qmax = i8 ? 127.0f : 448.0f; - const float scl = amax > 0.0f ? amax * (1.0f / qmax) : 1.0f; - const float inv = 1.0f / scl; - for (int64_t i = 0; i < g; ++i) { - float v = buf[(size_t)(k0 + i)] * inv; - if (v > qmax) v = qmax; - if (v < -qmax) v = -qmax; - if (i8) v = std::nearbyint(v); - st_dt(q->dtype, q->data, qb + (p * n + k0 + i) * qs, v); - } - stt(s, rowoff(s, r, P * ngrp) + (p * ngrp + gi) * laststride(s), scl); - } + for (int64_t k = 0; k < n; ++k) st_dt(q->dtype, q->data, qb + (p * n + k) * qs, buf[(size_t)k]); } } return RAD_OK; } -int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { return givens_body(a, true); } -int ref_givens_quant_act_i8g(const RadArgs* a, RadStream) { return givens_body(a, true, true); } - -/* The same activation with the rotation applied as the dense matrix: y[j] = sum_i T[j][i] * x[i] / D[i] over +/* ParoQuant's activation quantiser: the rotation applied as the dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i] over * each (part, 128-column group), then the quantiser `q`'s dtype names. T is the weight, f16, one [128, 128] * matrix a (part, group) -- what r4d_rad_relayout_gdense composes from the givens tables. */ int ref_givens_dense_quant(const RadArgs* a, RadStream) { @@ -541,9 +512,6 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) { return RAD_OK; } -/* The same channel scale and rotations with NO quantiser: y = the rotated row in y's dtype, `parts` - * copies side by side. For a weight whose GEMM reads a 16-bit activation (w5a16). */ -int ref_givens_rotate(const RadArgs* a, RadStream) { return givens_body(a, false); } /* ---------------------------------------------------------------- the Gram accumulator * diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 30430f8a..8a4fe796 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -201,10 +201,10 @@ static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") }; /* No `asum`: that output exists for the asymmetric integer grids and an fp8 grid is symmetric by * construction (libr4d/r4d_rows.cpp says the same). */ static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; -/* ParoQuant's activation quantiser: a rotation per part in front of quant_act_fp8's. The three +/* ParoQuant's rotation: a rotation per part, to f16 for the 16-bit GEMMs. The three * tables are the "givens" encoding's (abi/rad_encoding.h) and are WEIGHT operands, so they are * resolved, moved and placed with the weight they belong to. */ -static const RadParamSpec pGivensQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), +static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INT("stages"), P_INT("parts") }; static const RadParamSpec pGivensDense[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INT("parts"), P_STR("out") }; @@ -212,8 +212,6 @@ static const RadOperandSpec oGivensDense[] = { OPD("x"), WGT("tdense"), WGT("rsc OUT("scale") }; static const RadOperandSpec oGivensRotate[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), OUT("y") }; -static const RadOperandSpec oGivensQuant[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), - OUT("q"), OUT("scale") }; /* ---- the fp8 fusions ---------------------------------------------------------------------- * A fused op's operands are the unfused pair's minus the tensor between them, and `out_bf16` @@ -806,28 +804,15 @@ static const RadOpSchema kSchemas[] = { "previous pick. `hp` absent is a plane of ones, which drops the form to a plain low-rank " "bigram. Serial in l by construction -- the predecessor is not known until the previous step " "has been decided." }, -{ "givens_quant_act_fp8", ARR(pGivensQuant), ARR(oGivensQuant), - "ParoQuant's activation quantiser: x is divided by the channel scale `rscale`, rotated by " - "`stages` rounds of disjoint Givens pairs (a' = a cos t + b sin t, b' = b cos t - a sin t, pairs " - "as column indices of the row, each inside one scale group), then quantised as quant_act_fp8 " - "does: scale = amax / 448 per `group`. `parts` rotated copies are written side by side -- q is " - "[M, parts * n], scale [M, parts * n / group] -- part p from table rows [p * stages, (p + 1) * " - "stages) of `pairs` and `angle` and row p of `rscale`: a fused projection's pieces were each " - "rotated on their own. Only a weight stored with the \"givens\" transform reads the result; " - "it is NOT quant_act_fp8's output in either direction." }, { "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense), "ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / " "rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column " "group) that its Givens stages compose to, then the block-scaled quantiser `out` names " "(\"i8\": scale amax / 127, round to nearest; \"fp8\": E4M3, amax / 448). q is [M, parts * n] " "and scale [M, parts * n / group]; tdense is [parts * n, 128]. The same activation as " - "givens_quant_act_i8g / _fp8 up to the f16 rounding of T." }, -{ "givens_quant_act_i8g", ARR(pGivensQuant), ARR(oGivensQuant), - "givens_quant_act_fp8 with an int8 output: the same channel scale and rotations, then " - "quant_act_i8g's quantiser (scale = amax / 127 per `group`, round to nearest). For the int8 " - "prefill GEMMs of a weight stored with the \"givens\" transform." }, -{ "givens_rotate", ARR(pGivensQuant), ARR(oGivensRotate), - "givens_quant_act_fp8 without the quantiser: y = x / rscale rotated by `stages` rounds of Givens " + "the sequential rotation, up to the f16 rounding of T." }, +{ "givens_rotate", ARR(pGivensRotate), ARR(oGivensRotate), + "ParoQuant's rotation without a quantiser: y = x / rscale rotated by `stages` rounds of Givens " "pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight whose GEMM " "reads a 16-bit activation. `group` is the width a pair stays inside." }, { "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), @@ -1195,18 +1180,10 @@ SIMPLE("ref_dflash_select", "dflash_select", "draft", SIMPLE("ref_givens_rotate", "givens_rotate", "quant", "channel scale and Givens rotations per part, in the output's dtype", "float in, float out; int32 pairs, f32 angles and channel scales", ref_givens_rotate), -SIMPLE("ref_givens_quant_act_fp8", "givens_quant_act_fp8", "quant", - "channel scale and Givens rotations per part, then the block-scaled E4M3 quantiser", - "float in, fp8_e4m3 out, f32 scale per group; int32 pairs, f32 angles and channel scales", - ref_givens_quant_act_fp8), SIMPLE("ref_givens_dense_quant", "givens_dense_quant", "quant", "the rotation as a dense per-group matrix, then the block-scaled int8 or E4M3 quantiser", "float in, int8 or fp8_e4m3 out, f32 scale per group; f16 matrices and f32 channel scales", ref_givens_dense_quant), -SIMPLE("ref_givens_quant_act_i8g", "givens_quant_act_i8g", "quant", - "channel scale and Givens rotations per part, then the block-scaled int8 quantiser", - "float in, int8 out, f32 scale per group; int32 pairs, f32 angles and channel scales", - ref_givens_quant_act_i8g), SIMPLE("ref_had_quant_act_fp8", "had_quant_act_fp8", "quant", "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; n a multiple of group", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index f188cb1b..dc5a5112 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -832,20 +832,12 @@ int ref_gram_accum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou * stage, the partner inside the group), and a described operand can only be drawn, not constructed * -- an index draw has repeats, and a Givens stage over a repeated column is not a rotation. A case * built from one would compare two implementations of nothing. r4d_selftest builds real pairings. */ -int ref_givens_quant_act_fp8_shape(const RadParam*, int, int, RadOpdDesc*) { - return RAD_E_UNSUPPORTED; -} - -int ref_givens_quant_act_i8g_shape(const RadParam*, int, int, RadOpdDesc*) { - return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ -} - int ref_givens_dense_quant_shape(const RadParam*, int, int, RadOpdDesc*) { - return RAD_E_UNSUPPORTED; /* a composed rotation cannot be drawn: see givens_quant_act_fp8 */ + return RAD_E_UNSUPPORTED; /* a composed rotation cannot be drawn: it is a weight, built from real pairings */ } int ref_givens_rotate_shape(const RadParam*, int, int, RadOpdDesc*) { - return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ + return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: a described operand can only be drawn, and an index draw has repeats */ } int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 5ca8af2d..e7372111 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -261,7 +261,7 @@ TEST(op_vocabulary) { "embed_lookup_q", "cast", "scale_rows", "softmax", - "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "givens_quant_act_i8g", "givens_dense_quant", "givens_rotate", "had_quant_act_i8", + "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_dense_quant", "givens_rotate", "had_quant_act_i8", "gram_accum", /* The fused fp8 forms. A host run needs EVERY op covered, so these are what stands * between a host-backend run and "site 'host' is unavailable for this band". */ @@ -1506,10 +1506,13 @@ TEST(op_gemm_nt_q_parts_read_their_own_activation_copy) { } } -/* ParoQuant's activation quantiser. With zero angles and unit channel scales it IS quant_act_fp8; - * with real rotations the dequantised row is the rotated row to within the fp8 grid, and the - * rotation preserves the row's norm -- checked per part, against a double-precision rotation. */ -TEST(op_givens_quant_act_fp8) { +/* ParoQuant's activation quantiser, the rotation as dense per-group matrices. T[j][i] of a (part, group) is + * the group's composed network applied to the unit vector e_i, built here in double from the same pairs and + * angles the device layout hook reads; with it the dequantised row is the rotated row to within the + * quantiser's grid (plus the f16 rounding of T), and the rotation preserves the row's norm -- both checked + * per part against a double-precision rotation. With T the identity and unit channel scales it IS + * quant_act_fp8, exactly. Run for both quantisers `out` names. */ +TEST(op_givens_dense_quant) { const int64_t M = 3, n = 256, S = 3, P = 2, G = 128; uint32_t rng = 99; auto nxt = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; }; @@ -1517,70 +1520,105 @@ TEST(op_givens_quant_act_fp8) { T x(RAD_BF16, {M, n}); std::vector xv((size_t)(M * n)); for (auto& v : xv) v = frand(-3.0f, 3.0f); - x.f(xv); for (int64_t m = 0; m < M; ++m) xv[(size_t)(m * n + 7)] = 0; // a zero in the mix + x.f(xv); // a pairing of each group of 128 per stage per part - T pr(RAD_I32, {P * S, n}), an(RAD_F32, {P * S, n / 2}), rs(RAD_F32, {P, n}); + std::vector pairs((size_t)(P * S * n)); for (int64_t ps = 0; ps < P * S; ++ps) for (int64_t g = 0; g < n / G; ++g) { std::vector perm((size_t)G); for (int i = 0; i < G; ++i) perm[(size_t)i] = (int32_t)(g * G + i); for (int i = (int)G - 1; i > 0; --i) std::swap(perm[(size_t)i], perm[nxt() % (i + 1)]); - for (int i = 0; i < G; ++i) st_int(RAD_I32, pr.t.data, ps * n + g * G + i, perm[(size_t)i]); + for (int i = 0; i < G; ++i) pairs[(size_t)(ps * n + g * G + i)] = perm[(size_t)i]; } std::vector av((size_t)(P * S * n / 2)), sv((size_t)(P * n)); for (auto& v : av) v = frand(-3.0f, 3.0f); for (auto& v : sv) v = frand(0.5f, 2.0f); - an.f(av); + T rs(RAD_F32, {P, n}); rs.f(sv); - T q(RAD_F8E4M3, {M, P * n}), s(RAD_F32, {M, P * n / G}); - A a; a.t(x).t(pr).t(an).t(rs).t(q).t(s) - .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("stages", S).i("parts", P); - CHECK_OK(run("givens_quant_act_fp8", a)); - double worst = 0; - int bad_norm = 0; - for (int64_t m = 0; m < M; ++m) - for (int64_t p = 0; p < P; ++p) { - std::vector b((size_t)n); - double n0 = 0; - for (int64_t k = 0; k < n; ++k) { - b[(size_t)k] = (double)x.at(m * n + k) / (double)sv[(size_t)(p * n + k)]; - n0 += b[(size_t)k] * b[(size_t)k]; - } - for (int64_t st = 0; st < S; ++st) - for (int64_t j = 0; j < n / 2; ++j) { - const int64_t ia = pr.iat((p * S + st) * n + 2 * j), ib = pr.iat((p * S + st) * n + 2 * j + 1); - const double t = av[(size_t)((p * S + st) * (n / 2) + j)], c = std::cos(t), sn = std::sin(t); - const double va = b[(size_t)ia], vb = b[(size_t)ib]; - b[(size_t)ia] = va * c + vb * sn; - b[(size_t)ib] = vb * c - va * sn; - } - double n1 = 0; - for (int64_t k = 0; k < n; ++k) n1 += b[(size_t)k] * b[(size_t)k]; - if (std::fabs(n1 - n0) > 1e-9 * n0) ++bad_norm; - for (int64_t g = 0; g < n / G; ++g) { - double amax = 0; - for (int64_t i = 0; i < G; ++i) amax = std::max(amax, std::fabs(b[(size_t)(g * G + i)])); - const double sc = s.at(m * (P * n / G) + p * (n / G) + g); - CHECK(std::fabs(sc - amax / 448.0) < 1e-5 * amax / 448.0 + 1e-12); + // the composed matrices, [P * n/G groups][G (j)][G (i)], as f16 + auto compose = [&](const std::vector& angles, std::vector* tm) { + tm->assign((size_t)(P * (n / G) * G * G), 0.0f); + for (int64_t p = 0; p < P; ++p) + for (int64_t g = 0; g < n / G; ++g) for (int64_t i = 0; i < G; ++i) { - const double deq = (double)q.at(m * P * n + p * n + g * G + i) * sc; - worst = std::max(worst, std::fabs(deq - b[(size_t)(g * G + i)]) / amax); + std::vector v((size_t)G, 0.0); + v[(size_t)i] = 1.0; + for (int64_t st = 0; st < S; ++st) + for (int64_t j = 0; j < G / 2; ++j) { + const int64_t ia = pairs[(size_t)((p * S + st) * n + g * G + 2 * j)] - g * G; + const int64_t ib = pairs[(size_t)((p * S + st) * n + g * G + 2 * j + 1)] - g * G; + const double t = angles[(size_t)((p * S + st) * (n / 2) + g * (G / 2) + j)]; + const double c = std::cos(t), sn = std::sin(t); + const double va = v[(size_t)ia], vb = v[(size_t)ib]; + v[(size_t)ia] = va * c + vb * sn; + v[(size_t)ib] = vb * c - va * sn; + } + for (int64_t j = 0; j < G; ++j) + (*tm)[(size_t)(((p * (n / G) + g) * G + j) * G + i)] = (float)v[(size_t)j]; + } + }; + std::vector tmv; + compose(av, &tmv); + T tm(RAD_F16, {P * n, G}); + tm.f(tmv); + + for (int i8 = 0; i8 < 2; ++i8) { + const double qmax = i8 ? 127.0 : 448.0; + const uint32_t qdt = i8 ? RAD_I8 : RAD_F8E4M3; + T q(qdt, {M, P * n}), s(RAD_F32, {M, P * n / G}); + A a; a.t(x).t(tm).t(rs).t(q).t(s) + .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("parts", P).s("out", i8 ? "i8" : "fp8"); + CHECK_OK(run("givens_dense_quant", a)); + double worst = 0; + int bad_norm = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t p = 0; p < P; ++p) { + std::vector b((size_t)n); + double n0 = 0; + for (int64_t k = 0; k < n; ++k) { + b[(size_t)k] = (double)x.at(m * n + k) / (double)sv[(size_t)(p * n + k)]; + n0 += b[(size_t)k] * b[(size_t)k]; + } + for (int64_t st = 0; st < S; ++st) + for (int64_t j = 0; j < n / 2; ++j) { + const int64_t ia = pairs[(size_t)((p * S + st) * n + 2 * j)]; + const int64_t ib = pairs[(size_t)((p * S + st) * n + 2 * j + 1)]; + const double t = av[(size_t)((p * S + st) * (n / 2) + j)], c = std::cos(t), sn = std::sin(t); + const double va = b[(size_t)ia], vb = b[(size_t)ib]; + b[(size_t)ia] = va * c + vb * sn; + b[(size_t)ib] = vb * c - va * sn; + } + double n1 = 0; + for (int64_t k = 0; k < n; ++k) n1 += b[(size_t)k] * b[(size_t)k]; + if (std::fabs(n1 - n0) > 1e-9 * n0) ++bad_norm; + for (int64_t g = 0; g < n / G; ++g) { + double amax = 0; + for (int64_t i = 0; i < G; ++i) amax = std::max(amax, std::fabs(b[(size_t)(g * G + i)])); + const double sc = s.at(m * (P * n / G) + p * (n / G) + g); + CHECK(std::fabs(sc - amax / qmax) < 2e-3 * amax / qmax + 1e-12); // T is f16 + for (int64_t i = 0; i < G; ++i) { + const double deq = (double)q.at(m * P * n + p * n + g * G + i) * sc; + worst = std::max(worst, std::fabs(deq - b[(size_t)(g * G + i)]) / amax); + } } } - } - CHECK_EQ(bad_norm, 0); - CHECK(worst < 0.04); // half an e4m3 step at the top of the range is 1/16 of 1/2 + CHECK_EQ(bad_norm, 0); + CHECK(worst < (i8 ? 0.006 : 0.04)); // half a step of the grid (int8: 1/254 of the maximum), and T's f16 + } - // zero angles, unit scales: exactly quant_act_fp8 - T an0(RAD_F32, {P * S, n / 2}), rs1(RAD_F32, {P, n}); - std::vector ones((size_t)(P * n), 1.0f); + // T the identity, unit scales: exactly quant_act_fp8 + std::vector eye((size_t)(P * (n / G) * G * G), 0.0f), ones((size_t)(P * n), 1.0f); + for (int64_t pg = 0; pg < P * (n / G); ++pg) + for (int64_t i = 0; i < G; ++i) eye[(size_t)((pg * G + i) * G + i)] = 1.0f; + T tid(RAD_F16, {P * n, G}), rs1(RAD_F32, {P, n}); + tid.f(eye); rs1.f(ones); T q1(RAD_F8E4M3, {M, P * n}), s1(RAD_F32, {M, P * n / G}); - A b; b.t(x).t(pr).t(an0).t(rs1).t(q1).t(s1) - .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("stages", S).i("parts", P); - CHECK_OK(run("givens_quant_act_fp8", b)); + A b; b.t(x).t(tid).t(rs1).t(q1).t(s1) + .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("parts", P).s("out", "fp8"); + CHECK_OK(run("givens_dense_quant", b)); T q2(RAD_F8E4M3, {M, n}), s2(RAD_F32, {M, n / G}); A c; c.t(x).t(q2).t(s2).i("M", M).i("n", n).i("group", G).s("dtype", "bf16"); CHECK_OK(run("quant_act_fp8", c)); From d6b506fe4fe1aeaed4d48882cfb55d5d61e04c60 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 20:33:48 +0200 Subject: [PATCH 15/17] ParoQuant dense: the gdense relayout checks the pairs with the givens pairs hook's gv_pairs_ok (a full pairing of each group, not only the range) --- libr4d/r4d_layout.cpp | 138 +++++++++++++++++++++--------------------- 1 file changed, 68 insertions(+), 70 deletions(-) diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index e5b2fde4..89acd86f 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -571,6 +571,71 @@ extern "C" int r4d_rad_unrelayout_w5(const RadParam* p, int n_p, int operand, co return RAD_OK; } +/* ---- givens pairs: ParoQuant's rotation pairs (i32 [P*S, K]), stored as they are but CHECKED. + * The rotate kernels index a group's 128 LDS slots with them unchecked, so a stage that is not a + * pairing of its own group -- an index outside the group, or one column twice -- is refused here, + * at load, rather than read out of bounds. Operand 1 of the givens rows; the rest is as stored. */ +namespace { +constexpr int GV_PAIRS_OPERAND = 1; +constexpr long long GV_GROUP = 128; + +int gv_pairs_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + if (!out || !pl) return RAD_E_INVAL; + if (operand != GV_PAIRS_OPERAND) return RAD_E_UNSUPPORTED; + const long long K = r4d_pgeti_or(p, n_p, "n", 0); + if (K <= 0 || K % GV_GROUP || !selects(enc, sel, n, "t.pairs") || pl[0].rank != 2 || + pl[0].dtype != RAD_I32 || pl[0].shape[1] != K) return RAD_E_SHAPE; + fill(out, "r4d.givens.pairs", RAD_I32, pl[0].shape[0], K, pl[0].shape[0] * K * 4); + return RAD_OK; +} + +/* Every row (a stage of a part) is, group by group, a perfect matching of the group's columns. */ +bool gv_pairs_ok(const int32_t* pairs, long long rows, long long K) { + for (long long r = 0; r < rows; ++r) + for (long long g = 0; g < K; g += GV_GROUP) { + bool seen[GV_GROUP] = {}; + for (long long i = 0; i < GV_GROUP; ++i) { + const long long c = (long long)pairs[r * K + g + i] - g; + if (c < 0 || c >= GV_GROUP || seen[c]) return false; + seen[c] = true; + } + } + return true; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_givens_pairs(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + return gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, out); +} + +extern "C" int r4d_rad_relayout_givens_pairs(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + if (!gv_pairs_ok((const int32_t*)pl[0].data, L.shape[0], L.shape[1])) return RAD_E_FORMAT; + std::memcpy(dst, pl[0].data, (size_t)L.bytes); + return RAD_OK; +} + +extern "C" int r4d_rad_unrelayout_givens_pairs(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + std::memcpy(pl[0].data, src, (size_t)L.bytes); + return RAD_OK; +} + /* ---- givens_dense: ParoQuant's rotation tables composed into one dense matrix a (part, group). * * A "givens" weight stores its rotation as pairs (i32 [P*S, K]) and angles (f32 [P*S, K/2]); the dense @@ -620,6 +685,7 @@ extern "C" int r4d_rad_relayout_gdense(const RadParam* p, int n_p, int operand, rc = gd_geom(p, n_p, enc, sel, pl, n, &P, &S, &K); if (rc != RAD_OK) return rc; const int32_t* pairs = (const int32_t*)pdata(pl[0]); + if (!gv_pairs_ok(pairs, P * S, K)) return RAD_E_FORMAT; const float* ang = (const float*)pdata(pl[1]); uint16_t* t = (uint16_t*)dst; const long long nkb = K / GD_GROUP, half = GD_GROUP / 2; @@ -631,11 +697,8 @@ extern "C" int r4d_rad_relayout_gdense(const RadParam* p, int n_p, int operand, for (long long st = 0; st < S; ++st) for (long long j = 0; j < half; ++j) { const long long row = pt * S + st, o = (size_t)(st * half + j); - const long long a = pairs[row * K + g * GD_GROUP + 2 * j] - g * GD_GROUP; - const long long b = pairs[row * K + g * GD_GROUP + 2 * j + 1] - g * GD_GROUP; - if (a < 0 || a >= GD_GROUP || b < 0 || b >= GD_GROUP || a == b) return RAD_E_FORMAT; - ia[(size_t)o] = (int)a; - ib[(size_t)o] = (int)b; + ia[(size_t)o] = (int)(pairs[row * K + g * GD_GROUP + 2 * j] - g * GD_GROUP); + ib[(size_t)o] = (int)(pairs[row * K + g * GD_GROUP + 2 * j + 1] - g * GD_GROUP); const float th = ang[row * (K / 2) + g * half + j]; cs[(size_t)o] = std::cos(th); sn[(size_t)o] = std::sin(th); @@ -829,71 +892,6 @@ extern "C" int r4d_rad_unrelayout_w2a8(const RadParam* p, int n_p, int operand, return RAD_OK; } -/* ---- givens pairs: ParoQuant's rotation pairs (i32 [P*S, K]), stored as they are but CHECKED. - * The rotate kernels index a group's 128 LDS slots with them unchecked, so a stage that is not a - * pairing of its own group -- an index outside the group, or one column twice -- is refused here, - * at load, rather than read out of bounds. Operand 1 of the givens rows; the rest is as stored. */ -namespace { -constexpr int GV_PAIRS_OPERAND = 1; -constexpr long long GV_GROUP = 128; - -int gv_pairs_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, - const RadTensor* pl, int n, RadLayout* out) { - if (!out || !pl) return RAD_E_INVAL; - if (operand != GV_PAIRS_OPERAND) return RAD_E_UNSUPPORTED; - const long long K = r4d_pgeti_or(p, n_p, "n", 0); - if (K <= 0 || K % GV_GROUP || !selects(enc, sel, n, "t.pairs") || pl[0].rank != 2 || - pl[0].dtype != RAD_I32 || pl[0].shape[1] != K) return RAD_E_SHAPE; - fill(out, "r4d.givens.pairs", RAD_I32, pl[0].shape[0], K, pl[0].shape[0] * K * 4); - return RAD_OK; -} - -/* Every row (a stage of a part) is, group by group, a perfect matching of the group's columns. */ -bool gv_pairs_ok(const int32_t* pairs, long long rows, long long K) { - for (long long r = 0; r < rows; ++r) - for (long long g = 0; g < K; g += GV_GROUP) { - bool seen[GV_GROUP] = {}; - for (long long i = 0; i < GV_GROUP; ++i) { - const long long c = (long long)pairs[r * K + g + i] - g; - if (c < 0 || c >= GV_GROUP || seen[c]) return false; - seen[c] = true; - } - } - return true; -} -} /* namespace */ - -extern "C" int r4d_rad_layout_givens_pairs(const RadParam* p, int n_p, int operand, - const RadEncoding* enc, const int* sel, - const RadTensor* pl, int n, RadLayout* out) { - return gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, out); -} - -extern "C" int r4d_rad_relayout_givens_pairs(const RadParam* p, int n_p, int operand, - const RadEncoding* enc, const int* sel, - const RadTensor* pl, int n, void* dst, - int64_t dst_bytes) { - RadLayout L; - const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L); - if (rc != RAD_OK) return rc; - if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; - if (!gv_pairs_ok((const int32_t*)pl[0].data, L.shape[0], L.shape[1])) return RAD_E_FORMAT; - std::memcpy(dst, pl[0].data, (size_t)L.bytes); - return RAD_OK; -} - -extern "C" int r4d_rad_unrelayout_givens_pairs(const RadParam* p, int n_p, int operand, - const RadEncoding* enc, const int* sel, - const void* src, int64_t src_bytes, - const RadTensor* pl, int n) { - RadLayout L; - const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L); - if (rc != RAD_OK) return rc; - if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; - std::memcpy(pl[0].data, src, (size_t)L.bytes); - return RAD_OK; -} - /* ---- MXFP4: fp4 e2m1 codes with an E8M0 exponent a 32. The codes go to fragment order, the * exponents to [K/32][N], and b_ref is each row's largest exponent -- a reduction over the plane, * which is a derivation any reader of the plane could make and so not a choice. */ From 9137948b9512e5519177a6f818eb1577bacc2076 Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Thu, 8 Oct 2026 23:24:55 +0200 Subject: [PATCH 16/17] ParoQuant dense: review fixes -- the matrices composed exactly, `out` checked, the stored form pinned * r4d_rad_relayout_gdense composes in f64 (angles widened, cos/sin and products in double) and rounds to f16: the stored matrix is a derivation of the planes, the same bytes whichever libm computed it, as abi/rad_abi.h asks of a relayout. * givens_dense_quant (libr4d and libref) refuses an `out` that does not name q's dtype instead of reading the quantiser off q alone. * relayout_parity_test pins the dense stored form by hash, checks each matrix is orthogonal to f16 accuracy and that a broken pairing is refused. * r4d_givens_dense: static_assert that a thread stages one channel scale of the group; the selftest's givens_numeric takes one mode (rotate / dense fp8 / dense i8) instead of three flags; cGivensDense sits after the Hadamard constraint with its own comment. --- libr4d/r4d_givens_dense.hip | 7 ++++- libr4d/r4d_layout.cpp | 25 +++++++++------- libr4d/r4d_rows.cpp | 8 +++-- libr4d/r4d_selftest.cpp | 35 ++++++++++++---------- libref/ref_quant.cpp | 1 + tests/relayout_parity_test.cpp | 54 ++++++++++++++++++++++++++++++++++ 6 files changed, 100 insertions(+), 30 deletions(-) diff --git a/libr4d/r4d_givens_dense.hip b/libr4d/r4d_givens_dense.hip index 9d0a3f04..5fca31cb 100644 --- a/libr4d/r4d_givens_dense.hip +++ b/libr4d/r4d_givens_dense.hip @@ -33,13 +33,15 @@ #include #include #include +#include namespace { constexpr uint32_t kGroup = 128; constexpr uint32_t kThreads = 128; constexpr uint32_t kWaves = kThreads / 32; -constexpr uint32_t kTStride = kGroup + 8; // f16 per LDS row of T: 16 B pad, conflict-free b128 reads +constexpr uint32_t kTStride = kGroup + 8; +static_assert(kThreads == kGroup, "a thread stages one channel scale of the group (invd[tid])"); // f16 per LDS row of T: 16 B pad, conflict-free b128 reads typedef _Float16 v8h_t __attribute__((ext_vector_type(8))); @@ -141,8 +143,11 @@ static int givens_dense_body(const RadArgs* a, const R4dSink& sk) { if (x->rank < 2 || q->rank != 2 || sc->rank != 2 || t->rank != 2 || rs->rank != 2) return R4D_NO(RAD_E_SHAPE); if (t->dtype != RAD_F16 || rs->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + // `out` names the quantiser and q's dtype must be it: a mismatch is refused, not read from q + const char* out = r4d_gets(a, "out"); const bool i8 = q->dtype == RAD_I8; if (!i8 && q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE); + if (!out || std::strcmp(out, i8 ? "i8" : "fp8") != 0) return R4D_NO(RAD_E_DTYPE); const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); const long long parts = r4d_geti_or(a, "parts", 1), nkb = K / kGroup; if (r4d_geti_or(a, "group", kGroup) != kGroup || K % kGroup || parts < 1) return R4D_NO(RAD_E_SHAPE); diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 89acd86f..8372cbc6 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -641,9 +641,14 @@ extern "C" int r4d_rad_unrelayout_givens_pairs(const RadParam* p, int n_p, int o * A "givens" weight stores its rotation as pairs (i32 [P*S, K]) and angles (f32 [P*S, K/2]); the dense * kernel (r4d_givens_dense.hip) applies it as T (x / D), T being the composition of the group's S * stages. The blob is [P * K/128][128 (j)][128 (i)] f16, T[j][i] = output j of the network fed the unit - * vector e_i, so a (part, group) is 32 KiB the kernel stages whole. Composed in f32 in the order the - * stages are applied (stage 0 first), a' = a c + b s, b' = b c - a s -- libref's loop -- and rounded to - * f16 once. Operand 1 of givens_dense_quant; everything else stays as stored. */ + * vector e_i, so a (part, group) is 32 KiB the kernel stages whole. Composed in the order the stages are + * applied (stage 0 first), a' = a c + b s, b' = b c - a s -- libref's loop. + * + * A DERIVATION, NOT A CHOICE (abi/rad_abi.h: a relayout derives nothing a reader of the planes could not): + * the composition is done in f64 -- the f32 angles widened, cos and sin and every product in double -- + * so its error (~1e-15) is far below an f16 step and the stored matrix is the exact composition rounded + * to f16 (by way of f32), the same bytes whichever libm or summation order computed it. Operand 1 of + * givens_dense_quant; everything else stays as stored. */ namespace { constexpr int GD_OPERAND = 1; constexpr long long GD_GROUP = 128; @@ -690,8 +695,8 @@ extern "C" int r4d_rad_relayout_gdense(const RadParam* p, int n_p, int operand, uint16_t* t = (uint16_t*)dst; const long long nkb = K / GD_GROUP, half = GD_GROUP / 2; std::vector ia((size_t)(S * half)), ib((size_t)(S * half)); - std::vector cs((size_t)(S * half)), sn((size_t)(S * half)); - std::vector v((size_t)GD_GROUP); + std::vector cs((size_t)(S * half)), sn((size_t)(S * half)); + std::vector v((size_t)GD_GROUP); for (long long pt = 0; pt < P; ++pt) for (long long g = 0; g < nkb; ++g) { for (long long st = 0; st < S; ++st) @@ -699,20 +704,20 @@ extern "C" int r4d_rad_relayout_gdense(const RadParam* p, int n_p, int operand, const long long row = pt * S + st, o = (size_t)(st * half + j); ia[(size_t)o] = (int)(pairs[row * K + g * GD_GROUP + 2 * j] - g * GD_GROUP); ib[(size_t)o] = (int)(pairs[row * K + g * GD_GROUP + 2 * j + 1] - g * GD_GROUP); - const float th = ang[row * (K / 2) + g * half + j]; + const double th = (double)ang[row * (K / 2) + g * half + j]; cs[(size_t)o] = std::cos(th); sn[(size_t)o] = std::sin(th); } uint16_t* tg = t + (size_t)(pt * nkb + g) * GD_GROUP * GD_GROUP; for (long long i = 0; i < GD_GROUP; ++i) { - std::fill(v.begin(), v.end(), 0.0f); - v[(size_t)i] = 1.0f; + std::fill(v.begin(), v.end(), 0.0); + v[(size_t)i] = 1.0; for (long long o = 0; o < S * half; ++o) { - const float va = v[(size_t)ia[(size_t)o]], vb = v[(size_t)ib[(size_t)o]]; + const double va = v[(size_t)ia[(size_t)o]], vb = v[(size_t)ib[(size_t)o]]; v[(size_t)ia[(size_t)o]] = va * cs[(size_t)o] + vb * sn[(size_t)o]; v[(size_t)ib[(size_t)o]] = vb * cs[(size_t)o] - va * sn[(size_t)o]; } - for (long long j = 0; j < GD_GROUP; ++j) tg[j * GD_GROUP + i] = f32_to_f16(v[(size_t)j]); + for (long long j = 0; j < GD_GROUP; ++j) tg[j * GD_GROUP + i] = f32_to_f16((float)v[(size_t)j]); } } return RAD_OK; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index e4d51e77..70a7dc69 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -3020,12 +3020,14 @@ static const RadConstraint cQuantActFp8[] = { * straddle the end of a row: the ragged tail the unrotated kernel writes zero-padded would mix * real values with padding inside one butterfly, and there is no weight block on the other side * that was rotated the same way. */ -static const RadConstraint cGivensDense[] = { - C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), C_IN("out", "i8 fp8"), -}; static const RadConstraint cHadQuantActFp8[] = { C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; +/* ParoQuant's dense rotation: the same whole-group rule (a rotation group cannot straddle a row's end), + * and `out` one of the two quantisers its epilogue has. */ +static const RadConstraint cGivensDense[] = { + C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), C_IN("out", "i8 fp8"), +}; /* The dtype is the INPUT's, and the input is already quantised -- so it is `fp8a8` and not `bf16` * the way every other row in this family reads it. A four-multiple `n` is the staging slot (one diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index e68f2084..ae959e49 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3774,8 +3774,11 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ * kernel's scale must match it to the rounding of its f32 sincos, and every dequantised element * must sit within the E4M3 grid of the reference (half a step at the top of the range is 1/16 of * the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */ -static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, - bool rot_only = false, bool i8 = false, bool dense = false) { +/* What givens_numeric runs: the sequential rotation to f16, or the dense rotation with either quantiser. */ +enum class GvCase { Rotate, DenseFp8, DenseI8 }; + +static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, GvCase mode) { + const bool rot_only = mode == GvCase::Rotate, i8 = mode == GvCase::DenseI8, dense = !rot_only; const char* row = dense ? "givens_dense_quant" : "givens_rotate"; if (!sel(row)) return; char nm[160]; @@ -13176,24 +13179,24 @@ static void device_phase(const Plugin& pl) { if (sel("givens_rotate")) { if (!g_case) std::printf("\nParoQuant's rotation to f16, against an f64 rotation\n"); - givens_numeric(pl, 3, 5120, 1, 8, true); - givens_numeric(pl, 5, 5120, 2, 8, true); - givens_numeric(pl, 300, 6144, 2, 8, true); + givens_numeric(pl, 3, 5120, 1, 8, GvCase::Rotate); + givens_numeric(pl, 5, 5120, 2, 8, GvCase::Rotate); + givens_numeric(pl, 300, 6144, 2, 8, GvCase::Rotate); } if (sel("givens_dense_quant")) { if (!g_case) std::printf("\nParoQuant's rotation as dense per-group matrices, int8 and E4M3 output, against libm's rotation\n"); - for (int i8 = 0; i8 < 2; ++i8) { - givens_numeric(pl, 1, 128, 1, 8, false, i8, true); - givens_numeric(pl, 5, 5120, 2, 8, false, i8, true); - givens_numeric(pl, 8, 5120, 2, 8, false, i8, true); - givens_numeric(pl, 16, 5120, 1, 8, false, i8, true); - givens_numeric(pl, 300, 6144, 2, 8, false, i8, true); - givens_numeric(pl, 2048, 5120, 1, 8, false, i8, true); - givens_numeric(pl, 2048, 5120, 2, 8, false, i8, true); - givens_numeric(pl, 64, 17408, 1, 8, false, i8, true); - givens_numeric(pl, 2048, 17408, 1, 8, false, i8, true); - givens_numeric(pl, 7, 5120, 3, 2, false, i8, true); + for (const GvCase mode : { GvCase::DenseFp8, GvCase::DenseI8 }) { + givens_numeric(pl, 1, 128, 1, 8, mode); + givens_numeric(pl, 5, 5120, 2, 8, mode); + givens_numeric(pl, 8, 5120, 2, 8, mode); + givens_numeric(pl, 16, 5120, 1, 8, mode); + givens_numeric(pl, 300, 6144, 2, 8, mode); + givens_numeric(pl, 2048, 5120, 1, 8, mode); + givens_numeric(pl, 2048, 5120, 2, 8, mode); + givens_numeric(pl, 64, 17408, 1, 8, mode); + givens_numeric(pl, 2048, 17408, 1, 8, mode); + givens_numeric(pl, 7, 5120, 3, 2, mode); } } diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index ddbd46b3..6a28a2f1 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -476,6 +476,7 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) { if (n <= 0 || P <= 0 || g != 128 || n % g != 0) return RAD_E_SHAPE; const bool i8 = q->dtype == RAD_I8; if (!i8 && q->dtype != RAD_F8E4M3) return RAD_E_DTYPE; + if (std::strcmp(p_str(a, "out", ""), i8 ? "i8" : "fp8") != 0) return RAD_E_DTYPE; // `out` names q's dtype const int64_t rows = numel(x) / n, ngrp = n / g; if (rows <= 0 || numel(tm) < P * n * g || numel(sc) < P * n || numel(q) < rows * P * n || numel(s) < rows * P * ngrp) return RAD_E_SHAPE; diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index 11d93c50..3e664d70 100644 --- a/tests/relayout_parity_test.cpp +++ b/tests/relayout_parity_test.cpp @@ -835,3 +835,57 @@ TEST(givens_pairs_are_stored_as_they_are_and_checked) { RAD_E_FORMAT); } } + +/* ParoQuant's dense rotation matrices: composed at load from the pairs and angles, exactly (f64), and + * rounded to f16 -- a derivation of the planes, pinned by hash so that a change in how they are composed + * shows here. Each stored matrix is orthogonal to f16 accuracy, and a broken pairing is refused. */ +TEST(givens_dense_matrices_are_the_exact_composition) { + const int64_t K = 256, P = 2, S = 3, PS = P * S, G = 128; + RadEncoding e = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + rad_enc_add_table(&e, "t.pairs", RAD_I32, PS, K); + rad_enc_add_table(&e, "t.angle", RAD_F32, PS, K / 2); + const int sel[2] = { rad_enc_find(&e, "t.pairs"), rad_enc_find(&e, "t.angle") }; + std::vector pairs((size_t)(PS * K)); + std::vector ang((size_t)(PS * K / 2)); + for (int64_t r = 0; r < PS; ++r) { + const int64_t mul = 2 * r + 3, add = 17 * r + 5; /* odd multiplier: a permutation */ + for (int64_t c = 0; c < K; ++c) + pairs[(size_t)(r * K + c)] = (int32_t)((c / G) * G + (c % G * mul + add) % G); + for (int64_t j = 0; j < K / 2; ++j) ang[(size_t)(r * K / 2 + j)] = 0.37f * (float)(r + 1) - 0.011f * (float)j; + } + auto tensor = [](void* d, uint32_t dt, int64_t r, int64_t c) { + RadTensor t{}; + t.data = d; + t.dtype = dt; + t.rank = 2; + t.shape[0] = r; + t.shape[1] = c; + t.stride[0] = c; + t.stride[1] = 1; + return t; + }; + RadTensor t[2] = { tensor(pairs.data(), RAD_I32, PS, K), tensor(ang.data(), RAD_F32, PS, K / 2) }; + Opts kp; + kp.i("n", K).i("parts", P); + RadLayout L{}; + REQUIRE_EQ(r4d_rad_layout_gdense(kp.data(), kp.n(), 1, &e, sel, t, 2, &L), RAD_OK); + REQUIRE_EQ(L.bytes, (int64_t)(P * K * G * 2)); + std::vector dst((size_t)L.bytes); + REQUIRE_EQ(r4d_rad_relayout_gdense(kp.data(), kp.n(), 1, &e, sel, t, 2, dst.data(), L.bytes), RAD_OK); + golden("givens dense", fnv(dst), 0x8e72bd2bb541c6e6ull); + /* T's columns are unit vectors (the composition of rotations is orthogonal), to f16 accuracy */ + const uint16_t* tm = (const uint16_t*)dst.data(); + double worst = 0; + for (int64_t pg = 0; pg < P * K / G; ++pg) + for (int64_t i = 0; i < G; ++i) { + double nrm = 0; + for (int64_t j = 0; j < G; ++j) { + const double v = rad_f16_to_f32(tm[(size_t)((pg * G + j) * G + i)]); + nrm += v * v; + } + worst = std::max(worst, std::fabs(nrm - 1.0)); + } + CHECK(worst < 2e-3); + pairs[5] = pairs[6]; /* a column twice in a stage */ + CHECK_EQ(r4d_rad_relayout_gdense(kp.data(), kp.n(), 1, &e, sel, t, 2, dst.data(), L.bytes), RAD_E_FORMAT); +} From 32fa1a27eca88210f9070fb9b925e9f251de2c1d Mon Sep 17 00:00:00 2001 From: Malic Zilyas Date: Fri, 9 Oct 2026 12:30:15 +0200 Subject: [PATCH 17/17] libr4d: 5-/4-bit decode GEMM covers all row tiles in one block cfg_for() pins MB = 1 across the decode band (M <= 64): right for the bf16 and MXFP4 skinny kernels, where the grid, not the weight, is the cost. The w5a16 / w4a16_asym kernel is dequantise-bound, and one block per 16-row tile unpacks every weight fragment once per tile, so two or three concurrent streams (M = 16..48) paid the unpack two or three times: 104 us/call at one stream, 190 us at three (profile-ops, PARO int5, 1.3.0). Cover every row tile in one block (MB = ceil(M / 16), at most 4) unless a tuned MB is pinned. The split-K bound is unchanged, so every output element is still one wave's accumulation over the same K slices: output bits are identical. PARO int5, prod shape (175k / 3 seqs), BetterBench c3 aggregate t/s at 1 / 2 / 3 streams: 96 / 156 / 155 -> 92 / 169 / 170 (+9% / +10%); same-source A/B on the dev build: c3 127 -> 166. Single-stream decode is unchanged (that GEMM streams the weights at the memory roofline, ~620 GB/s). Quality unchanged: ppl wiki 6.797 / code 1.533, GSM8K 100%, genchat 17/17 cold-verified, dia-mini v2 23/27, v3 15/15. r4d_selftest gemm_w5a16_nt_m64: pass (incl. M = 40 with 3 parts, M = 64). --- libr4d/r4d_gemm_w5a16_nt_m64.hip | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/libr4d/r4d_gemm_w5a16_nt_m64.hip b/libr4d/r4d_gemm_w5a16_nt_m64.hip index 3a037dab..4309db4c 100644 --- a/libr4d/r4d_gemm_w5a16_nt_m64.hip +++ b/libr4d/r4d_gemm_w5a16_nt_m64.hip @@ -315,6 +315,13 @@ static int w5_dispatch(const RadArgs* a, RadStream s, bool hi5) { Cfg c; rc = cfg_for(a, g.K, mc, group, BR_FLAT, &c); if (rc != RAD_OK) return rc; + /* cfg_for pins MB = 1 across the decode band (the grid, not the weight, is the cost for the bf16 and + * mxfp4 skinny kernels). Here the dequantise is: one block per row tile unpacks each weight fragment + * once PER TILE, so three streams (M = 24, two tiles) pay it twice. Cover every row tile in one block + * unless the tuner pinned MB; same split, so the output bits are unchanged. */ + R4dGemmCfg tuned; + r4d_cfg_gemm(a, &tuned); + if (tuned.mb <= 0) c.mb = std::min(4, (mc + 15) / 16); const long long Ntot = g.N, K = g.K, lda = mp.lda ? mp.lda : g.K; const long long nsz = K / R4D_GEMM_W4_GROUP; for (int p = 0; p < mp.n; ++p) {