diff --git a/NOTICE b/NOTICE index bd429121..7f3b0765 100644 --- a/NOTICE +++ b/NOTICE @@ -17,7 +17,9 @@ serving any world size from the shipped container, the request log, an uneven wo and weights split, --rope-scaling, the model entry's context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, and curl, jq and a CA bundle in the image with hfget.sh -under its busybox), hazyumps (static YaRN for the Qwen rotary paths), redxherring (--model taking a +under its busybox), hazyumps (static YaRN for the Qwen rotary paths), malic (ParoQuant: its MXFP4, +int5 and int4 checkpoints imported and served, the Givens rotation as stages and as dense per-group +matrices on the matrix cores, and the 5- and 4-bit asymmetric GEMMs), redxherring (--model taking a Hugging Face repo id), sfjes (Gemma 4 31B dense: its plugin, its two attention classes and their kernels, and prefix reuse that leaves a windowed group alone) and zivius (LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg PR 50). diff --git a/abi/rad_encoding.h b/abi/rad_encoding.h index 49538c1e..385ce5f7 100644 --- a/abi/rad_encoding.h +++ b/abi/rad_encoding.h @@ -73,6 +73,17 @@ * [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. + * TABLE "t.dense" f16 [P * cols/128 x 128*128], where a weight carries it, is the same + * rotation composed: row p * (cols/128) + g holds part p's stages over the 128 columns + * of group g as one matrix, element j * 128 + i the output j for the unit input e_i, + * composed exactly (f64) and rounded to f16. It is stored because a kernel that + * applies the rotation as a matrix must not compute one at load (rad_abi.h). * * Pure C, header-only, like the rest of abi/. */ @@ -213,6 +224,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 +349,25 @@ 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; + { + const int id = rad_enc_find(e, "t.dense"); + if (id > 0 && (e->plane[id].kind != RAD_PLANE_TABLE || e->plane[id].dtype != RAD_F16 || + e->plane[ip].extent[1] % 128 || + e->plane[id].extent[0] != np * (e->plane[ip].extent[1] / 128) || + e->plane[id].extent[1] != 128 * 128)) return 0; + } + return 1; + } return 0; } 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_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index af2a2b35..f1b01720 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -125,10 +125,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 e0212f47..d7e21973 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,28 @@ 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_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. */ + 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, rot_dense = 0; + rad_buf rot_q = 0, rot_s = 0; + rad_op op_rot = 0; + 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; @@ -728,12 +751,39 @@ 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, + * 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 = {}); + /* 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 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, const RadEncoding& enc, + 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 @@ -797,6 +847,35 @@ inline bool linear_is_mxfp4(const RadEncoding& e) { sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP; } +/* 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)) 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 pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32; +} + +/* ...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) { + const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero"); + 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, std::initializer_list src) { if (src.size() == 0) return RAD_E_INVAL; @@ -808,16 +887,116 @@ 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. */ + 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; } +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 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. */ + 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; + rot_stages = S; + *pb1 = P > 1 ? cut[0] : 0; + *pb2 = P > 2 ? cut[0] + cut[1] : 0; + 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_scale ? RAD_OK : RAD_E_INVAL; +} + +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)), + RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), + { 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 "t.dense" table, f16 [P * K/128, 128*128], + * which rad-convert composes from the givens tables (abi/rad_encoding.h). A container written before the + * table existed carries only the pairs and angles; it is refused here, naming the reconvert, rather than + * served through a matrix the kernel library would have to compute. */ +inline rad_weight LinearFP8::decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, + const RadEncoding& enc, int64_t K, RadWeightGroup grp) { + if (!rad_enc_plane(&enc, "t.dense")) { + fprintf(stderr, "radiance: '%s' carries its rotation as pairs and angles only, and the dense " + "quantiser reads it composed (a \"t.dense\" table); convert it again with this " + "rad-convert -- --reuse copies every other weight\n", wn); + return 0; + } + return decl_view(b, nm.f("%s.rot_dense", base), wn, "t.dense", RAD_F16, + { rot_parts * (K / RAD_FP8_BLOCK), RAD_FP8_BLOCK * RAD_FP8_BLOCK }, + 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, 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; @@ -929,6 +1108,67 @@ 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; + 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; + 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, 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, 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. */ + 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; + rot_dense = decl_dense(b, nm, base, wn, enc, 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; + } + return RAD_OK; + } + /* 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) { @@ -941,9 +1181,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 +1221,21 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha } parts[np++] = p; } + int64_t pb1 = 0, pb2 = 0; + if (paro) { + 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, base, wn, enc, N, K, grp, cut, &pb1, &pb2)); + const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; + rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, rot_parts * K }); + rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, rot_parts * (K / RAD_FP8_BLOCK) }); + if (!rot_q || !rot_s) return RAD_E_INVAL; + rot_dense = decl_dense(b, nm, base, wn, enc, K, grp); + if (!rot_dense) return RAD_E_INVAL; + op_rot = decl_dense_op(b, g, a, "fp8", 1, rows, { rot_q, rot_s }); + if (!op_rot) return RAD_E_INVAL; + } const char* sn = nm.f("%s.scale", base); const char* rn = nm.f("%s.ref", base); w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN, @@ -989,12 +1259,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)); } - const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; - 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 }); + /* 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; } @@ -1096,9 +1363,33 @@ 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_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)), + 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) { - 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_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), RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref)); return; } diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index e13476a0..f6cd90d7 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -585,6 +585,26 @@ void Checkpoint::detect_import() { } else { import_why_ = "compressed-tensors: " + why; } + } 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 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 + * 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 @@ -608,7 +628,51 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, return RAD_OK; } - if (import_ == Import::QuarkMx) { + 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.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 * dtypes and the logical width; no byte moves. Its excluded layers are plain tensors. */ @@ -850,7 +914,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); @@ -862,6 +926,121 @@ 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 */ + +/* ONE (PART, GROUP)'S STAGES COMPOSED INTO ITS DENSE MATRIX: out[j * 128 + i] is output j of the + * stages fed the unit vector e_i, applied in table order (stage 0 first) as a' = a cos t + b sin t, + * b' = b cos t - a sin t -- libref's loop. In f64 throughout (the f32 angles widened, cos, sin and + * every product in double), so the error (~1e-15) is far below an f16 step and the bytes are the + * exact composition rounded to f16 by way of f32, whichever libm or summation order computed it. */ +void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const float* th, + uint16_t* out) { + constexpr int64_t G = kParoGroup, H = kParoGroup / 2; + std::vector cs((size_t)(S * H)), sn((size_t)(S * H)), v((size_t)G); + for (int64_t o = 0; o < S * H; ++o) { + cs[(size_t)o] = std::cos((double)th[o]); + sn[(size_t)o] = std::sin((double)th[o]); + } + for (int64_t i = 0; i < G; ++i) { + std::fill(v.begin(), v.end(), 0.0); + v[(size_t)i] = 1.0; + for (int64_t o = 0; o < S * H; ++o) { + const double va = v[(size_t)ia[o]], vb = v[(size_t)ib[o]]; + v[(size_t)ia[o]] = va * cs[(size_t)o] + vb * sn[(size_t)o]; + v[(size_t)ib[o]] = vb * cs[(size_t)o] - va * sn[(size_t)o]; + } + for (int64_t j = 0; j < G; ++j) out[j * G + i] = rad_f32_to_f16((float)v[(size_t)j]); + } +} + +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); + /* THE DENSE MATRICES, composed here and stored: the prefill quantiser (givens_dense_quant) applies a + * (part, group)'s stages as one 128 x 128 matrix, and a matrix is a number a kernel library must + * not choose at load (abi/rad_abi.h, weight layout) -- the pairs and angles stay for the stage-wise + * rotation the 16-bit GEMMs read. */ + if (rad_enc_add_table(&e, "t.dense", RAD_F16, P * K / kParoGroup, kParoGroup * kParoGroup) < 0) + return refuse("'" + out->name + "' has more planes than an encoding holds"); + 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) { @@ -897,6 +1076,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; @@ -979,6 +1166,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.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->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. */ @@ -1012,6 +1218,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 @@ -1033,7 +1243,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" + @@ -1048,7 +1261,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 (p0.ct_group) { /* CT-INT4, IMPORTED: one group throughout and joined only along rows, as GPTQ's. The codes @@ -1250,6 +1464,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 */ @@ -1290,13 +1509,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) @@ -1323,7 +1544,116 @@ 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 && 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] + * 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 + * 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 if (role == "t.dense") { + /* row r is part r / (K/128), group r % (K/128): its stages, group-local, composed */ + const int64_t nkb = K / kParoGroup, H = kParoGroup / 2, q = r / nkb, g = r % nkb; + const int16_t* pv = (const int16_t*)w.pq_pairs[(size_t)q]->data; + const SrcTensor& th = *w.pq_theta[(size_t)q]; + std::vector ia((size_t)(S * H)), ib((size_t)(S * H)); + std::vector an((size_t)(S * H)); + for (int64_t st = 0; st < S; ++st) + for (int64_t j = 0; j < H; ++j) { + const int64_t at = st * H + j; + ia[(size_t)at] = pv[st * K + g * kParoGroup + 2 * j]; + ib[(size_t)at] = pv[st * K + g * kParoGroup + 2 * j + 1]; + an[(size_t)at] = rad_load_f32(th.data, th.rad_dtype, st * (K / 2) + g * H + j); + } + paro_compose_dense(S, ia.data(), ib.data(), an.data(), (uint16_t*)o); + o += kParoGroup * kParoGroup * 2; + } 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 @@ -1392,6 +1722,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 339a8400..956c4260 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -62,6 +62,12 @@ struct SrcTensor { * RAD_I4; `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for * any other tensor. */ int64_t ct_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). */ + 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 { int64_t n = 1; @@ -134,11 +140,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, CtInt4 }; + enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4 }; Import imports() const { return import_; } const std::string& import_refusal() const { return import_why_; } @@ -193,6 +200,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; }; @@ -212,6 +226,11 @@ std::string ckpt_tensor_of(const SrcTensor& t); bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set& names, std::unordered_set* hit = nullptr); +/* One (part, group) of a ParoQuant rotation as its dense matrix: `S` stages of 64 pairs, the pair's two + * group-local columns `ia`/`ib` and angle `th`, stage-major; out[j * 128 + i] (f16) is output j for the + * unit vector e_i. It is the "givens" encoding's "t.dense" table, row for row. */ +void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const float* th, uint16_t* out); + /* Logical rows [r0, r0 + nr) of `w` as f32 [nr, cols], whatever the pieces are stored as: a * plain float widened, FP8 times its block scale, a GGUF block type dequantised. */ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, 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/data/recipes/q38-27b-paro-mxfp4-df2.recipe b/data/recipes/q38-27b-paro-mxfp4-df2.recipe new file mode 100644 index 00000000..bf017745 --- /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_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 +# 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 185661b2..faf6cccc 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -345,12 +345,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.** Two 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_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 | The width is read per tensor, so a release mixing int4 experts with int8 projections imports both. @@ -360,13 +362,21 @@ 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 + +# 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 3c96d423..ba0589db 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. @@ -376,10 +379,40 @@ 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_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_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_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 composes them once, in f64, +and stores them as the weight's `t.dense` table, which the layout hook (`r4d_rad_layout_gdense`) only +moves. 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 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. + ### The int8 and gated fp8 fusions — device-only | op | params | operands | @@ -435,7 +468,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_check.cpp b/libavx/avx_check.cpp index 52174e0e..a83ac685 100644 --- a/libavx/avx_check.cpp +++ b/libavx/avx_check.cpp @@ -771,6 +771,55 @@ static bool hand_cases(const Lib& ref, const Lib& avx, bool verbose, int* n_chec hs.push_back(std::move(s)); } + /* ---- ParoQuant's rotation over real pairings: every stage of every group a permutation of + * its 128 columns read as pairs, two parts of three stages. The dense form over a drawn matrix + * a (part, group) -- the op takes whatever matrices the weight stores. --------------------- */ + { + const int64_t M = 5, K = 256, S = 3, P = 2, G = 128; + std::vector pr((size_t)(P * S * K)); + for (int64_t ps = 0; ps < P * S; ++ps) + for (int64_t g = 0; g < K / G; ++g) { + std::vector perm((size_t)G); + for (int64_t i = 0; i < G; ++i) perm[(size_t)i] = (int32_t)i; + uint64_t x = 0x9E3779B97F4A7C15ull * (uint64_t)(ps * 31 + g + 1); + for (int64_t i = G - 1; i > 0; --i) { + x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29; + std::swap(perm[(size_t)i], perm[(size_t)(x % (uint64_t)(i + 1))]); + } + for (int64_t i = 0; i < G; ++i) + pr[(size_t)(ps * K + g * G + i)] = (int32_t)(g * G + perm[(size_t)i]); + } + const auto h63 = hfill(63); + const auto scl = [h63](int64_t i) { return 1.25f + 0.75f * h63(i); }; /* (0.5, 2) */ + const auto zero = [](int64_t) { return 0.0f; }; + for (uint32_t ydt : { (uint32_t)RAD_F16, (uint32_t)RAD_F32 }) { + Hand h(ydt == RAD_F16 ? "two parts of three stages, y f16" : "two parts of three stages, y f32", + "givens_rotate", 1e-5); + h.dense(RAD_BF16, { M, K }, hfill(61)) + .dense(RAD_I32, { P * S, K }, [pr](int64_t i) { return (float)pr[(size_t)i]; }) + .dense(RAD_F32, { P * S, K / 2 }, hfill(62, 3.0f)) + .dense(RAD_F32, { P, K }, scl) + .dense(ydt, { M, P * K }, zero, true) + .pi("M", M).pi("n", K).pi("group", G).ps("dtype", "bf16").pi("stages", S) + .pi("parts", P); + hs.push_back(std::move(h)); + } + /* A code may sit on a rounding edge that libref's f64 sum and libavx's f32 sum land on + * either side of, one step of the grid: the tolerance is a few such codes in 2560. */ + for (const char* outq : { "fp8", "i8" }) { + const bool i8 = outq[0] == 'i'; + Hand h(i8 ? "two parts, i8" : "two parts, fp8", "givens_dense_quant", 5e-3); + h.dense(RAD_BF16, { M, K }, hfill(64)) + .dense(RAD_F16, { P * K, G }, hfill(65, 0.1f)) + .dense(RAD_F32, { P, K }, scl) + .dense(i8 ? RAD_I8 : RAD_F8E4M3, { M, P * K }, zero, true) + .dense(RAD_F32, { M, P * K / G }, zero, true) + .pi("M", M).pi("n", K).pi("group", G).ps("dtype", "bf16").pi("parts", P) + .ps("out", outq); + hs.push_back(std::move(h)); + } + } + bool ok = true; int fails = 0; for (Hand& h : hs) { 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_isa.h b/libavx/avx_isa.h index 68a93cae..b653936c 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -97,7 +97,7 @@ int avx_isa_force(int level); /* ---- quantisation and rotation */ \ X(quant_act_i8) X(had_quant_act_i8) X(quant_act_fp8) X(had_quant_act_fp8) \ X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) X(dequant) \ - X(rmsnorm_quant_fp8) X(gated_quant_fp8) \ + X(rmsnorm_quant_fp8) X(gated_quant_fp8) X(givens_rotate) X(givens_dense_quant) \ /* ---- gemm and the vocabulary edges */ \ X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \ X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \ diff --git a/libavx/avx_quant.cpp b/libavx/avx_quant.cpp index 30b694bb..f362eaf3 100644 --- a/libavx/avx_quant.cpp +++ b/libavx/avx_quant.cpp @@ -551,6 +551,126 @@ AVX_KERNEL(had_quant_act_fp8) { return RAD_OK; } +/* ------------------------------------------------------------- givens_rotate */ +/* ParoQuant's activation side for a 16-bit GEMM: each row divided by its channel scales and rotated + * by `stages` rounds of disjoint Givens pairs, once a part, the parts side by side in y. libref's + * arithmetic (ref_quant.cpp) in its order: the divide, then a' = a cos t + b sin t, + * b' = b cos t - a sin t in f32, stage by stage. A pair walk is a gather and a scatter with nothing + * to vectorise; what is hoisted is the cos and sin of every angle, a property of the weight and the + * same for every row, so they are taken once a call rather than once a row. */ +AVX_KERNEL(givens_rotate) { + if (!rad_args_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], *y = &a->t[4]; + const int64_t n = p_int(a, "n", 0), S = p_int(a, "stages", 0), P = p_int(a, "parts", 1); + 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; + const int64_t NP = P * S * (n / 2); + if (numel(pr) < P * S * n || numel(an) < NP || numel(sc) < P * n) return RAD_E_SHAPE; + const int64_t rows = numel(x) / n; + if (rows <= 0 || numel(y) < rows * P * n) return RAD_E_SHAPE; + + int32_t* idx = (int32_t*)scratch_raw((size_t)(P * S * n) * sizeof(int32_t) + + (size_t)(2 * NP + P * n) * sizeof(float) + 64); + float* cs = (float*)(idx + P * S * n); + float* sn = cs + NP; + float* rs = sn + NP; + for (int64_t i = 0; i < P * S * n; ++i) { + const int64_t c = ldi(pr, i); + if (c < 0 || c >= n) return RAD_E_INVAL; + idx[i] = (int32_t)c; + } + for (int64_t j = 0; j < NP; ++j) { + const float th = ldt(an, j); + cs[j] = std::cos(th); + sn[j] = std::sin(th); + } + for (int64_t k = 0; k < P * n; ++k) rs[k] = ldt(sc, k); + + AVX_PARALLEL_FOR_IF(rows * P * n * S >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)n); + float* out = scratch_f32_b((size_t)(P * n)); + const float* v = in_row(x, rowoff(x, r, n), n, buf); + for (int64_t p = 0; p < P; ++p) { + float* w = out + p * n; + for (int64_t k = 0; k < n; ++k) w[k] = v[k] / rs[p * n + k]; + for (int64_t st = 0; st < S; ++st) { + const int32_t* ip = idx + (p * S + st) * n; + const int64_t a0 = (p * S + st) * (n / 2); + for (int64_t j = 0; j < n / 2; ++j) { + const float c = cs[a0 + j], s1 = sn[a0 + j]; + const float va = w[ip[2 * j]], vb = w[ip[2 * j + 1]]; + w[ip[2 * j]] = va * c + vb * s1; + w[ip[2 * j + 1]] = vb * c - va * s1; + } + } + } + out_row(y, rowoff(y, r, P * n), P * n, out); + } + return RAD_OK; +} + +/* --------------------------------------------------------- givens_dense_quant */ +/* The quantising form: the rotation as one dense 128 x 128 f16 matrix a (part, group) -- `tdense`, + * which rad-convert composes from the pairs and angles and stores as the weight's "t.dense" table -- + * then the block-scaled quantiser `out` names: "fp8" E4M3 with scale amax / 448, "i8" scale + * amax / 127 rounded to nearest; scale 1 for an all-zero group, as libref. The matrices are widened + * to f32 once a call; a row is then a matrix-vector product a group, in f32 where libref sums in + * f64, so a code can differ from libref's where the value sits on a rounding edge. */ +AVX_KERNEL(givens_dense_quant) { + if (!rad_args_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 char* outs = p_str(a, "out", ""); + if (std::strcmp(outs, 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; + const float qmax = i8 ? 127.0f : 448.0f; + + float* T = (float*)scratch_raw((size_t)(P * n * g + P * n) * sizeof(float) + 64); + float* rs = T + P * n * g; + for (int64_t i = 0; i < P * n; ++i) { + row_to_f32(tm->dtype, byte_at(tm->data, tm->dtype, rowoff(tm, i, g)), T + i * g, g); + rs[i] = ldt(sc, i); + } + + AVX_PARALLEL_FOR_IF(rows * P * n * g >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)n); + float* out = scratch_f32_b((size_t)(P * n)); + float* in = scratch_f32_c((size_t)g); + const float* v = in_row(x, rowoff(x, r, n), n, buf); + 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[i] = v[gi * g + i] / rs[p * n + gi * g + i]; + float* yv = out + p * n + gi * g; + const float* Tg = T + (p * n + gi * g) * g; + for (int64_t j = 0; j < g; ++j) { + vf acc = vf_zero(); + for (int64_t i = 0; i < g; i += VF_N) + acc = vf_fma(vf_loadu(Tg + j * g + i), vf_loadu(in + i), acc); + yv[j] = vf_hsum(acc); + } + const float amax = row_amax(yv, g); + 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 t = yv[j] * inv; + t = t > qmax ? qmax : (t < -qmax ? -qmax : t); + yv[j] = i8 ? std::nearbyint(t) : t; + } + stt(s, rowoff(s, r, P * ngrp) + (p * ngrp + gi) * laststride(s), scl); + } + out_row(q, rowoff(q, r, P * n), P * n, out); + } + 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 a diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 9ae6973d..49fcff0c 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -181,6 +181,16 @@ static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group static const RadOperandSpec oQuant[] = { OPD("x"), OUT("q"), OUT("scale"), OUT_O("asum") }; static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") }; static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; +/* ParoQuant's rotation, libref's declaration: the tables are the "givens" encoding's + * (abi/rad_encoding.h) and WEIGHT operands, resolved and placed with the weight they belong to. */ +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") }; +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") }; /* The fp8 fusions: the unfused pair's operands minus the tensor between them, and `out_bf16` to * put even that back. */ @@ -218,6 +228,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") }; @@ -565,6 +577,13 @@ static const RadOpSchema kSchemas[] = { "the 1/group is folded into the stored weight scale at convert (docs/OPS.md)." }, { "gram_accum", ARR(pQuant), ARR(oGram), "h += x^T x over a dequantised E4M3 activation. `h` is [n, n] and INOUT." }, +{ "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, then the block-scaled quantiser `out` names " + "(\"i8\": amax / 127, round to nearest; \"fp8\": E4M3, amax / 448)." }, +{ "givens_rotate", ARR(pGivensRotate), ARR(oGivensRotate), + "ParoQuant's rotation without a quantiser: x / rscale rotated by `stages` rounds of Givens " + "pairs, `parts` copies side by side, in y's own dtype." }, { "had_quant_act_i8", ARR(pQuant), ARR(oHadQuant), "Walsh-Hadamard rotation at width `group`, then symmetric int8 with ONE scale per row carrying " "the 1/sqrt(group)." }, @@ -589,7 +608,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]." }, @@ -782,6 +801,13 @@ SIMPLE("avx_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", L(had_quant_act_fp8)), +SIMPLE("avx_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", L(givens_rotate)), +SIMPLE("avx_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", + L(givens_dense_quant)), SIMPLE("avx_gram_accum", "gram_accum", "quant", "h += x^T x over a dequantised E4M3 activation, or a plain bf16 one", "fp8_e4m3 plus an f32 scale per group, or bf16 with no scale, in; an f32 [n][n] " diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index b228c10e..2fb9865c 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -114,6 +114,9 @@ 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_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}" @@ -130,6 +133,7 @@ set(R4D_UNITS "r4d_gemm_fp8a16_nt_m1|" "r4d_gemm_fp8a8|" "r4d_quant_act_fp8|" + "r4d_givens_rotate|" "r4d_fused_quant_fp8|" "r4d_gram_accum_fp8|" "r4d_qsa_block_key_bf16|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 4827de66..1ec00bf4 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -592,7 +592,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 @@ -601,8 +602,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_fp8_args.h b/libr4d/r4d_fp8_args.h index 05c95a85..84d163e0 100644 --- a/libr4d/r4d_fp8_args.h +++ b/libr4d/r4d_fp8_args.h @@ -45,6 +45,9 @@ enum { FP8_OPS_BLOCK_SCALE = 0, FP8_OPS_ROW_SCALE = 1 }; static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale, int wscale = FP8_OPS_BLOCK_SCALE) { std::memset(g, 0, sizeof(*g)); + /* No fp8 or int8 block GEMM reads a partitioned weight's `pb1`/`pb2`; refused, not ignored (see + * gemm_ops). */ + if (r4d_geti_or(a, "pb1", 0) > 0 || r4d_geti_or(a, "pb2", 0) > 0) return R4D_NO(RAD_E_UNSUPPORTED); g->a = r4d_opt(a, F_A); g->ascale = r4d_opt(a, F_ASCALE); g->b = r4d_opt(a, F_B); diff --git a/libr4d/r4d_gemm_args.h b/libr4d/r4d_gemm_args.h index 3c534d32..37c21ae7 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,18 +340,83 @@ 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 */ +}; + +/* 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) { + p->n = 1; + p->n0[0] = 0; + p->n1[0] = g->N; + p->lda = 0; + 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); + 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]) { + 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 * rad-convert wrote from RadLayout.bytes, and re-deriving it from N and K would be a second * source for one number. */ -static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised) { +/* `parts`: the caller reads a partitioned weight's `pb1`/`pb2` (mx_parts). Any other row REFUSES them + * rather than ignore them -- a part bound it does not apply would multiply every row of the weight by + * the first copy of the activation. */ +static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised, int parts = 0) { std::memset(g, 0, sizeof(*g)); + if (quantised && !parts && (r4d_geti_or(a, "pb1", 0) > 0 || r4d_geti_or(a, "pb2", 0) > 0)) + return R4D_NO(RAD_E_UNSUPPORTED); if (quantised) { g->a = r4d_opt(a, Q_A); g->ascale = r4d_opt(a, Q_ASCALE); diff --git a/libr4d/r4d_gemm_mxfp4a8_decode.hip b/libr4d/r4d_gemm_mxfp4a8_decode.hip index 52e56f0a..d68d6fd9 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; @@ -155,7 +155,7 @@ static __device__ __forceinline__ void mxd_epilogue( o.y = bf16x2_rne_nan(v[2], v[3]); o.z = bf16x2_rne_nan(v[4], v[5]); o.w = bf16x2_rne_nan(v[6], v[7]); - *(mxd_u4*)(C + (size_t)m * N + nb) = o; + *(mxd_u4*)(C + (size_t)m * ldc + nb) = o; } } } @@ -195,7 +195,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])); } } } @@ -220,7 +220,8 @@ void r4d_gemm_mxfp4a8_decode_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, 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; @@ -266,7 +267,7 @@ void r4d_gemm_mxfp4a8_decode_kernel( 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 @@ -290,7 +291,7 @@ void r4d_gemm_mxfp4a8_decode_kernel( 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}; @@ -323,7 +324,7 @@ void r4d_gemm_mxfp4a8_decode_kernel( __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); } @@ -340,7 +341,8 @@ void r4d_gemm_mxfp4a8_decode1_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, 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; @@ -403,7 +405,7 @@ void r4d_gemm_mxfp4a8_decode1_kernel( 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; @@ -414,7 +416,7 @@ void r4d_gemm_mxfp4a8_decode1_kernel( 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 = [&]() { @@ -472,7 +474,7 @@ void r4d_gemm_mxfp4a8_decode1_kernel( __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); } @@ -530,7 +532,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) @@ -565,10 +567,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_) \ @@ -602,38 +604,58 @@ extern "C" int r4d_gemm_mxfp4a8_decode_max_m(void) { return R4D_MXD_MTILE * R4D_ // ============================================================== the plugin ABI entry point extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) { GemmOps g; - int rc = gemm_ops(a, &g, 1); + int rc = gemm_ops(a, &g, 1, /*parts=*/1); if (rc != RAD_OK) return rc; if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE); + if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL); + MxParts mp; + rc = mx_parts(a, &g, &mp); + if (rc != RAD_OK) return rc; if (g.K % 64) return R4D_NO(RAD_E_SHAPE); if (g.M > r4d_gemm_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; + long long bound[4]; + mx_part_bounds(N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound); + int64_t worst = 0; + for (int i = 0; i < 3; ++i) { + const long long np = bound[i + 1] - bound[i]; + if (np < 16) continue; + int ks = 1; + for (int m = 1; m <= (int)M; ++m) { + const int k = 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..345bda3c 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; \ @@ -300,7 +308,7 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l // is no adapter directory between the core and these launches. extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) { GemmOps g; - int rc = gemm_ops(a, &g, 1); + int rc = gemm_ops(a, &g, 1, /*parts=*/1); if (rc != RAD_OK) return rc; if (g.N % 16) return R4D_NO(RAD_E_SHAPE); if (g.M > r4d_gemm_mxfp4a8_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE); @@ -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 01c0fab1..f5a0ec95 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) { @@ -312,7 +312,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( o.y = bf16x2_rne_nan(v[2], v[3]); o.z = bf16x2_rne_nan(v[4], v[5]); o.w = bf16x2_rne_nan(v[6], v[7]); - *(mxt_u4*)(C + (size_t)m * N + nb) = o; + *(mxt_u4*)(C + (size_t)m * ldc + nb) = o; } } } @@ -323,17 +323,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) @@ -361,7 +364,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); } @@ -370,34 +373,46 @@ 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 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); + int rc = gemm_ops(a, &g, 1, /*parts=*/1); if (rc != RAD_OK) return rc; if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE); - if (g.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) 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; - 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)); + 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_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 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); return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K); diff --git a/libr4d/r4d_gemm_w5a16_nt_m64.hip b/libr4d/r4d_gemm_w5a16_nt_m64.hip new file mode 100644 index 00000000..46b72580 --- /dev/null +++ b/libr4d/r4d_gemm_w5a16_nt_m64.hip @@ -0,0 +1,347 @@ +// 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; +} + +// 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. + +// 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'. 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; +} +__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_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_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_w5a16_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_w5a16_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, /*parts=*/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; + /* 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) { + 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_gemm_wpa8i8_tiled.hip b/libr4d/r4d_gemm_wpa8i8_tiled.hip new file mode 100644 index 00000000..40665f8e --- /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_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: +// +// * 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, 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 +static int wpa8i8_dispatch(const RadArgs* a, RadStream s) { + GemmOps g; + int rc = gemm_ops(a, &g, 1, /*parts=*/1); + if (rc != RAD_OK) return rc; + if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE); + if (!g.ascale) return R4D_NO(RAD_E_INVAL); + 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) 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]; + 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_dense.hip b/libr4d/r4d_givens_dense.hip new file mode 100644 index 00000000..3ca47151 --- /dev/null +++ b/libr4d/r4d_givens_dense.hip @@ -0,0 +1,173 @@ +// 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_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 +// 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 Givens stages and stores them as the +// encoding's `t.dense` table, [parts * K / 128][128 (j)][128 (i)] f16, which the layout +// (r4d_layout.cpp, r4d.givens.dense) takes as it is, 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 +#include + +namespace { + +constexpr uint32_t kGroup = 128; +constexpr uint32_t kThreads = 128; +constexpr uint32_t kWaves = kThreads / 32; +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))); + +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); + // `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); + 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_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 700a4ce9..f77b7a47 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) @@ -342,6 +354,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 +384,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; @@ -395,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; } @@ -437,6 +473,214 @@ 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) { + if (!sz_zeros_fit(g, pl[1], 5)) return RAD_E_FORMAT; + 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 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 uint32_t q = rad_load_bits(row, 5, k); + 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); + } + } + 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; +} + +/* ---- 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 as one dense matrix a (part, group). + * + * The dense kernel (r4d_givens_dense.hip) applies a part's Givens stages over each group of 128 columns as + * T (x / D), T being their composition. rad-convert composes T and stores it as the "givens" encoding's + * "t.dense" table, f16 [P * K/128, 128 * 128], row p * (K/128) + g element j * 128 + i the output j for the + * unit input e_i (abi/rad_encoding.h) -- which is the order the kernel stages a (part, group), 32 KiB, whole. + * So the layout is the table as stored: a relayout that moves bytes and derives none (abi/rad_abi.h). + * 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* K) { + if (n != 1 || std::strncmp(r4d_enc::role(enc, sel, 0), "t.dense", 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 (!dims(pl[0], *P * (*K / GD_GROUP), GD_GROUP * GD_GROUP) || pl[0].dtype != RAD_F16) 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, K; + const int rc = gd_geom(p, n_p, enc, sel, pl, n, &P, &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; + std::memcpy(dst, pdata(pl[0]), (size_t)L.bytes); + 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. */ @@ -615,6 +859,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_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. */ +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 +889,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 fb502104..21980a6d 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -236,6 +236,12 @@ 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_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); @@ -346,6 +352,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_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*); @@ -412,10 +420,26 @@ 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_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*, 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 af046483..0642e474 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -706,12 +706,19 @@ static const RadOperandSpec oGemmNt[] = { { "y", RAD_OPD_OUT, 0 }, }; +/* `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. */ 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, @@ -1047,6 +1054,45 @@ static const RadOperandSpec oQuantActFp8[] = { { "scale", RAD_OPD_OUT, 0 }, }; +/* `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 }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "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 }, +}; + +/* `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 -- the givens encoding's "t.dense" table, + * which rad-convert composes -- 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. * @@ -2461,6 +2507,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", 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_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 " + "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 " @@ -3109,6 +3166,19 @@ 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 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"), }; @@ -3172,6 +3242,11 @@ static const RadConstraint cQuantActFp8[] = { 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 @@ -5039,6 +5114,53 @@ 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, 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 " + "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, 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): " + "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, 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 " + "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, 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", "M <= 64; N a multiple of 16; K divisible by SK*128; weight pre-permuted into fragment order, " @@ -5518,6 +5640,29 @@ 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 }, +{ "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", + "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, 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", "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 1a6e93ff..882c3caa 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -1105,6 +1105,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) { @@ -3844,11 +3880,17 @@ 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 PartCut cut(N, pb1, pb2); + const int parts = cut.parts; char nm[160]; std::string ex; for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival); + if (parts > 1) ex += " parts=" + std::to_string(parts); std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld tn=%d%s%s", row, (long long)M, (long long)N, (long long)K, tn, ablk ? " ascale=row x 128" : "", ex.c_str()); const RadKernelInfo* r = find(pl, row); @@ -3873,20 +3915,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); @@ -3903,8 +3946,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() }), }; @@ -3912,6 +3955,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)); @@ -3942,11 +3987,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 = 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); - 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; @@ -3961,6 +4007,468 @@ 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). */ +/* 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]; + 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; + 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) * (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); + 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, 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(); + 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 as a container stores them (the "t.dense" table, abi/rad_encoding.h): one + // 128x128 f16 matrix a (part, group), row p * ng + g, element [j][i] the image of column i + // under the stages, composed in f64 as rad-convert does. Through the row's own layout hook. + std::vector dm((size_t)(parts * ng * G * G)); + std::vector v((size_t)G); + for (int p = 0; p < parts; ++p) + for (int64_t g = 0; g < ng; ++g) + for (int64_t i = 0; i < G; ++i) { + std::fill(v.begin(), v.end(), 0.0); + v[(size_t)i] = 1.0; + for (int st = 0; st < stages; ++st) + for (int64_t j = g * G / 2; j < (g + 1) * G / 2; ++j) { // group g's pairs + const int64_t ia = pairs[(size_t)((p * stages + st) * K + 2 * j)] - g * G; + const int64_t ib = pairs[(size_t)((p * stages + st) * K + 2 * j + 1)] - g * G; + const double t = ang[(size_t)((p * stages + st) * (K / 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) + dm[(size_t)(((p * ng + g) * G + j) * G + i)] = rad_f32_to_f16((float)v[(size_t)j]); + } + Planes pp; + pp.enc = rad_enc_plain(RAD_BF16); + rad_enc_add_table(&pp.enc, "t.dense", RAD_F16, parts * ng, G * G); + pp.data.assign(2, {}); + pp.rows = { 0, parts * ng }; + pp.cols = { 0, G * G }; + pp.data[1].assign((const uint8_t*)dm.data(), (const uint8_t*)(dm.data() + dm.size())); + std::vector lp = { PI("n", K), PI("parts", parts) }; + std::vector blob; + const int rl = stored(r, lp, 1, pp, { "t.dense" }, &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(); + 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) * (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); + + 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)])); + 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)]; + 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(), 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[128]; + std::snprintf(d, sizeof d, "scale rel %.2e, value/amax %.3f", worst_scale, worst_val); + 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); +} + + +/* 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 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; + 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); + 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 = 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); + 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); +} + + +/* 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 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; + 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); + 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 = 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 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)]; + } + 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 @@ -13081,6 +13589,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. */ @@ -13522,6 +14041,58 @@ 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); + 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, 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 (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); + } + } + if (sel("gram_accum")) { if (!g_case) std::printf("\nthe GPTQ calibration accumulator, against an f64 host Gram\n"); gram_accum_case(pl); 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 0fc2066b..907b25c4 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -106,6 +106,8 @@ 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_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); int ref_gemm_nt_q_gated (const RadArgs*, RadStream); @@ -240,6 +242,8 @@ 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_dense_quant); +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 f01559b0..221eda82 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -410,6 +410,110 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------- 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: 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. 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); + 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; + 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) { + 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 k = 0; k < n; ++k) st_dt(q->dtype, q->data, qb + (p * n + k) * qs, buf[(size_t)k]); + } + } + return RAD_OK; +} + +/* 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 rad-convert composes from the givens tables and stores as "t.dense". */ +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; + 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; + 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 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 42dd25c3..aa89fb4c 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -210,6 +210,17 @@ 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 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 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") }; +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") }; /* ---- the fp8 fusions ---------------------------------------------------------------------- * A fused op's operands are the unfused pair's minus the tensor between them, and `out_bf16` @@ -273,7 +284,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, @@ -825,6 +839,17 @@ 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_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 " + "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), "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 " @@ -866,7 +891,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 " @@ -1201,6 +1226,13 @@ 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_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_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 3c7d6ce2..32f403e7 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -890,6 +890,18 @@ 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_dense_quant_shape(const RadParam*, int, int, RadOpdDesc*) { + 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: 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) { 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/checkpoint_test.cpp b/tests/checkpoint_test.cpp index aeec27c5..316bdbf2 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 @@ -845,3 +846,419 @@ TEST(a_ct_int4_checkpoint_this_does_not_read_is_refused) { remove_checkpoint(dir); } } + +/* 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, 7); + + 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); + /* t.dense: each (part, group) row is that part's stages composed, so T x is x rotated stage by + * stage -- checked on a vector against the tables above, in f64, to the f16 the matrix is in */ + REQUIRE_EQ(std::string(w.enc.plane[6].role), std::string("t.dense")); + { + const uint16_t* td = (const uint16_t*)pl[6].data(); + const int64_t nkb = K / 128; + double worst_d = 0; + for (int64_t part = 0; part < 2; ++part) + for (int64_t g = 0; g < nkb; ++g) { + std::vector x(128), y(128, 0.0); + for (int i = 0; i < 128; ++i) x[(size_t)i] = std::sin(0.7 * i + part + 3.0 * g); + for (int j = 0; j < 128; ++j) + for (int i = 0; i < 128; ++i) + y[(size_t)j] += rad_f16_to_f32(td[((part * nkb + g) * 128 + j) * 128 + i]) * x[(size_t)i]; + std::vector v = x; + for (int64_t st = 0; st < S; ++st) + for (int j = 0; j < 64; ++j) { + const int64_t row = part * S + st; + const int a = tp[row * K + g * 128 + 2 * j] - (int)(g * 128); + const int b = tp[row * K + g * 128 + 2 * j + 1] - (int)(g * 128); + const double t = ta[row * (K / 2) + g * 64 + j], va = v[(size_t)a], vb = v[(size_t)b]; + v[(size_t)a] = va * std::cos(t) + vb * std::sin(t); + v[(size_t)b] = vb * std::cos(t) - va * std::sin(t); + } + for (int j = 0; j < 128; ++j) worst_d = std::max(worst_d, std::fabs(y[(size_t)j] - v[(size_t)j])); + } + CHECK(worst_d < 5e-3); + } + + // decode, rotate forward again with the checkpoint's own convention, compare to the codes + const void* data[7]; + for (int k = 0; k < 7; ++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); +} + +/* 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); +} + +/* 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); +} + +/* THE COMPOSITION IS PINNED BY ITS BYTES. The same pairs and angles the kernel library composed at load + * before "t.dense" was a table give the same hash here, so a container that stores the table serves the + * matrices the load-time composition did; and each matrix is orthogonal to f16 accuracy. */ +TEST(paro_dense_matrices_are_the_exact_composition) { + const int64_t K = 256, P = 2, S = 3, PS = P * S, G = 128; + 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; + } + std::vector t((size_t)(P * (K / G) * G * G)); + for (int64_t pt = 0; pt < P; ++pt) + for (int64_t g = 0; g < K / G; ++g) { + std::vector ia((size_t)(S * 64)), ib((size_t)(S * 64)); + std::vector th((size_t)(S * 64)); + for (int64_t st = 0; st < S; ++st) + for (int64_t j = 0; j < 64; ++j) { + const int64_t row = pt * S + st, o = st * 64 + j; + ia[(size_t)o] = pairs[(size_t)(row * K + g * G + 2 * j)] - (int32_t)(g * G); + ib[(size_t)o] = pairs[(size_t)(row * K + g * G + 2 * j + 1)] - (int32_t)(g * G); + th[(size_t)o] = ang[(size_t)(row * (K / 2) + g * 64 + j)]; + } + paro_compose_dense(S, ia.data(), ib.data(), th.data(), t.data() + (pt * (K / G) + g) * G * G); + } + uint64_t h = 0xcbf29ce484222325ull; + for (uint8_t b : std::vector((const uint8_t*)t.data(), (const uint8_t*)t.data() + t.size() * 2)) + h = (h ^ b) * 1099511628211ull; + CHECK_EQ(h, (uint64_t)0x8e72bd2bb541c6e6ull); + 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(t[(size_t)((pg * G + j) * G + i)]); + nrm += v * v; + } + worst = std::max(worst, std::fabs(nrm - 1.0)); + } + CHECK(worst < 2e-3); +} 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); diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 9fabb089..c87bedf1 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -262,7 +262,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_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". */ "rmsnorm_quant_fp8", "gated_quant_fp8", "gemm_nt_q_gated", "dflash_select", @@ -1644,6 +1645,182 @@ 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, 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; }; + 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); + 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 + 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) 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); + T rs(RAD_F32, {P, n}); + rs.f(sv); + + // 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) { + 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 < (i8 ? 0.006 : 0.04)); // half a step of the grid (int8: 1/254 of the maximum), and T's f16 + } + + // 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(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)); + 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 diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index f1f45f96..d7f74660 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; @@ -760,3 +789,77 @@ 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); + } +} + +/* ParoQuant's dense rotation matrices are the "t.dense" table rad-convert composed (checkpoint_test pins the + * composition by hash): the layout takes the table as stored, byte for byte, and refuses a view of anything + * else -- the pairs and angles, which it would have to compose, included. */ +TEST(givens_dense_layout_is_the_stored_table) { + const int64_t K = 256, P = 2, G = 128; + RadEncoding e = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + rad_enc_add_table(&e, "t.pairs", RAD_I32, P * 3, K); + rad_enc_add_table(&e, "t.angle", RAD_F32, P * 3, K / 2); + rad_enc_add_table(&e, "t.dense", RAD_F16, P * K / G, G * G); + std::vector dense((size_t)(P * K / G * G * G)); + for (size_t i = 0; i < dense.size(); ++i) dense[i] = (uint16_t)(i * 2654435761u >> 7); + RadTensor t{}; + t.data = dense.data(); t.dtype = RAD_F16; t.rank = 2; + t.shape[0] = P * K / G; t.shape[1] = G * G; t.stride[0] = G * G; t.stride[1] = 1; + Opts kp; + kp.i("n", K).i("parts", P); + const int sel[1] = { rad_enc_find(&e, "t.dense") }; + RadLayout L{}; + REQUIRE_EQ(r4d_rad_layout_gdense(kp.data(), kp.n(), 1, &e, sel, &t, 1, &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, 1, dst.data(), L.bytes), RAD_OK); + CHECK_EQ(std::memcmp(dst.data(), dense.data(), dst.size()), 0); + const int sel2[2] = { rad_enc_find(&e, "t.pairs"), rad_enc_find(&e, "t.angle") }; + RadTensor two[2] = { t, t }; + CHECK(r4d_rad_layout_gdense(kp.data(), kp.n(), 1, &e, sel2, two, 2, &L) != RAD_OK); +}