diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 5670b431..51bce18e 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -712,7 +712,7 @@ struct LinearFP8 { rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0; rad_buf rot_q = 0, rot_s = 0; rad_op op_rot = 0; - int64_t rot_parts = 1; + int64_t rot_parts = 1, rot_stages = 0; /* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear * before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */ bool probed_i8 = false; @@ -761,14 +761,16 @@ struct LinearFP8 { std::initializer_list row_parts = {}, int64_t span_lo = 0, int64_t span_hi = 0, std::initializer_list rot_part_rows = {}); - /* THE ROTATION OF A ROTATED WEIGHT, declared: its tables as views of the weight's own planes, its - * code planes (`givens_quant_act_fp8`: E4M3 and a scale) or, with `f16`, its single f16 plane - * (`givens_rotate`, for a GEMM that reads a 16-bit activation), and the op in front of the - * GEMM. `cut` is the rows of each rotated part; the GEMM's part bounds come back in pb1 and pb2. */ - int declare_rotation(RadBuilder* b, Names& nm, const Geom& g, const char* base, const char* wn, + /* THE ROTATION TABLES OF A ROTATED WEIGHT, declared as views of the weight's own planes, with + * `rot_parts` and `rot_stages`. `cut` is the rows of each rotated part; the GEMM's part bounds + * come back in pb1 and pb2. */ + int declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp, - const ActFP8& a, int64_t max_rows, const std::vector& cut, - bool f16, int64_t* pb1, int64_t* pb2); + const std::vector& cut, int64_t* pb1, int64_t* pb2); + /* The op in front of the GEMM, over those tables: `op` is givens_rotate (f16 out) or a + * rotate-and-quantise (codes and a scale), for M in [lo, hi]. */ + rad_op decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* op, int64_t lo, + int64_t hi, std::initializer_list outs) const; /* gemm_nt_q over this weight, M in [lo, hi]. `pb1`/`pb2` go only to a weight with rotated * parts, so a one-part op keeps the plain op's geometry -- the key the tune cache is read by. */ rad_op decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group, const char* dtype, @@ -837,30 +839,33 @@ inline bool linear_is_mxfp4(const RadEncoding& e) { sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP; } -/* The ROTATED OCP-MXFP4 weight (ParoQuant): the same codes and E8M0 exponents, stored in the basis - * a "givens" transform names, with the rotation's tables as planes of their own (int32 column - * pairs, f32 angles, f32 channel scales, and for a fused projection one set a part). The GEMM - * reads it as the plain MXFP4 weight; the activation in front of it is rotated first. */ -inline bool linear_is_paro_mxfp4(const RadEncoding& e) { +/* A ROTATED weight (ParoQuant): an affine encoding stored in the basis a "givens" transform names, + * with the rotation's tables as planes of their own -- int32 column pairs, f32 angles, f32 channel + * scales, and for a fused projection one set a part. The GEMM reads the codes as stored; the + * activation in front of it is rotated first. */ +inline bool linear_is_givens(const RadEncoding& e) { if (!rad_enc_is(&e, "affine") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false; - if (!rad_enc_valid(&e) || e.n_planes < 5) return false; - const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + if (!rad_enc_valid(&e)) return false; const RadEncPlane *pr = rad_enc_plane(&e, "t.pairs"), *an = rad_enc_plane(&e, "t.angle"), *rs = rad_enc_plane(&e, "t.scale"); - return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc && - sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP && - pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32; + return pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32; } -/* ParoQuant's int5 (u5 codes) and z-lab's own int4 (u4 codes): u5 codes, an f16 scale and a u8 zero point a 128 of K (asymmetric), in the rotated - * basis, with the same rotation tables. Read by gemm_nt_q at dtype w5a16 over an f16 activation. */ +/* ...whose codes and E8M0 exponents are OCP-MXFP4's: read as the plain MXFP4 weight. */ +inline bool linear_is_paro_mxfp4(const RadEncoding& e) { + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return linear_is_givens(e) && e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc && + sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP; +} + +/* ...whose codes are ParoQuant's int5 (u5) or z-lab's int4 (u4), asymmetric: an f16 scale and a u8 + * zero point a 128 of K. Read by gemm_nt_q at w5a16 / w4a16_asym over an f16 activation, and at + * w5a8i8 / w4a8i8_asym over an int8 one. */ inline bool linear_is_paro_w5(const RadEncoding& e) { - if (!rad_enc_is(&e, "affine") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false; - if (!rad_enc_valid(&e) || e.n_planes < 6) return false; const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero"); - return (e.plane[0].dtype == RAD_U5 || e.plane[0].dtype == RAD_U4) && sc && zp && sc->dtype == RAD_F16 && sc->block[0] == 1 && - sc->block[1] == RAD_FP8_BLOCK && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK && - rad_enc_find(&e, "t.pairs") > 0; + return linear_is_givens(e) && (e.plane[0].dtype == RAD_U5 || e.plane[0].dtype == RAD_U4) && sc && + zp && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK && + zp->dtype == RAD_U8 && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK; } inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base, @@ -891,11 +896,10 @@ inline rad_op LinearFP8::decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int6 return rw(b, rad_decl_op(b, "gemm_nt_q", ps, n_ps, wts.begin(), (int)wts.size()), reads, { y }); } -inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const Geom& g, const char* base, - const char* wn, const RadEncoding& enc, int64_t N, int64_t K, - RadWeightGroup grp, const ActFP8& a, int64_t max_rows, - const std::vector& cut_in, bool f16, int64_t* pb1, - int64_t* pb2) { +inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn, + const RadEncoding& enc, int64_t N, int64_t K, + RadWeightGroup grp, const std::vector& cut_in, + int64_t* pb1, int64_t* pb2) { /* THE PARTS, in rows, and the tables as weights of their own. The container records how many * parts there are and not where they end -- a declaration has no plane bytes -- so the block * says: `rot_part_rows`, or its row parts when those are the cut. */ @@ -923,6 +927,7 @@ inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const Geom& g, return RAD_E_SHAPE; } rot_parts = P; + rot_stages = S; *pb1 = P > 1 ? cut[0] : 0; *pb2 = P > 2 ? cut[0] + cut[1] : 0; rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, @@ -931,29 +936,17 @@ inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const Geom& g, { P * S, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); rot_scale = decl_view(b, nm.f("%s.rot_scale", base), wn, "t.scale", RAD_F32, { P, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - if (!rot_pairs || !rot_angle || !rot_scale) return RAD_E_INVAL; - const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; - if (f16) { - rot_q = decl_b(b, nm.f("%s.rot_y", base), RAD_F16, { rows, P * K }); - if (!rot_q) return RAD_E_INVAL; - op_rot = rw(b, RAD_OP(b, "givens_rotate", - RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), - RAD_INT("stages", S), RAD_INT("parts", P)), - RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), - { a.x }, { rot_q }); - return op_rot ? RAD_OK : RAD_E_INVAL; - } - rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, P * K }); - rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, P * (K / RAD_FP8_BLOCK) }); - if (!rot_q || !rot_s) return RAD_E_INVAL; - op_rot = rw(b, RAD_OP(b, "givens_quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), - RAD_INT("stages", S), RAD_INT("parts", P)), - RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), - { a.x }, { rot_q, rot_s }); - return op_rot ? RAD_OK : RAD_E_INVAL; + return rot_pairs && rot_angle && rot_scale ? RAD_OK : RAD_E_INVAL; +} + +inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* op, + int64_t lo, int64_t hi, std::initializer_list outs) const { + return rw(b, RAD_OP(b, op, + RAD_PARAMS(RAD_RANGE("M", lo, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_INT("stages", rot_stages), + RAD_INT("parts", rot_parts)), + RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), + { a.x }, outs); } inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, @@ -1102,32 +1095,29 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha const bool bits5 = enc.plane[0].dtype == RAD_U5; const int64_t kSplit = 64; /* the skinny kernel's M ceiling */ const bool band = hi > kSplit; - RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, - band ? kSplit : max_rows, cut, true, &pb1, &pb2)); + const int64_t f16_hi = band ? kSplit : hi; /* the f16 chain's rows */ + RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2)); + const int64_t P = rot_parts; + rot_q = decl_b(b, nm.f("%s.rot_y", base), RAD_F16, { f16_hi, P * K }); + if (!rot_q) return RAD_E_INVAL; + op_rot = decl_rot_op(b, g, a, "givens_rotate", 1, f16_hi, { rot_q }); + if (!op_rot) return RAD_E_INVAL; w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); if (!w || !ws) return RAD_E_INVAL; - op = decl_gemm_q(b, 1, band ? kSplit : hi, RAD_FP8_BLOCK, bits5 ? "w5a16" : "w4a16_asym", + op = decl_gemm_q(b, 1, f16_hi, RAD_FP8_BLOCK, bits5 ? "w5a16" : "w4a16_asym", pb1, pb2, { w, ws }, { rot_q }, y); if (!op) return RAD_E_INVAL; if (band) { /* THE PREFILL BAND: rows above the skinny kernel's ceiling rotate to int8 and meet the int8 * tiled GEMM. Declared over the tables and weight views already made above. */ - const int64_t P = rot_parts; rot_split = kSplit; rot_q2 = decl_b(b, nm.f("%s.rot_q2", base), RAD_I8, { hi, P * K }); rot_s2 = decl_b(b, nm.f("%s.rot_s2", base), RAD_F32, { hi, P * (K / RAD_FP8_BLOCK) }); if (!rot_q2 || !rot_s2) return RAD_E_INVAL; - const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs"); - const int64_t S = tp->extent[0] / P; - op_rot2 = rw(b, RAD_OP(b, "givens_quant_act_i8g", - RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("n", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), - RAD_INT("stages", S), RAD_INT("parts", P)), - RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), - { a.x }, { rot_q2, rot_s2 }); + op_rot2 = decl_rot_op(b, g, a, "givens_quant_act_i8g", kSplit + 1, hi, { rot_q2, rot_s2 }); op2 = decl_gemm_q(b, kSplit + 1, hi, RAD_FP8_BLOCK, bits5 ? "w5a8i8" : "w4a8i8_asym", pb1, pb2, { w, ws }, { rot_q2, rot_s2 }, y); if (!op_rot2 || !op2) return RAD_E_INVAL; @@ -1192,8 +1182,13 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha std::vector cut; for (int64_t p : rot_part_rows) cut.push_back(p); if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p); - RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, max_rows, cut, - false, &pb1, &pb2)); + RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2)); + const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; + rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, rot_parts * K }); + rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, rot_parts * (K / RAD_FP8_BLOCK) }); + if (!rot_q || !rot_s) return RAD_E_INVAL; + op_rot = decl_rot_op(b, g, a, "givens_quant_act_fp8", 1, rows, { rot_q, rot_s }); + if (!op_rot) return RAD_E_INVAL; } const char* sn = nm.f("%s.scale", base); const char* rn = nm.f("%s.ref", base); diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 3f414b92..3c10addb 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -552,8 +552,8 @@ void Checkpoint::detect_import() { else if (qc("format").empty() && qc("bits") == "4" && qc("group_size") == "128") import_ = Import::ParoI4; /* z-lab's own release: AWQ-packed int4, asymmetric */ else - import_why_ = "ParoQuant here is not the int5-bitplane format with 5-bit codes in groups " - "of 128, which is the one this reads"; + import_why_ = "ParoQuant here is neither the int5-bitplane format (5-bit codes) nor z-lab's " + "AWQ-packed int4, in groups of 128, which are the ones this reads"; } else if (qm == "paroquant_mxfp4") { /* QUARK'S MXFP4 PLANES IN A ROTATED BASIS: e2m1 codes, an e8m0 exponent a 32 of K, and per * projection the learned Givens rotations (`pairs`, `theta`) and channel scales in groups diff --git a/docs/OPS.md b/docs/OPS.md index 4c7ce457..42f56a32 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -39,10 +39,13 @@ made knowingly. - `dtype` is always present and always a string. It names the **operand combination**, which is why a weight format and an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`, `fp8_e4m3`, `fp8a8`, `fp8a16`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`, `w8a16`, - `w2a8`, `mxfp4a8`. `w4a8h` is `w4a8` with a `group`-wide Walsh–Hadamard along K baked into the - stored weight (`docs/MOE-W4.md`), `w4a8_asym` the unsigned-nibble-minus-zero-point grid rather - than the symmetric one, and `fp8a8`/`fp8a16` say whether a block-scaled E4M3 weight is met by - an fp8 activation or a bf16 one. `q_dtype` and `kv_dtype` are the same key split in two where + `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`. `w4a8h` is `w4a8` with a + `group`-wide Walsh–Hadamard along K baked into the stored weight (`docs/MOE-W4.md`), `w4a8_asym` + the unsigned-nibble-minus-zero-point grid rather than the symmetric one, and `fp8a8`/`fp8a16` say + whether a block-scaled E4M3 weight is met by an fp8 activation or a bf16 one. `w5a16` and + `w4a16_asym` are ParoQuant's int5 and z-lab's int4 (u5 / u4 codes, an f16 scale and a u8 zero + point a 128 of K) against an f16 activation, and `w5a8i8` / `w4a8i8_asym` the same weights + against an int8 one with an f32 scale per (row, 128 of K). `q_dtype` and `kv_dtype` are the same key split in two where attention reads two formats at once. - `M` is the ranged parameter wherever a token count appears. **At most one ranged parameter per op** — that is what keeps `rad_issue` a single integer on the hot path. @@ -387,9 +390,10 @@ copies of the activation, written side by side -- `q` is `[M, parts * n]`, `scal `[M, parts * n / group]` -- and `pairs` and `angle` stack the parts' `stages` rows each, `rscale` one row a part. `gemm_nt_q` then takes `pb1` and `pb2`, the row bounds of the weight's parts: its rows `[0, pb1)`, `[pb1, pb2)` and `[pb2, N)` meet copy 0, 1 and 2, and `a`/`a_scale` are the wide -planes. `givens_rotate` is the same rotation with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` (ParoQuant int5: u5 codes, an f16 scale and a u8 zero point a 128 of K) and `w4a16_asym` (z-lab's int4, the same at 4 bits); their GEMM serves any `M` (rows past 64 run as chunks of 64). `pb1` absent is one part; `pb2` absent ends the second part at `N`. Only the `mxfp4a8` rows -read them, and the host rows that do not (`libavx`) refuse a call that names one rather than -contract against the wrong copy. +planes. `givens_rotate` is the same rotation with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`; their GEMM serves any `M` (rows past 64 run as chunks of 64). `givens_quant_act_i8g` is the rotation with `quant_act_i8g`'s quantiser (scale `amax / 127` per `group`), for `w5a8i8` / `w4a8i8_asym`. `pb1` absent is one part; `pb2` absent ends the second part at `N`. The `mxfp4a8` rows and the +asymmetric 4- and 5-bit rows (`w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`) read them, and the +host rows that do not (`libavx`) refuse a call that names one rather than contract against the +wrong copy. ### The int8 and gated fp8 fusions — device-only diff --git a/libr4d/r4d_gemm_w5a16_nt_m64.hip b/libr4d/r4d_gemm_w5a16_nt_m64.hip index 548d9b56..3a037dab 100644 --- a/libr4d/r4d_gemm_w5a16_nt_m64.hip +++ b/libr4d/r4d_gemm_w5a16_nt_m64.hip @@ -76,54 +76,18 @@ __device__ __forceinline__ v8h fragA(r4d_gu2 p, int u) { return x.f; } -// One dword of eight nibbles -> one 16x16x16 f16 B fragment, minus the zero point. -// t0/t1 split the even and odd nibbles into bytes; each v_perm_b32 pairs two of those bytes with -// the constant high byte 0x64, which is the f16 exponent field for 1024. nz carries -// -(1024 + zero) in BOTH halves so one v_pk_add_f16 corrects a pair. -// The unpack is under a percent of this kernel at M=8, where it is at the DRAM roofline and the -// arithmetic hides in the load latency. It is a real fraction at M=64, but that band belongs to -// r4d_gemm_w4a8_nt_m64 -- and with no dequant at all the f16 form still trails the int8 one there, -// because the gap is the matrix instruction and not the dequant. Nothing here is worth a knob. -#ifndef R4D_GEMM_W4_TWOS -#define R4D_GEMM_W4_TWOS 1 -#endif - // DO NOT FOLD THE GROUP SCALE INTO THE B FRAGMENT. One v_pk_mul_f16 per pair on the finished // integer q is exact in f16, removes the second accumulator array entirely and takes the M=64 shape // from 192 VGPRs to 135 -- and it is SLOWER on most of the drafter's shapes. The multiply lands // inside the per-fragment dependent chain between the unpack and the WMMA, where the per-group // epilogue it replaces sits outside it; this kernel is stall-bound, not register-bound. -__device__ __forceinline__ v8h dequant(unsigned w, __half2 nz) { - const unsigned K64 = 0x64646464u; -#if R4D_GEMM_W4_TWOS - // The stored nibble is a 4-bit TWO'S COMPLEMENT code, because that is what - // r4d_gemm_w4a8_nt_m64 needs -- it shifts the nibble into the byte's high half and reads the - // byte signed. This kernel wants OFFSET BINARY, so that 1024 + n minus the constant 1024 + 8 - // is the value. The two differ by bit 3 of the nibble, so one XOR per spread dword converts, - // and the zero point is then pinned to 8 for every group. Two instructions per fragment, on - // the kernel whose whole unpack is a fraction of a percent of its time at M=8 -- which is why - // the conversion lives here and not in the int8 kernel, where the unpack is three instructions - // and does matter. One quantised weight, two kernels, dispatched on M. - const unsigned t0 = (w & 0x0F0F0F0Fu) ^ 0x08080808u; - const unsigned t1 = ((w >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; -#else - const unsigned t0 = w & 0x0F0F0F0Fu; - const unsigned t1 = (w >> 4) & 0x0F0F0F0Fu; -#endif - union { unsigned u[4]; __half2 h2[4]; v8h f; } x; - x.u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // nibbles 0, 2 - x.u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // nibbles 4, 6 - x.u[2] = __builtin_amdgcn_perm(K64, t1, 0x05010400u); // nibbles 1, 3 - x.u[3] = __builtin_amdgcn_perm(K64, t1, 0x05030402u); // nibbles 5, 7 -#pragma unroll - for (int i = 0; i < 4; i++) x.h2[i] = __hadd2(x.h2[i], nz); - return x.f; -} - // One dword of eight nibbles plus the byte of their fifth bits -> one 16x16x16 f16 B fragment, // minus the zero point. Nibble 2e (e < 4) / 2(e-4)+1 is fragment element e, so bits 0..3 of `hb` -// are the fifth bits of the even nibbles' elements and bits 4..7 the odd nibbles'. +// are the fifth bits of the even nibbles' elements and bits 4..7 the odd nibbles'. Each v_perm_b32 +// pairs two code bytes with the constant high byte 0x64, the f16 exponent field for 1024, so a half +// is 1024 + code; nz carries -(1024 + zero) in BOTH halves, so one v_pk_add_f16 corrects a pair. +// The codes are offset binary (0..31, or 0..15 without the fifth bit): no sign flip. __device__ __forceinline__ unsigned spread16(unsigned n) { // 4 bits -> bit 4 of each byte return ((n * 0x00204081u) & 0x01010101u) << 4; } @@ -288,18 +252,18 @@ void r4d_gemm_w5a16_nt_m64(long a, long wq, long whi, long wsz, long c, int M, i if (!lda) lda = K; if (!ldc) ldc = N; if (M < 1 || M > R4D_GEMM_W4_MAX_M) - throw std::runtime_error("r4d gemm_w4a16_nt_m64: M must be 1..64"); - if (N % 16) throw std::runtime_error("r4d gemm_w4a16_nt_m64: N must be a multiple of 16"); + throw std::runtime_error("r4d gemm_w5a16_nt_m64: M must be 1..64"); + if (N % 16) throw std::runtime_error("r4d gemm_w5a16_nt_m64: N must be a multiple of 16"); if (K % (SK * R4D_GEMM_W4_GROUP)) - throw std::runtime_error("r4d gemm_w4a16_nt_m64: K must be divisible by SK*128"); - if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w4a16_nt_m64: threads/block > 1024"); - if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w4a16_nt_m64: MB must be 1..4"); - if (NPW != 1 && NPW != 4) throw std::runtime_error("r4d gemm_w4a16_nt_m64: NPW must be 1 or 4"); + throw std::runtime_error("r4d gemm_w5a16_nt_m64: K must be divisible by SK*128"); + if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w5a16_nt_m64: threads/block > 1024"); + if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w5a16_nt_m64: MB must be 1..4"); + if (NPW != 1 && NPW != 4) throw std::runtime_error("r4d gemm_w5a16_nt_m64: NPW must be 1 or 4"); const int ntiles = N / 16, mtiles = (M + 15) / 16; const int ncols = WV * NPW; dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32); size_t smem = (size_t)ncols * SK * 256 * sizeof(float); - if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w4a16_nt_m64: WV*NPW*SK too large"); + if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w5a16_nt_m64: WV*NPW*SK too large"); auto Ap = (const unsigned short*)a; auto Wp = (const unsigned*)wq; auto Hp = (const unsigned*)whi; @@ -316,7 +280,7 @@ void r4d_gemm_w5a16_nt_m64(long a, long wq, long whi, long wsz, long c, int M, i case 2: LAUNCH(2, NP, TT); break; \ case 3: LAUNCH(3, NP, TT); break; \ case 4: LAUNCH(4, NP, TT); break; \ - default: throw std::runtime_error("r4d gemm_w4a16_nt_m64: MB unsupported"); } + default: throw std::runtime_error("r4d gemm_w5a16_nt_m64: MB unsupported"); } if (NPW == 1) { if (NT) { LAUNCH_MB(1, true); } else { LAUNCH_MB(1, false); } } else { diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index ea31548c..17ba87e0 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -327,6 +327,18 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) { } } +/* Every zero point a code of `bits` bits: what an asymmetric grid's zero is, and what the int8 + * prefill kernel reads back out of the scale dword (r4d_gemm_wpa8i8_tiled.hip takes five bits of it, + * where the f16 kernel takes the whole value -- a larger zero would make the two disagree). */ +bool sz_zeros_fit(const WGeom& g, const RadTensor& zp, int bits) { + const long long nz = g.N * (g.K / g.group); + for (long long i = 0; i < nz; ++i) { + const int z = zero_at(zp, i); + if (z < 0 || z >= (1 << bits)) return false; + } + return true; +} + void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym) { const long long nt = g.N / R4D_NTILE, nsz = g.K / g.group; for (long long t = 0; t < nt; ++t) @@ -416,6 +428,9 @@ extern "C" int r4d_rad_relayout_w4(const RadParam* p, int n_p, int operand, cons if (dst_bytes != L.bytes) return RAD_E_SHAPE; std::memset(dst, 0, (size_t)dst_bytes); if (operand == Q_BSCALE) { + /* a ROTATED (ParoQuant) grid's zero is a 4-bit code */ + if (w4_asym(p, n_p) && std::strncmp(enc->transform, "givens", RAD_ENC_STR) == 0 && + !sz_zeros_fit(g, pl[1], 4)) return RAD_E_FORMAT; sz_write(g, pl, w4_asym(p, n_p) ? -1 : 8, (uint32_t*)dst); return RAD_OK; } @@ -501,6 +516,7 @@ extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, cons if (dst_bytes != L.bytes) return RAD_E_SHAPE; std::memset(dst, 0, (size_t)dst_bytes); if (operand == Q_BSCALE) { + if (!sz_zeros_fit(g, pl[1], 5)) return RAD_E_FORMAT; sz_write(g, pl, -1, (uint32_t*)dst); return RAD_OK; } @@ -526,6 +542,35 @@ extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, cons return RAD_OK; } +extern "C" int r4d_rad_unrelayout_w5(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + WGeom g; + const int rc = w5_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes) return RAD_E_SHAPE; + if (operand == Q_BSCALE) { + sz_read(g, (const uint32_t*)src, pl, true); + return RAD_OK; + } + const uint32_t* wq = (const uint32_t*)src; + const uint32_t* hi = wq + g.N * g.K / 8; + const long long rb = (g.K * 5 + 7) / 8; + uint8_t* d = (uint8_t*)pl[0].data; + std::memset(d, 0, (size_t)(g.N * rb)); + for (long long nn = 0; nn < g.N; ++nn) + for (long long k = 0; k < g.K; ++k) { + long long w; + int nib; + w4_slot(g, nn, k, &w, &nib); + const int e = nib % 2 == 0 ? nib / 2 : 4 + nib / 2; /* as r4d_rad_relayout_w5 */ + const uint32_t q = ((wq[w] >> (4 * nib)) & 15u) | (((hi[w / 4] >> (8 * (w % 4) + e)) & 1u) << 4); + rad_store_bits(d + nn * rb, 5, k, q); + } + return RAD_OK; +} + /* ---- w8: i8 codes, symmetric about zero, an f16 scale a group. The f16 kernel (a16) reads the * code offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed with a * bare f16 scale plane. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 25f30698..3609719f 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -399,6 +399,8 @@ int r4d_rad_layout_w5(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_w5(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, void*, int64_t); +int r4d_rad_unrelayout_w5(const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 96d82e1f..5b841e59 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4711,7 +4711,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, ROW(cGemmNtW5), ROW(tGemmSkinny), r4d_tune_valid_gemm, nullptr, nullptr, r4d_rad_gemm_w5a16_m64, nullptr, r4d_rad_layout_w5, r4d_rad_relayout_w5, - nullptr, nullptr }, + nullptr, r4d_rad_unrelayout_w5 }, { "gemm_w4a16_asym_nt_m64", "gemm_nt_q", "gemm", "skinny GEMM with a 4-bit ASYMMETRIC weight (z-lab's ParoQuant int4), the 5-bit row's kernel with " @@ -4722,7 +4722,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, ROW(cGemmNtW4Asym), ROW(tGemmSkinny), r4d_tune_valid_gemm, nullptr, nullptr, r4d_rad_gemm_w4a16asym_m64, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4, - nullptr, nullptr }, + nullptr, r4d_rad_unrelayout_w4 }, { "gemm_w4a8i8_tiled", "gemm_nt_q", "gemm", "the 4-bit ASYMMETRIC weight x int8 activation GEMM for prefill row counts (z-lab's ParoQuant int4): " @@ -4734,7 +4734,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, ROW(cGemmNtW4A8I8), NOTUNE, nullptr, nullptr, r4d_rad_gemm_w4a8i8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, - r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, nullptr }, + r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, r4d_rad_unrelayout_w4 }, { "gemm_w5a8i8_tiled", "gemm_nt_q", "gemm", "the 5-bit ASYMMETRIC weight x int8 activation GEMM for prefill row counts (ParoQuant int5): int8 " @@ -4746,7 +4746,7 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, ROW(cGemmNtW5A8I8), NOTUNE, nullptr, nullptr, r4d_rad_gemm_w5a8i8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, - r4d_rad_layout_w5, r4d_rad_relayout_w5, nullptr, nullptr }, + r4d_rad_layout_w5, r4d_rad_relayout_w5, nullptr, r4d_rad_unrelayout_w5 }, { "gemm_w8a16_nt_m64", "gemm_nt_q", "gemm", "skinny GEMM with an 8-bit weight, 16x16x16 WMMA, split-K reduced in LDS", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 2d18e012..c2f1f4f2 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -865,6 +865,42 @@ struct Planes { } }; +/* gemm_nt_q's `pb1`/`pb2` over N rows (ParoQuant): rows [0, e1), [e1, e2), [e2, N) meet copies 0, 1, + * 2 of the activation, side by side in a row; `parts` is how many copies there are. 0 leaves a + * bound out, as the kernels read it. */ +struct PartCut { + int64_t e1, e2; + int parts; + PartCut(int64_t N, int64_t pb1, int64_t pb2) + : e1(pb1 > 0 ? std::min(pb1, N) : N), + e2(pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N), + parts(e2 < N ? 3 : (e1 < N ? 2 : 1)) {} + int part_of(int64_t n) const { return (int)(n >= e1) + (int)(n >= e2); } +}; + +/* An ASYMMETRIC grid's planes for a [N, K] weight: `bits`-bit codes (a bit stream along K), an f16 + * scale and a u8 zero point 0 .. 2^bits - 1 a 128 of K, drawn through st_mix32 of their coordinates. */ +static Planes asym_planes(int bits, int64_t N, int64_t K) { + Planes p; + p.enc = rad_enc_affine(bits == 4 ? RAD_U4 : RAD_U5, RAD_F16, 1, 128); + rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); + p.size(N, K); + const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); + const int64_t rb = p.row_bytes(ic), G = K / 128; + const uint32_t top = (1u << bits) - 1; + for (int64_t n = 0; n < N; ++n) { + for (int64_t k = 0; k < K; ++k) + rad_store_code(p.data[(size_t)ic].data() + n * rb, p.enc.plane[ic].dtype, k, + (int)(st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & top)); + for (int64_t g = 0; g < G; ++g) { + const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); + rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, 0.002f * (float)(1 + h % 40)); + p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)((h >> 8) & top); + } + } + return p; +} + /* The unnormalised Sylvester Walsh-Hadamard transform of `n` values, in place: (a + b) to the lower * index and (a - b) to the upper, the transform an "fwhtN" encoding names. H_n H_n = n I. */ static void h_fwht(float* v, int64_t n) { @@ -3609,10 +3645,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ if (!sel(row)) return; /* PARTS (ParoQuant): the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy * of the activation, the copies side by side in a row. `K` is one copy's width. */ - const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; - const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; - const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); - auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + const PartCut cut(N, pb1, pb2); + const int parts = cut.parts; char nm[160]; std::string ex; for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival); @@ -3713,7 +3747,7 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ for (int64_t i = 0; i < M; ++i) for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) { double acc = 0; - const int pt = part_of(n); + const int pt = cut.part_of(n); for (int64_t k = 0; k < K; ++k) { const double w = (double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) * (double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32); @@ -3857,38 +3891,17 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int int64_t pb2 = 0) { const char* row = "gemm_w5a16_nt_m64"; if (!sel(row)) return; - const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; - const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; - const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); - auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + const PartCut cut(N, pb1, pb2); + const int parts = cut.parts; char nm[160]; std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, (long long)N, (long long)K, parts); const RadKernelInfo* r = find(pl, row); if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } const int64_t G = K / 128; - Planes p; - p.enc = rad_enc_affine(RAD_U5, RAD_F16, 1, 128); - rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); - p.size(N, K); + const Planes p = asym_planes(5, N, K); const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); const int64_t rb = p.row_bytes(ic); - for (int64_t n = 0; n < N; ++n) { - for (int64_t k = 0; k < K; ++k) { - const uint32_t q = st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & 31u; - const int64_t bit = k * 5; - uint8_t* b = p.data[(size_t)ic].data() + n * rb + (bit >> 3); - const uint32_t v = q << (bit & 7); - b[0] |= (uint8_t)(v & 0xFF); - if ((bit & 7) > 3) b[1] |= (uint8_t)(v >> 8); - } - for (int64_t g = 0; g < G; ++g) { - const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); - const float sc = 0.002f * (float)(1 + h % 40); - rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, sc); - p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)(8 + (h >> 8) % 20); - } - } std::vector lp = { PI("N", N), PI("K", K), PI("group", 128) }; std::vector wq, ws; const int rw = stored(r, lp, 2, p, { "codes" }, &wq); @@ -3938,7 +3951,7 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int double num = 0, den = 0; for (int64_t i = 0; i < M; ++i) for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) { - const int pt = part_of(n); + const int pt = cut.part_of(n); double acc = 0; for (int64_t k = 0; k < K; ++k) { const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, RAD_U5, k); @@ -4048,37 +4061,17 @@ static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int int64_t pb2 = 0) { const char* row = bits == 4 ? "gemm_w4a8i8_tiled" : "gemm_w5a8i8_tiled"; if (!sel(row)) return; - const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; - const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; - const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); - auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + const PartCut cut(N, pb1, pb2); + const int parts = cut.parts; char nm[160]; std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, (long long)N, (long long)K, parts); const RadKernelInfo* r = find(pl, row); if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } const int64_t G = K / 128; - Planes p; - p.enc = rad_enc_affine(bits == 4 ? RAD_U4 : RAD_U5, RAD_F16, 1, 128); - rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); - p.size(N, K); + const Planes p = asym_planes(bits, N, K); const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); const int64_t rb = p.row_bytes(ic); - for (int64_t n = 0; n < N; ++n) { - for (int64_t k = 0; k < K; ++k) { - const uint32_t q = st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & ((1u << bits) - 1); - const int64_t bit = k * bits; - uint8_t* b = p.data[(size_t)ic].data() + n * rb + (bit >> 3); - const uint32_t v = q << (bit & 7); - b[0] |= (uint8_t)(v & 0xFF); - if ((bit & 7) > 3) b[1] |= (uint8_t)(v >> 8); - } - for (int64_t g = 0; g < G; ++g) { - const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); - rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, 0.002f * (float)(1 + h % 40)); - p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)((h >> 8) % (1u << bits)); - } - } std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", bits == 4 ? "w4a8i8_asym" : "w5a8i8") }; std::vector wq, ws; const int rw = stored(r, lp, 2, p, { "codes" }, &wq); @@ -4136,18 +4129,14 @@ static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int double num = 0, den = 0; for (int64_t i = 0; i < M; i += (M > 64 ? 3 : 1)) for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) { - const int pt = part_of(n); + const int pt = cut.part_of(n); double acc = 0; for (int64_t g = 0; g < G; ++g) { double grp = 0; const double z = p.data[(size_t)iz][(size_t)(n * G + g)]; const double sc = rad_load_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g); for (int64_t k = g * 128; k < (g + 1) * 128; ++k) { - const int64_t bit = k * bits; - const uint8_t* rowp = p.data[(size_t)ic].data() + n * rb; - uint32_t v = rowp[bit >> 3]; - if ((bit & 7) > 3) v |= (uint32_t)rowp[(bit >> 3) + 1] << 8; - const double q = (v >> (bit & 7)) & ((1u << bits) - 1); + const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, p.enc.plane[ic].dtype, k); grp += (double)av[(size_t)(i * PK + pt * K + k)] * (q - z); } acc += grp * sc * (double)as[(size_t)(i * PG + pt * G + g)]; diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index 1968e8aa..dbc669f4 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -932,3 +932,100 @@ TEST(a_paroquant_int5_weight_is_relaid_row_by_row) { CHECK_EQ(bad, 0); remove_checkpoint(dir); } + +/* Z-LAB'S INT4 (`paroquant`, bits 4, no `format`): the int5 test's AWQ nibbles with no fifth-bit + * planes, here as a fused gate|up -- two pieces, each with its own rotation, so the weight carries + * two parts. Codes and zero points come out row by row per piece, and t.part ends each piece. */ +TEST(a_paroquant_int4_fused_weight_is_two_rotated_parts) { + const int64_t N = 32, K = 128, G = K / 128; + uint32_t rng = 4242; + auto next = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; }; + static const int kOrder[8] = { 0, 2, 4, 6, 1, 3, 5, 7 }; + auto pack_awq = [&](const std::string& name, const std::vector& v, int64_t rows) { + T t{ name, "I32", { rows, N / 8 }, {} }; + t.bytes.assign((size_t)(rows * N / 8 * 4), 0); + for (int64_t r = 0; r < rows; ++r) + for (int64_t n = 0; n < N; ++n) { + int j = 0; + while (kOrder[j] != n % 8) ++j; + uint32_t w; + uint8_t* p = t.bytes.data() + (r * (N / 8) + n / 8) * 4; + std::memcpy(&w, p, 4); + w |= (uint32_t)(v[(size_t)(n * rows + r)] & 15) << (4 * j); + std::memcpy(p, &w, 4); + } + return t; + }; + auto f16s = [&](const std::string& name, std::vector shape, float v) { + T t{ name, "F16", shape, {} }; + int64_t cnt = 1; + for (int64_t d : shape) cnt *= d; + const uint16_t h = rad_f32_to_f16(v); + for (int64_t i = 0; i < cnt; ++i) { t.bytes.push_back((uint8_t)(h & 0xff)); t.bytes.push_back((uint8_t)(h >> 8)); } + return t; + }; + auto pairs = [&](const std::string& name, int shift) { + T t{ name, "I16", { 1, K }, {} }; + for (int64_t i = 0; i < K; ++i) { + const int16_t v = (int16_t)((i ^ shift) % 128); + t.bytes.push_back((uint8_t)(v & 0xff)); + t.bytes.push_back((uint8_t)(v >> 8)); + } + return t; + }; + std::vector ts; + std::vector code[2], zero[2]; + const char* names[2] = { "g", "u" }; + for (int p = 0; p < 2; ++p) { + code[p].resize((size_t)(N * K)); + zero[p].resize((size_t)(N * G)); + for (auto& c : code[p]) c = (int)(next() % 16); + for (auto& z : zero[p]) z = (int)(next() % 16); + const std::string b = names[p]; + ts.push_back(pack_awq(b + ".qweight", code[p], K)); + ts.push_back(pack_awq(b + ".qzeros", zero[p], G)); + ts.push_back(f16s(b + ".scales", { G, N }, 0.01f * (float)(p + 1))); + ts.push_back(pairs(b + ".pairs", p + 1)); // adjacent / next-but-one swaps + ts.push_back(f16s(b + ".theta", { 1, K / 2 }, 0.2f)); + ts.push_back(f16s(b + ".channel_scales", { 1, K }, 1.25f)); + } + const std::string dir = write_checkpoint(ts, + "{\"model_type\":\"qwen3_5\",\"quantization_config\":{\"quant_method\":\"paroquant\"," + "\"bits\":4,\"group_size\":128,\"krot\":1}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK(ck.imports() == Checkpoint::Import::ParoI4); + Program prog; + prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "g.weight", "u.weight" })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK); + REQUIRE(w.paro && w.imported); + CHECK_EQ(w.rows, 2 * N); + CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_U4); + CHECK_EQ(rad_enc_givens_parts(&w.enc), (int64_t)2); + std::vector> pl((size_t)w.enc.n_planes); + for (int k = 0; k < w.enc.n_planes; ++k) { + int64_t pr_ = 0, pc = 0; + rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr_, &pc); + pl[(size_t)k].assign((size_t)(pr_ * rad_enc_row_bytes(w.enc.plane[k].dtype, pc)) + 8, 0); + REQUIRE_EQ(ckpt_plane_rows(w, k, 0, pr_, pl[(size_t)k].data(), &why), RAD_OK); + } + const int64_t rb = rad_enc_row_bytes(RAD_U4, K); + int bad = 0; + for (int p = 0; p < 2; ++p) + for (int64_t n = 0; n < N; ++n) { + const int64_t r = p * N + n; + for (int64_t k = 0; k < K; ++k) + if ((int)rad_load_f32(pl[0].data() + r * rb, RAD_U4, k) != code[p][(size_t)(n * K + k)]) ++bad; + for (int64_t g = 0; g < G; ++g) + if (pl[2][(size_t)(r * G + g)] != zero[p][(size_t)(n * G + g)]) ++bad; + } + CHECK_EQ(bad, 0); + const int tpart = rad_enc_find(&w.enc, "t.part"); + REQUIRE(tpart > 0); + const int32_t* ends = (const int32_t*)pl[(size_t)tpart].data(); + CHECK_EQ(ends[0], (int32_t)N); + CHECK_EQ(ends[1], (int32_t)(2 * N)); + remove_checkpoint(dir); +} diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index d34b2801..11d93c50 100644 --- a/tests/relayout_parity_test.cpp +++ b/tests/relayout_parity_test.cpp @@ -166,6 +166,7 @@ const Hooks nHc { r4d_rad_layout_hc_e4m3, r4d_rad_relayout_hc_e4m3, const Hooks nMtp { r4d_rad_layout_mtp_e4m3, r4d_rad_relayout_mtp_e4m3, r4d_rad_unrelayout_mtp_e4m3 }; const Hooks nW4 { r4d_rad_layout_w4, r4d_rad_relayout_w4, r4d_rad_unrelayout_w4 }; +const Hooks nW5 { r4d_rad_layout_w5, r4d_rad_relayout_w5, r4d_rad_unrelayout_w5 }; const Hooks nW8a16 { r4d_rad_layout_w8a16, r4d_rad_relayout_w8a16, nullptr }; const Hooks nW8a8 { r4d_rad_layout_w8a8, r4d_rad_relayout_w8a8, nullptr }; const Hooks nW2 { r4d_rad_layout_w2a8, r4d_rad_relayout_w2a8, r4d_rad_unrelayout_w2a8 }; @@ -284,6 +285,34 @@ TEST(dense_int4_symmetric_and_asymmetric) { } } +/* ParoQuant's int5: u5 codes as w4's nibble plane plus a fifth-bit plane, the (scale, zero) dwords + * of the asymmetric w4 grid -- read back exactly; and a zero point that is not a 5-bit code refused, + * since the int8 prefill kernel reads five bits of it where the f16 one reads the whole value. */ +TEST(dense_int5_asymmetric) { + NEED_LIBQUANT(); + const int64_t N = 64, K = 256; + const std::vector w = weight(N, K, 19, 1, 128); + Opts kp, g; + kp.i("N", N).i("K", K).s("dtype", "w5a16"); + g.s("codes", "u5").s("zero", "u8").i("group", 128).s("scale", "f16"); + golden("w5", stored("w5", nW5, kp, "rtn", g, "blk.0.ffn_up.weight", N, K, w, + { { B, { "codes" } }, { BSCALE, { "scale", "zero" } } }), + 0xb0b1f9d187cbf267ull); + const Quantised q = quantise(quantizer("rtn"), g, "x", N, K, w); + REQUIRE_EQ(q.status, RAD_OK); + std::vector> bufs; + Selection s = select(q, N, K, { "scale", "zero" }, &bufs); + std::memcpy(bufs[0].data(), q.planes[(size_t)s.sel[0]].data(), bufs[0].size()); + std::memcpy(bufs[1].data(), q.planes[(size_t)s.sel[1]].data(), bufs[1].size()); + bufs[1][3] = 32; + RadLayout L{}; + REQUIRE_EQ(r4d_rad_layout_w5(kp.data(), kp.n(), BSCALE, &q.enc, s.sel.data(), s.t.data(), + (int)s.t.size(), &L), RAD_OK); + std::vector dst((size_t)L.bytes); + CHECK_EQ(r4d_rad_relayout_w5(kp.data(), kp.n(), BSCALE, &q.enc, s.sel.data(), s.t.data(), + (int)s.t.size(), dst.data(), L.bytes), RAD_E_FORMAT); +} + TEST(dense_int8_for_the_f16_and_the_int8_kernel) { NEED_LIBQUANT(); const int64_t N = 48, K = 256;