From d1b5a45e312a258e28d9b910760cc0a602dd058a Mon Sep 17 00:00:00 2001 From: Constantin Date: Mon, 16 Nov 2026 18:40:07 -0500 Subject: [PATCH] feat(qwen4exp): support U4 gate with W6NL down experts --- arch/common/rad_block_moe_fp8.h | 45 ++++---- arch/qwen4exp_fp8/qwen4exp_fp8.cpp | 2 +- data/recipes/qwen4exp-u4-w6nl-bf16ple.recipe | 45 ++++++++ docs/MOE-W6.md | 27 +++++ libquant/lq_grid.cpp | 14 ++- libquant/lq_grid.h | 2 +- libquant/lq_quant.h | 2 +- libr4d/r4d_args.h | 19 +++- libr4d/r4d_layout.cpp | 94 ++++++++++++++-- libr4d/r4d_moe.hip | 87 +++++++++++---- libr4d/r4d_rows.cpp | 2 +- libr4d/r4d_selftest.cpp | 61 +++++++--- libref/ref_moe.cpp | 9 +- libref/ref_registry.cpp | 2 +- libref/ref_shapes.cpp | 2 +- tests/arch_test.cpp | 23 +++- tests/quant_test.cpp | 38 +++++++ tests/ref_test.cpp | 56 +++++++++- tests/relayout_parity_test.cpp | 57 ++++++++++ tools/fit_w6nl.py | 110 +++++++++++++++++++ 20 files changed, 618 insertions(+), 79 deletions(-) create mode 100644 data/recipes/qwen4exp-u4-w6nl-bf16ple.recipe create mode 100644 docs/MOE-W6.md create mode 100644 tools/fit_w6nl.py diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index c36f58b8..4cdd9bd7 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -259,6 +259,7 @@ struct MoeFP8 { * layer's; the 64-group codebook forms may differ by layer and projection, and declare() * resolves each layer's (MoeFP8::fmt). */ int expert_w5 = 0; + int expert_w6 = 0; /* six-bit codebook, E4M3 scale per 64 */ /* Int8 experts (`i8*bf16[1x128]/fwht128`): codes -127..127 with a bf16 scale per (row, 128 * of K), each 128 of K rotated as `expert_rot` describes, read against int8 activations * (dtype `i8a8h`). The eight-bit expert of an int8 model, where block fp8 is that of an @@ -512,12 +513,12 @@ struct MoeFP8 { static int format_of(const RadEncoding& e); /* format_of's numbers as the grouped GEMMs' dtype strings against an E4M3 activation, and * against an int8 one (null: the format has no such row). Int8 experts read int8 only. */ - static constexpr const char* kServed[12] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h", + static constexpr const char* kServed[13] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h", "w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", - "fp8a8f32", nullptr, nullptr }; - static constexpr const char* kServed8[12] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr, + "fp8a8f32", nullptr, nullptr, "w6nl64a8h" }; + static constexpr const char* kServed8[13] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr, "w4nl64a8i8h", "w4nl32a8i8h", nullptr, nullptr, - nullptr, "i8a8h", "i8a8h" }; + nullptr, "i8a8h", "i8a8h", nullptr }; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const Src& src, bool fold = false, bool add_out = true, @@ -569,6 +570,8 @@ inline int MoeFP8::format_of(const RadEncoding& e) { return sc->block[1] == RAD_FP8_BLOCK / 2 ? 5 : 6; if (t->extent[1] == 32 && e.plane[0].dtype == RAD_U5 && sc->block[1] == RAD_FP8_BLOCK / 2) return 7; + if (t->extent[1] == 64 && e.plane[0].dtype == RAD_U6 && sc->block[1] == RAD_FP8_BLOCK / 2) + return 12; return RAD_E_DTYPE; } if (!sc) return RAD_E_DTYPE; @@ -685,13 +688,14 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config return linear_refuse_retired(guw, f == 8 ? "MXFP4" : "block fp8"); if (f != 3) break; } - cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0; - cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 10 || f == 11) ? 1 : 0; + cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0; + cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 10 || f == 11 || f == 12) ? 1 : 0; cfg->expert_i8 = f == 10 ? 1 : 0; cfg->expert_iqr = f == 11 ? 1 : 0; - cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0; - cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0; + cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0; + cfg->expert_g64 = (f == 5 || f == 7 || f == 12) ? 2 : f == 6 ? 4 : 0; cfg->expert_w5 = f == 7 ? 1 : 0; + cfg->expert_w6 = f == 12 ? 1 : 0; cfg->expert_bf16 = f == 3 ? 1 : 0; cfg->expert_mx = f == 8 ? 1 : 0; cfg->expert_f32_scale = f == 9 ? 1 : 0; @@ -777,7 +781,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, a8 = w.eff.q8_fed && !c.expert_bf16; prot.clear(); { - const int want = c.expert_iqr ? 11 : c.expert_i8 ? 10 : c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6 + const int want = c.expert_iqr ? 11 : c.expert_i8 ? 10 : c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w6 ? 12 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6 : c.expert_g64 ? 5 : c.expert_nl ? 4 : c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0; auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) { @@ -799,7 +803,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const bool a8f = a8; auto family = [a8f](int f) { return a8f ? (f == 2 || f == 5 || f == 6 || f == 10 || f == 11) - : (f == 5 || f == 6 || f == 7); + : (f == 5 || f == 6 || f == 7 || f == 12); }; fmt[0] = fmt[1] = want; fenc[0] = fenc[1] = RadEncoding{}; @@ -812,8 +816,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, for (int i = 0; i < 2; ++i) { /* A trellis gate_up reads rotated int8, but the down projection can use the * W5NL E4M3 kernel: its gated intermediate is quantised independently below. */ - const bool mixed_w5_down = a8f && want == 11 && i == 1 && fe[i] == 7; - if (family(want) && (family(fe[i]) || mixed_w5_down)) fmt[i] = fe[i]; + const bool mixed_codebook_down = a8f && want == 11 && i == 1 && + (fe[i] == 7 || fe[i] == 12); + if (family(want) && (family(fe[i]) || mixed_codebook_down)) fmt[i] = fe[i]; fenc[i] = enc[i]; } break; @@ -1041,6 +1046,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, switch (f) { /* An IQR weight: the codes at their stored width with the code's planes, and the row and * block scales as one view at the weight's extents (LinearFP8's views of the same form). */ + case 12: return { RAD_U6, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" }; case 11: return { fe.plane[0].dtype, "codes,trellis,trellis.mad", RAD_F32, 1, "scale,scale.col" }; case 10: return { RAD_I8, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" }; @@ -1077,15 +1083,16 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, return RAD_E_INVAL; } /* ---- The routed arm's activations (see `a8`). */ - if ((c.expert_i8 || c.expert_iqr || fmt[0] >= 10 || fmt[1] >= 10) && !a8) { + if ((c.expert_i8 || c.expert_iqr || fmt[0] == 10 || fmt[0] == 11 || + fmt[1] == 10 || fmt[1] == 11) && !a8) { fprintf(stderr, "radiance: layer %d's experts read int8 activations (int8, or an IQR weight); the " "architecture declared the routed arm's codes E4M3\n", l); return RAD_E_UNSUPPORTED; } - const bool down_w5_fp8 = a8 && fmt[0] == 11 && fmt[1] == 7; + const bool down_codebook_fp8 = a8 && fmt[0] == 11 && (fmt[1] == 7 || fmt[1] == 12); if (a8) { const bool pair = w.eff.q8 && w.eff.s8 && w.eff.q8_rot && w.eff.g8 == RAD_FP8_BLOCK; - const bool down_supported = down_w5_fp8 ? (w.eff.q && w.eff.s && kServed[fmt[1]]) + const bool down_supported = down_codebook_fp8 ? (w.eff.q && w.eff.s && kServed[fmt[1]]) : kServed8[fmt[1]] != nullptr; /* A clamped layer is served too: GateQuantFP8 clamps into the bf16 plane, then * quantises it into the rotated codes. Not before a W5NL down projection, which reads @@ -1116,7 +1123,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, * experts' encoding or the kernel is not a candidate. */ gu_trellis = fmt[0] == 11; const char* const edtype[2] = { a8 ? kServed8[fmt[0]] : kServed[fmt[0]], - a8 && !down_w5_fp8 ? kServed8[fmt[1]] : kServed[fmt[1]] }; + a8 && !down_codebook_fp8 ? kServed8[fmt[1]] : kServed[fmt[1]] }; /* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale * planes the same in their own units. */ auto span = [&](rad_weight h, int q, int64_t unit) -> int { @@ -1316,9 +1323,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* Gate_up and down are separate GEMMs. A trellis gate uses int8 input while W5NL down * reads rotated E4M3: select the latter pair only for the gated intermediate. */ ActFP8 down_eff = w.eff; - if (down_w5_fp8) down_eff.q8_fed = down_eff.q8_rot = false; + if (down_codebook_fp8) down_eff.q8_fed = down_eff.q8_rot = false; RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, down_eff, c.n_ff_exp, gact, c.rows * c.top_k, - false, rot && (!a8 || down_w5_fp8), c.swiglu_limit, + false, rot && (!a8 || down_codebook_fp8), c.swiglu_limit, c.swiglu_step != 0)); { const std::vector tab = tables(w_dn, w_dns); @@ -1336,7 +1343,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]), RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]), RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) }; - const int cut = a8 && !down_w5_fp8 ? 0 : 1; + const int cut = a8 && !down_codebook_fp8 ? 0 : 1; rad_op h = ncls == 4 ? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut, tab.data(), (int)tab.size()) diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 25d7ef9f..cfb99495 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -812,7 +812,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * (MoeFP8::a8), which the rotated four-bit plane, the codebook at E4M3 scales a 64 or 32 of K * and rotated int8 experts have. The codebook at a bf16 scale a 128 and the five-bit one do * not: under them the connections keep E4M3 codes, as for unrotated experts. */ - const bool exp8 = m.moecfg.expert_rot && !m.moecfg.expert_w5 && + const bool exp8 = m.moecfg.expert_rot && !m.moecfg.expert_w5 && !m.moecfg.expert_w6 && (!m.moecfg.expert_nl || m.moecfg.expert_g64); m.hccfg.codes_i8 = (m.trunk_i8 && (exp8 || m.moecfg.expert_bf16)) ? 1 : 0; m.a_x.q8_fed = m.hccfg.codes_i8 != 0; diff --git a/data/recipes/qwen4exp-u4-w6nl-bf16ple.recipe b/data/recipes/qwen4exp-u4-w6nl-bf16ple.recipe new file mode 100644 index 00000000..0f3436e9 --- /dev/null +++ b/data/recipes/qwen4exp-u4-w6nl-bf16ple.recipe @@ -0,0 +1,45 @@ +# Candidate Qwen3.8 Flash-Next: U4-trellis gate/up, W6NL down, BF16 PLE and vision. +# Requires the W6NL runtime and codebook in this branch. Untested as a complete model. +# CALIB: flat, verified BF16-domain expert and trunk RADGRAM2 files for this checkpoint. +# MTP_CALIB: separately captured draft Grams (including the qg/k/v and shared-gate aliases). +# First match wins. Unmatched source tensors, including vision and PLE key/value, stay BF16. +# Gate/up uses pooled input Hessians; expert-specific down Grams have the converter's layer fallback. + +blk.34.ffn_*_exps.407.weight cast dtype=bf16 +blk.34.ffn_*_exps.496.weight cast dtype=bf16 +blk.44.ffn_*_exps.292.weight cast dtype=bf16 +blk.44.ffn_*_exps.350.weight cast dtype=bf16 +blk.46.ffn_*_exps.290.weight cast dtype=bf16 +blk.46.ffn_*_exps.392.weight cast dtype=bf16 +blk.47.ffn_*_exps.122.weight cast dtype=bf16 +blk.47.ffn_*_exps.143.weight cast dtype=bf16 +blk.47.ffn_*_exps.399.weight cast dtype=bf16 +blk.47.ffn_*_exps.445.weight cast dtype=bf16 + +# Keep the IQ5R artifact's draft recipe unchanged for the controlled comparison. +blk.48.ffn_*_exps.*.weight gptq table=w4nl group=64 scale=fp8_e4m3 scale2=f32 block2=*x* scale2_value=0.0001220703125 transform=fwht128 rule=search cd=3 calib=$MTP_CALIB +blk.48.attn_qg.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 damp=0.01 tcq_gain=1.12 calib=$MTP_CALIB tcq_order=1 +blk.48.attn_k.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 damp=0.01 tcq_gain=1.12 calib=$MTP_CALIB tcq_order=1 +blk.48.attn_v.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 damp=0.01 tcq_gain=1.12 calib=$MTP_CALIB tcq_order=1 +blk.48.ffn_gate_up_shexp.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=128 block=1x* scale=f32 transform=fwht128 damp=0.01 tcq_gain=1.12 calib=$MTP_CALIB tcq_order=1 + +blk.*.ffn_gate_up_exps.*.weight gptq codes=u4 tcq=16 tcq_code=mad tcq_rows=128 block=1x* scale=f32 transform=fwht128 damp=0.01 tcq_gain=1.12 calib=$CALIB tcq_order=1 +blk.*.ffn_down_exps.*.weight gptq table=w6nl group=64 scale=fp8_e4m3 scale2=f32 block2=*x* scale2_value=0.0001220703125 transform=fwht128 rule=search cd=3 calib=$CALIB + +*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32 +*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32 +mtp.fc_hidden.weight rtn codes=fp8_e4m3 group=128 scale=f32 +mtp.fc_embedding.weight rtn codes=fp8_e4m3 group=128 scale=f32 + +blk.*.attn_qg.weight gptq codes=u5 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 damp=0.01 tcq_gain=1.16 calib=$CALIB tcq_order=1 +blk.*.ssm_inz.weight gptq codes=u5 tcq=16 tcq_code=mad tcq_rows=256 block=1x* scale=f32 transform=fwht128 damp=0.01 tcq_gain=1.16 calib=$CALIB tcq_order=1 +blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ssm_out.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search + +blk.*.ple_ngram.weight cast dtype=bf16 +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/docs/MOE-W6.md b/docs/MOE-W6.md new file mode 100644 index 00000000..018e9e72 --- /dev/null +++ b/docs/MOE-W6.md @@ -0,0 +1,27 @@ +# W6NL routed experts: candidate implementation + +`w6nl64a8h` is a six-bit scalar codebook for the routed experts' down projection. It is a candidate format, not a claim that six-bit down improves task quality. `data/recipes/qwen4exp-u4-w6nl-bf16ple.recipe` pairs it with U4 trellis gate/up and preserves the existing U5 trunk, protected BF16 experts, BF16 PLE/vision and draft recipe. The format needs this branch's Radiance build; an older build must not be expected to serve it. + +## Format + +The canonical weight is an affine `u6` code plane with a 64-entry `f32` table, `fp8_e4m3` scales per row per 64 columns and one `f32` scale above them, with the `fwht128` transform. The first 32 table entries are positive E4M3-exact magnitudes and the second 32 their negatives. Bit 5 is sign; bits 0–4 select the magnitude. The fixed upper scale is `2^-13`; the quantizer folds the unnormalised Hadamard's `1/128` into the weight scale. + +The container's six-bit codes are packed LSB-first. At load, `libr4d` arranges each row as the permuted low nibbles followed by two bit planes (the high magnitude bit and sign). Both arrangements occupy `6*K/8` code bytes per row. The kernel expands the two 16-entry halves of the magnitude table to E4M3, selects between them and merges sign before the existing FP8 WMMA. The loader checks the entire table, the fixed upper scale, transform and shape; same-width encodings with different semantics are refused. + +A trellis gate reads rotated INT8 activations; W6NL down reads a separately quantized rotated E4M3 gated intermediate, like W5NL. The architecture must select that producer and the W6 kernel for the down projection. The BF16 protected experts retain their separate path. + +## Codebook pilot + +The candidate table is fitted, not derived from the evaluation prompts. `tools/fit_w6nl.py /path/to/original-bf16-checkpoint` reads only selected BF16 safetensor rows; it does not load or serve a model. It samples five experts per layer, 128 rows per expert, and FWHT-rotates weights in groups of 128 before normalising each group of 64 by its absolute maximum. Fit layers are 0, 8, 16, 24, 32, 40 and 47 (2,867,200 weights); separate check layers are 4, 12, 20, 28, 36 and 44 (2,457,600 weights). The script fits a 32-magnitude symmetric grid and chooses distinct E4M3-representable values. + +On that separate weight sample, normalised scalar MSE with one globally optimized scale per table was approximately 0.000305 for W5NL and 0.000103 for this W6NL candidate. This is **not** a GPTQ, activation-weighted, KL or task result. It does not establish model quality or prove the candidate's table is optimal. + +A separate 41,600-group sample had candidate pre-rounded group scales between 0.136 and 1.160 in E4M3 units under the fixed upper scale, with none subnormal or above the format's maximum. This does not cover every expert; check saturation and fallback reports during actual conversion. + +## Checks and limits + +The host tests cover W6NL GPTQ on a synthetic BF16-domain Gram, all 64 code values, exact table/scale checks, packing and reference math. The synthetic GPU tests exercise all 64 codes, sorted and token-order inputs, two/four classes and decode/prefill forms; they do not load a model. The U4/W5, U4/W6, U5/W5 and U5/W6 graph declarations are checked for both TP ranks. + +A `rad-convert --plan-only` pass over the BF16 checkpoint declared 51,489 weights and estimated about 170.26 GiB for the candidate recipe. The plan used placeholder calibration paths and wrote no model: it validates neither the downloaded Grams nor conversion. + +These tests are not an end-to-end model validation. No full W6 model has been converted or scored; mixed-model inference, throughput, placement, and speculative parity remain to be measured. The main calibration directory must be reassembled and verified before conversion, with the separate draft Gram directory supplied as `MTP_CALIB`. diff --git a/libquant/lq_grid.cpp b/libquant/lq_grid.cpp index 1b8d25ec..50abc1bf 100644 --- a/libquant/lq_grid.cpp +++ b/libquant/lq_grid.cpp @@ -99,6 +99,18 @@ const std::vector& named_tables() { 14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 30.0f, -0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f, -14.0f, -16.0f, -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -30.0f } }, + /* Candidate W6NL: 32 positive E4M3-exact magnitudes followed by their negatives. Fitted + * to group-64 absmax-normalised FWHT-128 BF16 Flash-Next down-weight samples. This is a + * weight-error pilot, not a claim of improved model quality. The high code bit is the + * sign, and libr4d's layout verifies this complete table before serving it. */ + { "w6nl", { 0.875f, 2.75f, 4.5f, 6.0f, 6.5f, 7.0f, 7.5f, 8.0f, + 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, + 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 28.0f, 30.0f, 32.0f, + 36.0f, 40.0f, 44.0f, 48.0f, 52.0f, 56.0f, 60.0f, 64.0f, + -0.875f, -2.75f, -4.5f, -6.0f, -6.5f, -7.0f, -7.5f, -8.0f, + -9.0f, -10.0f, -11.0f, -12.0f, -13.0f, -14.0f, -15.0f, -16.0f, + -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -28.0f, -30.0f, -32.0f, + -36.0f, -40.0f, -44.0f, -48.0f, -52.0f, -56.0f, -60.0f, -64.0f } }, /* A one-bit weight: a sign and the block's scale. */ { "binary", { -1.0f, 1.0f } }, /* BitNet's ternary weight, a two-bit code with one code unused. */ @@ -117,7 +129,7 @@ bool parse_table(const char* s, std::vector* out, std::string* why) { char* end = nullptr; const float v = std::strtof(p, &end); if (end == p || !std::isfinite(v)) { - if (why) *why = fmt("table=%s is neither nf4, iq4nl, w4nl, w5nl, binary, ternary nor a " + if (why) *why = fmt("table=%s is neither nf4, iq4nl, w4nl, w5nl, w6nl, binary, ternary nor a " "`;`-separated list of values", s); return false; } diff --git a/libquant/lq_grid.h b/libquant/lq_grid.h index 5ad847e3..87192587 100644 --- a/libquant/lq_grid.h +++ b/libquant/lq_grid.h @@ -13,7 +13,7 @@ * table=T a scalar codebook: each code indexes a table of values, which a block's scale * multiplies. nf4 (QLoRA's NormalFloat), iq4nl (llama.cpp's IQ4_NL values), * w4nl (the rotated expert grid libr4d's w4nla8h kernel decodes), w5nl (its - * 32-level form, libr4d's w5nl64a8h), + * 32-level form, libr4d's w5nl64a8h), w6nl (the 64-level candidate), * binary {-1, +1}, ternary {-1, 0, +1}, or the values themselves, `;`-separated. * The codes are the narrowest unsigned width that indexes it. * group=N one scale per N columns of a row -- block [1 x N] diff --git a/libquant/lq_quant.h b/libquant/lq_quant.h index a6d07c08..94c3441c 100644 --- a/libquant/lq_quant.h +++ b/libquant/lq_quant.h @@ -19,7 +19,7 @@ "code dtype: i2..i8, i16, i32 (signed, symmetric), u1..u8, u16 with zero= (asymmetric), " \ "fp8_e4m3, fp8_e5m2, fp6_e2m3, fp6_e3m2, fp4_e2m1" }, \ { "table", RAD_P_STR, nullptr, \ - "a codebook the codes index: nf4, iq4nl, w4nl, w5nl, binary, ternary, or values " \ + "a codebook the codes index: nf4, iq4nl, w4nl, w5nl, w6nl, binary, ternary, or values " \ "separated by ;" }, \ { "vq", RAD_P_STR, nullptr, \ "a vector codebook file: one codeword a line, its integers (-127..127) separated by " \ diff --git a/libr4d/r4d_args.h b/libr4d/r4d_args.h index fc9f2fe0..82acb011 100644 --- a/libr4d/r4d_args.h +++ b/libr4d/r4d_args.h @@ -264,7 +264,10 @@ enum { R4D_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8, /* The M2XFP4 GEMMs' stored weight: R4D_DT_MXFP4_FRAG's fragment-order e2m1 codes, then the * [K/32][N] meta plane the kernel reads beside the E8M0 exponents (r4d_layout.cpp, m2xfp4). */ - R4D_DT_M2XFP4_FRAG = RAD_DT_PLUGIN_BASE + 9 + R4D_DT_M2XFP4_FRAG = RAD_DT_PLUGIN_BASE + 9, + /* Six-bit expert codes: row-major permuted low nibbles followed by the transposed fifth + * magnitude bit and sign bit, one dword per 32 elements in each bit plane. */ + R4D_DT_MOEW6 = RAD_DT_PLUGIN_BASE + 10 }; /* The grouped MoE GEMM's code tables, as the four dwords w4_e4m3's byte permutes read @@ -307,6 +310,20 @@ static constexpr float kW5nlTable[32] = { -0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f, -14.0f, -16.0f, -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -30.0f }; +/* W6NL's 32 E4M3-exact positive magnitudes, ordered by the low five code bits; bit 5 is sign. + * The first and second 16 magnitudes are each expanded by w4_expand, then selected by bit 4. */ +static constexpr uint32_t kW6nlMagPerm[8] = { 0x4C494336u, 0x504F4E4Du, 0x54535251u, 0x58575655u, + 0x5C5B5A59u, 0x605F5E5Du, 0x64636261u, 0x68676665u }; +static constexpr float kW6nlTable[64] = { + 0.875f, 2.75f, 4.5f, 6.0f, 6.5f, 7.0f, 7.5f, 8.0f, + 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f, + 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 28.0f, 30.0f, 32.0f, + 36.0f, 40.0f, 44.0f, 48.0f, 52.0f, 56.0f, 60.0f, 64.0f, + -0.875f, -2.75f, -4.5f, -6.0f, -6.5f, -7.0f, -7.5f, -8.0f, + -9.0f, -10.0f, -11.0f, -12.0f, -13.0f, -14.0f, -15.0f, -16.0f, + -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -28.0f, -30.0f, -32.0f, + -36.0f, -40.0f, -44.0f, -48.0f, -52.0f, -56.0f, -60.0f, -64.0f }; + /* The fixed second-level scale of `w4nl64a8h`, `w4nl32a8h` and `w5nl64a8h`: it multiplies a * weight's per-(row, 64 or 32 of K) E4M3 scale. A container states it (libquant's scale2_value=), * and the layout hook compares it with this before serving. Fixed rather than per row because the diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index f702e18e..6e83e65f 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -180,7 +180,7 @@ static int moe_w4_nl(const RadParam* p, int n_p) { const char* d = r4d_pgets(p, n_p, "dtype"); return d && (std::strcmp(d, "w4nla8h") == 0 || std::strcmp(d, "w4nl64a8h") == 0 || std::strcmp(d, "w4nl32a8h") == 0 || std::strcmp(d, "w5nl64a8h") == 0 || - std::strcmp(d, "w4nl64a8i8h") == 0 || std::strcmp(d, "w4nl32a8i8h") == 0); + std::strcmp(d, "w6nl64a8h") == 0 || std::strcmp(d, "w4nl64a8i8h") == 0 || std::strcmp(d, "w4nl32a8i8h") == 0); } /* The `a8i8` names are the same stored planes met by an int8 activation (moe_gemm_w4a8i8): * `w4a8i8` and `w4a8i8h` are w4a8's and w4a8h's, `w4nl64a8i8h` and `w4nl32a8i8h` the subgroup-scaled @@ -194,6 +194,10 @@ static bool moe_w5(const RadParam* p, int n_p) { const char* d = r4d_pgets(p, n_p, "dtype"); return d && std::strcmp(d, "w5nl64a8h") == 0; } +static bool moe_w6(const RadParam* p, int n_p) { + const char* d = r4d_pgets(p, n_p, "dtype"); + return d && std::strcmp(d, "w6nl64a8h") == 0; +} /* `w4nl64a8h` is the codebook form with one E4M3 scale per (row, 64 of K) under a fixed f32 * second level, kW4G64Scale, stored once per weight (`u4*fp8_e4m3[1x64]*f32[*x*]/fwht128` with the * table). Codes are stored as w4nla8h's. The scale view selects the E4M3 plane and the second @@ -205,7 +209,7 @@ static int moe_w4_g64(const RadParam* p, int n_p) { const char* d = r4d_pgets(p, n_p, "dtype"); if (!d) return 0; return (std::strcmp(d, "w4nl64a8h") == 0 || std::strcmp(d, "w5nl64a8h") == 0 || - std::strcmp(d, "w4nl64a8i8h") == 0) ? 2 + std::strcmp(d, "w6nl64a8h") == 0 || std::strcmp(d, "w4nl64a8i8h") == 0) ? 2 : (std::strcmp(d, "w4nl32a8h") == 0 || std::strcmp(d, "w4nl32a8i8h") == 0) ? 4 : 0; } static int moe_w4_rot(const RadParam* p, int n_p) { @@ -933,11 +937,12 @@ int moew4_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* char fw[RAD_ENC_STR] = ""; if (moe_w4_rot(p, n_p)) std::snprintf(fw, sizeof fw, "fwht%lld", g.group); const bool nl = moe_w4_nl(p, n_p); - const bool w5 = moe_w5(p, n_p); + const bool w5 = moe_w5(p, n_p), w6 = moe_w6(p, n_p); const int g64 = moe_w4_g64(p, n_p); /* scale groups a 128 of K, or 0 */ - if (w5 && g.K % 32) return RAD_E_SHAPE; /* a sign word is 32 elements */ - if (g64 ? !r4d_enc::affine_table2(enc, w5 ? RAD_U5 : RAD_U4, RAD_F8E4M3, 1, g.group / g64, - RAD_F32, RAD_F32, w5 ? 32 : 16, fw) + if ((w5 || w6) && g.K % 32) return RAD_E_SHAPE; /* a bit-plane word is 32 elements */ + if (g64 ? !r4d_enc::affine_table2(enc, w6 ? RAD_U6 : w5 ? RAD_U5 : RAD_U4, + RAD_F8E4M3, 1, g.group / g64, + RAD_F32, RAD_F32, w6 ? 64 : w5 ? 32 : 16, fw) : nl ? !r4d_enc::affine_table(enc, RAD_U4, RAD_BF16, 1, g.group, RAD_F32, 16, fw) : !r4d_enc::affine(enc, RAD_I4, RAD_BF16, 1, g.group, RAD_DT_INVALID, fw)) return RAD_E_DTYPE; @@ -955,11 +960,15 @@ int moew4_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* return RAD_E_UNSUPPORTED; /* bf16 a row a group, as it is */ } if (operand != Q_B) return RAD_E_UNSUPPORTED; - if (nl ? !selects(enc, sel, n, "codes", "table") || !dims(pl[1], 1, w5 ? 32 : 16) + if (nl ? !selects(enc, sel, n, "codes", "table") || !dims(pl[1], 1, w6 ? 64 : w5 ? 32 : 16) : !selects(enc, sel, n, "codes")) return RAD_E_SHAPE; if (!dims(pl[0], g.N, g.K)) return RAD_E_SHAPE; if (!g64 && (g.N % 16 || g.K % 64)) return RAD_E_SHAPE; + if (w6) { + fill(out, "r4d.moew6nh64.w", R4D_DT_MOEW6, g.N, g.K, g.N * (g.K / 4) * 3); + return RAD_OK; + } if (w5) { fill(out, "r4d.moew5nh64.w", R4D_DT_MOEW5, g.N, g.K, g.N * (g.K / 8) * 5); return RAD_OK; @@ -986,6 +995,12 @@ bool moew5_table_is_kernels(const RadTensor& t) { if (v[i] != kW5nlTable[i]) return false; return true; } +bool moew6_table_is_kernels(const RadTensor& t) { + const float* v = (const float*)t.data; + for (int i = 0; i < 64; ++i) + if (v[i] != kW6nlTable[i]) return false; + return true; +} /* The expansion's nibble order, applied to a 64-bit word (two dwords). Canonical element 8g+i is * nibble i of dword g; stored, byte b holds element b low and b+4 high (nibbles n0 n4 n1 n5 n2 n6 @@ -1095,6 +1110,54 @@ void moew5_row(const uint8_t* s, uint8_t* d, int64_t K, uint8_t* nib, bool forwa } } } +/* Six-bit rows: canonical 8 codes in 6 bytes; served as W5's permuted low nibbles and + * two transposed bit planes (magnitude bit 4, sign bit 5). All layouts are K*6/8 bytes. */ +void moew6_row(const uint8_t* s, uint8_t* d, int64_t K, uint8_t* nib, bool forward) { + if (forward) { + uint8_t* hi = d + K / 2; + uint8_t* sg = hi + K / 8; + for (int64_t c0 = 0; c0 < K; c0 += 32) { + uint32_t h = 0, sign = 0; + for (int64_t k = c0; k < c0 + 32; k += 8) { + uint64_t x = 0; + std::memcpy(&x, s + k / 8 * 6, 6); + uint32_t lo = 0; + for (int i = 0; i < 8; ++i) { + const uint32_t c = (uint32_t)(x >> (6 * i)) & 63u; + lo |= (c & 15u) << (4 * i); + const uint32_t pos = moew5_sign_bit(k - c0 + i); + h |= ((c >> 4) & 1u) << pos; + sign |= (c >> 5) << pos; + } + std::memcpy(nib + k / 2, &lo, 4); + } + std::memcpy(hi + c0 / 8, &h, 4); + std::memcpy(sg + c0 / 8, &sign, 4); + } + moew4_permute(nib, d, K / 2, true); + return; + } + moew4_permute(s, nib, K / 2, false); + const uint8_t* hi = s + K / 2; + const uint8_t* sg = hi + K / 8; + for (int64_t c0 = 0; c0 < K; c0 += 32) { + uint32_t h = 0, sign = 0; + std::memcpy(&h, hi + c0 / 8, 4); + std::memcpy(&sign, sg + c0 / 8, 4); + for (int64_t k = c0; k < c0 + 32; k += 8) { + uint32_t lo = 0; + std::memcpy(&lo, nib + k / 2, 4); + uint64_t x = 0; + for (int i = 0; i < 8; ++i) { + const uint32_t pos = moew5_sign_bit(k - c0 + i); + const uint64_t c = ((lo >> (4 * i)) & 15u) | + (((h >> pos) & 1u) << 4) | (((sign >> pos) & 1u) << 5); + x |= c << (6 * i); + } + std::memcpy(d + k / 8 * 6, &x, 6); + } + } +} } /* namespace */ namespace { @@ -1125,6 +1188,14 @@ int moew4_relayout_by(MoeViewFn view, const RadParam* p, int n_p, int operand, std::memcpy(dst, pdata(pl[0]), (size_t)L.bytes); return RAD_OK; } + if (moe_w6(v.p, v.n)) { + if (!moew6_table_is_kernels(pl[1])) return RAD_E_DTYPE; + const int64_t rb = g.K / 4 * 3; + std::vector nib((size_t)(g.K / 2)); + for (long long nn = 0; nn < g.N; ++nn) + moew6_row(pdata(pl[0]) + nn * rb, (uint8_t*)dst + nn * rb, g.K, nib.data(), true); + return RAD_OK; + } if (moe_w5(v.p, v.n)) { if (!moew5_table_is_kernels(pl[1])) return RAD_E_DTYPE; const int64_t rb = g.K / 8 * 5; @@ -1154,6 +1225,15 @@ int moew4_unrelayout_by(MoeViewFn view, const RadParam* p, int n_p, int operand, std::memcpy(pl[1].data, &kW4G64Scale, sizeof kW4G64Scale); return RAD_OK; } + if (moe_w6(v.p, v.n)) { + const int64_t rb = g.K / 4 * 3; + std::vector nib((size_t)(g.K / 2)); + for (long long nn = 0; nn < g.N; ++nn) + moew6_row((const uint8_t*)src + nn * rb, (uint8_t*)pl[0].data + nn * rb, g.K, + nib.data(), false); + std::memcpy(pl[1].data, kW6nlTable, sizeof kW6nlTable); + return RAD_OK; + } if (moe_w5(v.p, v.n)) { const int64_t rb = g.K / 8 * 5; std::vector nib((size_t)(g.K / 2)); diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index 7fd6b23c..8036fbbe 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -491,6 +491,25 @@ __device__ __forceinline__ Stage8 w5_expand(uint4 p, uint32_t sg, const uint32_t return r; } +/* W6NL: low nibbles address both halves of the 32 positive levels. The transposed magnitude + * bit selects a byte from those expansions and the transposed sign bit supplies E4M3's sign. */ +__device__ __forceinline__ Stage8 w6_expand(uint4 p, uint32_t mh, uint32_t sg, + const uint32_t (&tab)[4]) { + const uint32_t high[4] = { 0x5C5B5A59u, 0x605F5E5Du, 0x64636261u, 0x68676665u }; + Stage8 l = w4_expand(p, tab), h = w4_expand(p, high); + uint32_t a[8] = { l.v.x, l.v.y, l.v.z, l.v.w, l.w.x, l.w.y, l.w.z, l.w.w }; + const uint32_t b[8] = { h.v.x, h.v.y, h.v.z, h.v.w, h.w.x, h.w.y, h.w.z, h.w.w }; +#pragma unroll + for (uint32_t m = 0; m < 8; ++m) { + const uint32_t top = (mh << m) & 0x80808080u; + const uint32_t mask = top | (top - (top >> 7)); + a[m] = (a[m] ^ ((a[m] ^ b[m]) & mask)) | ((sg << m) & 0x80808080u); + } + l.v = make_uint4(a[0], a[1], a[2], a[3]); + l.w = make_uint4(a[4], a[5], a[6], a[7]); + return l; +} + /* ---- the codebook levels against an int8 activation --------------------------------------------- * * The iu8 WMMA wants the levels as int8. The two's-complement nibble is its own value @@ -729,7 +748,7 @@ __device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) { static_assert(kRowS || kBlock % FN == 0, "a block's N rows must sit in one 128-row weight scale row"); /* Scale groups per 128-wide block: one, or the 64- or 32-column groups at W4 2-4. */ - constexpr uint32_t kSub = W4 == 3 ? 4u : (W4 == 2 || W4 == 4) ? 2u : 1u; + constexpr uint32_t kSub = W4 == 3 ? 4u : (W4 == 2 || W4 == 4 || W4 == 5) ? 2u : 1u; /* What multiplies a subgroup's E4M3 scale: the format's fixed second level, and at I8 the * levels' unit. */ constexpr float kSubScale = I8 ? kW4G64Scale * kW4nlI8Unit : kW4G64Scale; @@ -804,7 +823,8 @@ __device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) { constexpr uint32_t kEwTPR = FK / 32, kEwRPP = NTHR / kEwTPR; constexpr uint32_t kEwBP = (FN + kEwRPP - 1) / kEwRPP; [[maybe_unused]] uint4 ew_b4[AL && W4 ? kEwBP : 1]; - [[maybe_unused]] uint32_t ew_sp[AL && W4 == 4 ? kEwBP : 1]; + [[maybe_unused]] uint32_t ew_sp[AL && (W4 == 4 || W4 == 5) ? kEwBP : 1]; + [[maybe_unused]] uint32_t ew_hp[AL && W4 == 5 ? kEwBP : 1]; [[maybe_unused]] Stage8 ew_b8[AL && !W4 ? kEwBP : 1]; [[maybe_unused]] bool ew_ok[AL ? kEwBP : 1]; [[maybe_unused]] const uint8_t* ew_wp = nullptr; @@ -839,8 +859,11 @@ __device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) { if constexpr (W4) { ew_b4[p] = moe_w4_load(ew_wp, ew_ok[p] ? wn0 + r : 0u, C.w_ld, sk, true); - if constexpr (W4 == 4) - ew_sp[p] = u32_load_w((const uint32_t*)(wr + (C.k >> 1) + (sk >> 3))); + if constexpr (W4 == 4 || W4 == 5) + ew_sp[p] = u32_load_w((const uint32_t*)(wr + (C.k >> 1) + + (W4 == 5 ? (C.k >> 3) : 0) + (sk >> 3))); + if constexpr (W4 == 5) + ew_hp[p] = u32_load_w((const uint32_t*)(wr + (C.k >> 1) + (sk >> 3))); } else ew_b8[p] = stage8_load_w(wr + sk, true); } @@ -1110,7 +1133,8 @@ __device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) { * the fold reads them from LDS. Bit-identical. */ Stage8 apre[kAP]; uint4 bpre4[kBP]; /* W4: packed nibbles, expanded at store time as before */ - uint32_t spre[W4 == 4 ? kBP : 1]; /* W4 4: the same 32 elements' sign bits */ + uint32_t spre[(W4 == 4 || W4 == 5) ? kBP : 1]; + uint32_t hpre[W4 == 5 ? kBP : 1]; Stage8 bpre8[kBP]; /* otherwise: the fp8 bytes themselves */ /* kUL: whether each staged row is live. Under kUL every row's tile is loaded (a dead row * reads a row that exists) and the zero is selected at the LDS store. A guarded load writes @@ -1213,7 +1237,8 @@ __device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) { bok[p] = ew_ok[p]; if constexpr (W4) { bpre4[p] = ew_b4[p]; - if constexpr (W4 == 4) spre[p] = ew_sp[p]; + if constexpr (W4 == 4 || W4 == 5) spre[p] = ew_sp[p]; + if constexpr (W4 == 5) hpre[p] = ew_hp[p]; } else bpre8[p] = ew_b8[p]; continue; @@ -1221,7 +1246,8 @@ __device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) { /* The dead rows' zeros, as w4_load / stage8_load give them. */ if constexpr (W4) { bpre4[p] = ew_ok[p] ? ew_b4[p] : make_uint4(0, 0, 0, 0); - if constexpr (W4 == 4) spre[p] = ew_ok[p] ? ew_sp[p] : 0u; + if constexpr (W4 == 4 || W4 == 5) spre[p] = ew_ok[p] ? ew_sp[p] : 0u; + if constexpr (W4 == 5) hpre[p] = ew_ok[p] ? ew_hp[p] : 0u; } else { bpre8[p].v = ew_ok[p] ? ew_b8[p].v : make_uint4(0, 0, 0, 0); bpre8[p].w = ew_ok[p] ? ew_b8[p].w : make_uint4(0, 0, 0, 0); @@ -1243,10 +1269,12 @@ __device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) { if constexpr (W4) { bpre4[p] = moe_w4_load(Wp, kUL && !ok ? wn0 : wn0 + r, w_ld, cc + sk, kUL || ok); - if constexpr (W4 == 4) + if constexpr (W4 == 4 || W4 == 5) spre[p] = kUL || ok ? u32_load_w((const uint32_t*)(wr + (K >> 1) + - ((cc + sk) >> 3))) - : 0u; + (W4 == 5 ? (K >> 3) : 0) + ((cc + sk) >> 3))) : 0u; + if constexpr (W4 == 5) + hpre[p] = kUL || ok ? u32_load_w((const uint32_t*)(wr + (K >> 1) + + ((cc + sk) >> 3))) : 0u; } else bpre8[p] = stage8_load_w(wr + cc + sk, kUL || ok); } @@ -1286,7 +1314,10 @@ __device__ __forceinline__ void moe_gemm_q_body(R4D_MOEGQ_PARAMS) { /* a dead row's zero, where the packed form held it before (see bok) */ const bool live = !kUL || bok[p]; const uint4 b4 = live ? bpre4[p] : make_uint4(0, 0, 0, 0); - if constexpr (W4 == 4) + if constexpr (W4 == 5) + stage8_store(s_b, r, sk, w6_expand(b4, live ? hpre[p] : 0u, + live ? spre[p] : 0u, tab.v)); + else if constexpr (W4 == 4) stage8_store(s_b, r, sk, w5_expand(b4, live ? spre[p] : 0u, tab.v)); else if constexpr (W4) stage8_store(s_b, r, sk, moe_w4_bytes(b4, tab.v)); @@ -1522,7 +1553,7 @@ template __device__ __forceinline__ void moe_down_dec_body(R4D_MOEDD_PARAMS) { constexpr bool UW = true; constexpr uint32_t FM = 16, FN = 64, FK = kFK, NTHR = 4 * kWave; - constexpr uint32_t kSub = W4 == 3 ? 4u : (W4 == 2 || W4 == 4) ? 2u : 1u; + constexpr uint32_t kSub = W4 == 3 ? 4u : (W4 == 2 || W4 == 4 || W4 == 5) ? 2u : 1u; /* moe_gemm_q_kernel's I8, with its per-row scale and its subgroup unit. */ constexpr bool kRowS = W4 != 0 || I8; constexpr float kSubScale = I8 ? kW4G64Scale * kW4nlI8Unit : kW4G64Scale; @@ -1659,7 +1690,8 @@ __device__ __forceinline__ void moe_down_dec_body(R4D_MOEDD_PARAMS) { * zero selected at the LDS store, scale-role registers uninitialised (see the note there). */ Stage8 apre[kAP]; uint4 bpre4[kBP]; - uint32_t spre[W4 == 4 ? kBP : 1]; + uint32_t spre[(W4 == 4 || W4 == 5) ? kBP : 1]; + uint32_t hpre[W4 == 5 ? kBP : 1]; Stage8 bpre8[kBP]; using PwsT = uint32_t; /* a 16-bit scale zero-extended: see u16_load_w */ float pau[1]; @@ -1702,10 +1734,12 @@ __device__ __forceinline__ void moe_down_dec_body(R4D_MOEDD_PARAMS) { if constexpr (W4) { const uint8_t* wr = Wp + (size_t)(wn0 + r) * w_ld; bpre4[p] = moe_w4_load(Wp, wn0 + r, w_ld, cc + sk, ok); - if constexpr (W4 == 4) + if constexpr (W4 == 4 || W4 == 5) spre[p] = ok ? u32_load_w((const uint32_t*)(wr + (K >> 1) + - ((cc + sk) >> 3))) - : 0u; + (W4 == 5 ? (K >> 3) : 0) + ((cc + sk) >> 3))) : 0u; + if constexpr (W4 == 5) + hpre[p] = ok ? u32_load_w((const uint32_t*)(wr + (K >> 1) + + ((cc + sk) >> 3))) : 0u; } else bpre8[p] = stage8_load_w(Wp + (size_t)(wn0 + r) * w_ld + cc + sk, ok); } @@ -1731,7 +1765,9 @@ __device__ __forceinline__ void moe_down_dec_body(R4D_MOEDD_PARAMS) { for (uint32_t q = 0; q < kBP; ++q) { const uint32_t r = sn + q * kRPP; if (r >= FN) continue; - if constexpr (W4 == 4) + if constexpr (W4 == 5) + stage8_store(s_b, r, sk, w6_expand(bpre4[q], hpre[q], spre[q], tab.v)); + else if constexpr (W4 == 4) stage8_store(s_b, r, sk, w5_expand(bpre4[q], spre[q], tab.v)); else if constexpr (W4) stage8_store(s_b, r, sk, moe_w4_bytes(bpre4[q], tab.v)); @@ -2629,7 +2665,8 @@ static inline bool r4d_moe_decode_band(long long T, long long n_expert) { * the 4-bit formats still take two blocks up to 80 rows (two sequences at depth 3): on Flash-Next * (w4nl64a8h) a one-stream step at depth 3 is 1.1% shorter at TP4 and no slower at TP2. */ template -constexpr long long kMoeGuFk256Rows = W4 == 4 ? (1ll << 40) : (W4 == 2 || W4 == 3) ? 80 : 0; +constexpr long long kMoeGuFk256Rows = (W4 == 4 || W4 == 5) ? (1ll << 40) + : (W4 == 2 || W4 == 3) ? 80 : 0; /* The decode form's staged K, pinnable for tests: 0 kMoeGuFk256Rows's rule, 1 one 128-wide block * per pass, 2 two wherever allowed. r4d_selftest compares both byte for byte. */ static int g_moe_fk_pin = 0; @@ -2848,6 +2885,7 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) { * magnitudes, or two's complement for w4a8 and w4a8h. */ const char* wdt = r4d_gets(a, "dtype"); const uint32_t* tab = I8 ? kW4IntPermI8 + : W4 == 5 ? kW6nlMagPerm : W4 == 4 ? kW5nlMagPerm : (W4 && wdt && (!std::strcmp(wdt, "w4nla8h") || !std::strcmp(wdt, "w4nl64a8h") || @@ -2860,10 +2898,12 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) { long long k, MoeCls* c) -> int { long long w_ld = 0, ws_ld = 0; size_t w_s0 = 0, s_s0 = 0; - int rc = wtab_of(w, W4 == 4 ? (uint32_t)R4D_DT_MOEW5 + int rc = wtab_of(w, W4 == 5 ? (uint32_t)R4D_DT_MOEW6 + : W4 == 4 ? (uint32_t)R4D_DT_MOEW5 : W4 ? (uint32_t)R4D_DT_MOEW4 : I8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, - W4 == 4 ? 5 : W4 ? 4 : 8, cnt, n, k, &c->w, &w_s0, &w_ld); + W4 == 5 ? 6 : W4 == 4 ? 5 : W4 ? 4 : 8, + cnt, n, k, &c->w, &w_s0, &w_ld); if (rc != RAD_OK) return rc; if constexpr (W4 >= 2) { /* One E4M3 byte per (row, group of 64 or 32 K). The pitch is derived, not read: the @@ -2875,8 +2915,9 @@ static int moe_gemm_launch(const RadArgs* a, RadStream stream, int ncls = 2) { if (rc != RAD_OK) return rc; /* A 5-bit row is its nibbles then its sign bits; the kernel finds the signs K/2 bytes * in. */ - if (W4 == 4 ? (w_ld % 8 || k % 32) : (w_ld % 2)) return R4D_NO(RAD_E_STRIDE); - w_ld = W4 == 4 ? w_ld / 8 * 5 : w_ld / 2; + if (W4 == 5 ? (w_ld % 4 || k % 32) : W4 == 4 ? (w_ld % 8 || k % 32) : (w_ld % 2)) + return R4D_NO(RAD_E_STRIDE); + w_ld = W4 == 5 ? w_ld / 4 * 3 : W4 == 4 ? w_ld / 8 * 5 : w_ld / 2; ws_ld = k / kBlock; } else if constexpr (W4) { /* The scale plane is one bf16 per (row, 128 of K), not per 128x128 tile. */ @@ -3138,6 +3179,7 @@ extern "C" int r4d_rad_moe_gemm_w4a8(const RadArgs* a, RadStream stream) { if (wdt && !std::strcmp(wdt, "w4nl64a8h")) return moe_gemm_launch<2>(a, stream); if (wdt && !std::strcmp(wdt, "w4nl32a8h")) return moe_gemm_launch<3>(a, stream); if (wdt && !std::strcmp(wdt, "w5nl64a8h")) return moe_gemm_launch<4>(a, stream); + if (wdt && !std::strcmp(wdt, "w6nl64a8h")) return moe_gemm_launch<5>(a, stream); return moe_gemm_launch<1>(a, stream); } @@ -3168,6 +3210,7 @@ extern "C" int r4d_rad_moe_gemm_w4a8_mod4(const RadArgs* a, RadStream stream) { if (wdt && !std::strcmp(wdt, "w4nl64a8h")) return moe_gemm_launch<2>(a, stream, 4); if (wdt && !std::strcmp(wdt, "w4nl32a8h")) return moe_gemm_launch<3>(a, stream, 4); if (wdt && !std::strcmp(wdt, "w5nl64a8h")) return moe_gemm_launch<4>(a, stream, 4); + if (wdt && !std::strcmp(wdt, "w6nl64a8h")) return moe_gemm_launch<5>(a, stream, 4); return moe_gemm_launch<1>(a, stream, 4); } diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 3b2835d3..a5fb9ed9 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -5109,7 +5109,7 @@ static const RadConstraint cMoeMx[] = { static const RadConstraint cMoeGemmW4[] = { C_GE("M", 1), C_DIV("N", 64), C_DIV("K", 128), C_GE("n_expert", 1), C_LE("n_expert", 65536), C_GE("top_k", 1), C_EQ("group", 128), - C_IN("dtype", "w4a8 w4a8h w4nla8h w4nl64a8h w4nl32a8h w5nl64a8h"), + C_IN("dtype", "w4a8 w4a8h w4nla8h w4nl64a8h w4nl32a8h w5nl64a8h w6nl64a8h"), }; /* The op against an int8 activation with an f32 scale per (row, 128 of K): int8 experts with a * bf16 scale per (row, 128 of K), `i8a8h` rotated 128 wide along K as its activation is; and the diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 0c28b624..3a1dda27 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -2327,15 +2327,15 @@ static Planes nl_planes(const std::vector& w, int64_t N, int64_t K, int64 * the stored scale. Planes: codes, scale (E4M3 [1 x gs]), scale.1 (f32 constant), table. With * `w5`, w5nl64a8h's: u5 codes into kW5nlTable, whose largest entry is 30. */ static Planes nl64_planes(const std::vector& w, int64_t N, int64_t K, int64_t gs = 64, - bool w5 = false) { - const float* tab = w5 ? kW5nlTable : kW4nlTable; - const int nt = w5 ? 32 : 16; - const float top = w5 ? 30.0f : 22.0f; + int w5 = 0) { + const float* tab = w5 == 2 ? kW6nlTable : w5 ? kW5nlTable : kW4nlTable; + const int nt = w5 == 2 ? 64 : w5 ? 32 : 16; + const float top = w5 == 2 ? 64.0f : w5 ? 30.0f : 22.0f; Planes p; rad_enc_clear(&p.enc); rad_enc_copy_str(p.enc.scheme, "affine"); rad_enc_copy_str(p.enc.transform, "fwht128"); - rad_enc_add_plane(&p.enc, "codes", w5 ? RAD_U5 : RAD_U4, 1, 1); + rad_enc_add_plane(&p.enc, "codes", w5 == 2 ? RAD_U6 : w5 ? RAD_U5 : RAD_U4, 1, 1); rad_enc_add_plane(&p.enc, "scale", RAD_F8E4M3, 1, gs); rad_enc_add_plane(&p.enc, "scale.1", RAD_F32, 0, 0); rad_enc_add_table(&p.enc, "table", RAD_F32, 1, nt); @@ -2362,7 +2362,8 @@ static Planes nl64_planes(const std::vector& w, int64_t N, int64_t K, int int best = 0; for (int c = 1; c < nt; ++c) if (std::fabs(u - tab[c]) < std::fabs(u - tab[best])) best = c; - rad_store_code(p.data[0].data() + n * crow, w5 ? RAD_U5 : RAD_U4, + rad_store_code(p.data[0].data() + n * crow, + w5 == 2 ? RAD_U6 : w5 ? RAD_U5 : RAD_U4, g * 128 + h * gs + j, best); } } @@ -22850,15 +22851,15 @@ static void moe_aligned_down_tile(const Plugin& pl, const RadKernelInfo* row, Ra * it (`moe_gemm_i8a8`), each with its own four-class twin. */ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int sub = 0, bool w5 = false, bool four = false, int64_t top_k = 2, int act8 = 0, - int64_t ag = 128) { + int64_t ag = 128, bool w6 = false) { const bool g64 = sub > 1, w8 = act8 == 2; /* Against an int8 activation the codebook is read at its int8 levels (r4d_args.h's kW4nlI8). */ float tab_i8[16]; for (int i = 0; i < 16; ++i) tab_i8[i] = (float)(i < 8 ? kW4nlI8[i] : -kW4nlI8[i - 8]) * kW4nlI8Unit; - const float* tab = w5 ? kW5nlTable : act8 ? tab_i8 : kW4nlTable; + const float* tab = w6 ? kW6nlTable : w5 ? kW5nlTable : act8 ? tab_i8 : kW4nlTable; const char* const rname = w8 ? "moe_gemm_i8a8" : act8 ? "moe_gemm_w4a8i8" : "moe_gemm_w4a8"; - if (act8 && (w5 || (w8 && sub))) { + if ((w6 && (w5 || sub != 2)) || (act8 && (w5 || w6 || (w8 && sub)))) { ok((std::string(rname) + " (" + sh.name + ")").c_str(), false, "no such int8 form"); return; } @@ -22871,7 +22872,8 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int } const char* dt = w8 ? "i8a8" : act8 ? (sub == 4 ? "w4nl32a8i8h" : g64 ? "w4nl64a8i8h" : "w4a8i8") - : w5 ? "w5nl64a8h" : sub == 4 ? "w4nl32a8h" : g64 ? "w4nl64a8h" : "w4a8"; + : w6 ? "w6nl64a8h" : w5 ? "w5nl64a8h" + : sub == 4 ? "w4nl32a8h" : g64 ? "w4nl64a8h" : "w4a8"; const std::string what = std::string(rname) + " vs a host decode (T=" + std::to_string(Tr) + ", " + sh.name + (g64 || act8 ? std::string(", ") + dt : std::string()) + @@ -22900,7 +22902,8 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int for (int c = 0; c < 2; ++c) { const int ow = c ? 6 : 2, os = c ? 7 : 3; const int64_t kbc = Kc[c] / group; - const int64_t wbytes = w8 ? Nc[c] * Kc[c] : w5 ? Nc[c] * Kc[c] / 8 * 5 : Nc[c] * Kc[c] / 2; + const int64_t wbytes = w8 ? Nc[c] * Kc[c] : w6 ? Nc[c] * Kc[c] / 4 * 3 + : w5 ? Nc[c] * Kc[c] / 8 * 5 : Nc[c] * Kc[c] / 2; wq[c].assign((size_t)(nec[c] * wbytes), 0); ws[c].assign((size_t)(nec[c] * Nc[c] * kbc * (sub == 4 ? 2 : 1)), 0); std::vector wsrc((size_t)(Nc[c] * Kc[c])); @@ -22911,8 +22914,16 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int wsrc[(size_t)(n * Kc[c] + k)] = (float)(((e * 7 + n * 31 + k * 17) % 61) - 30) / 37.0f; cp[c].push_back(w8 ? int8_planes(wsrc, Nc[c], Kc[c], RAD_BF16) - : g64 ? nl64_planes(wsrc, Nc[c], Kc[c], 128 / sub, w5) + : g64 ? nl64_planes(wsrc, Nc[c], Kc[c], 128 / sub, w6 ? 2 : w5) : int4_planes(wsrc, Nc[c], Kc[c], group, RAD_BF16, false)); + if (w6) { + /* Exercise every six-bit code, not only the levels the source happened to pick. */ + Planes& p = cp[c].back(); + for (int64_t n = 0; n < Nc[c]; ++n) + for (int64_t k = 0; k < Kc[c]; ++k) + rad_store_code(p.data[0].data() + n * p.row_bytes(0), RAD_U6, k, + (int)((k + n * 17 + e * 13) % 64)); + } std::vector w, sc; const int rw = g64 ? stored(r, lp, ow, cp[c].back(), { "codes", "table" }, &w) : stored(r, lp, ow, cp[c].back(), { "codes" }, &w); @@ -22990,13 +23001,15 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int std::vector ts = { T(d_a, act8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, { M, K }), T(d_as, RAD_F32, { M, kb }), - T(d_w[0], w8 ? (uint32_t)RAD_I8 : w5 ? (uint32_t)R4D_DT_MOEW5 : (uint32_t)R4D_DT_MOEW4, + T(d_w[0], w8 ? (uint32_t)RAD_I8 : w6 ? (uint32_t)R4D_DT_MOEW6 + : w5 ? (uint32_t)R4D_DT_MOEW5 : (uint32_t)R4D_DT_MOEW4, { nec[0], sh.N0, sh.K0 }), g64 ? T(d_ws[0], RAD_F8E4M3, { nec[0], sh.N0, sub * sh.K0 / group }) : T(d_ws[0], RAD_BF16, { nec[0], sh.N0, sh.K0 / group }), T(d_s, RAD_I32, { Tr }), T(d_o, RAD_I32, { ne + 1 }), - T(d_w[1], w8 ? (uint32_t)RAD_I8 : w5 ? (uint32_t)R4D_DT_MOEW5 : (uint32_t)R4D_DT_MOEW4, + T(d_w[1], w8 ? (uint32_t)RAD_I8 : w6 ? (uint32_t)R4D_DT_MOEW6 + : w5 ? (uint32_t)R4D_DT_MOEW5 : (uint32_t)R4D_DT_MOEW4, { nec[1], sh.N1, sh.K1 }), g64 ? T(d_ws[1], RAD_F8E4M3, { nec[1], sh.N1, sub * sh.K1 / group }) : T(d_ws[1], RAD_BF16, { nec[1], sh.N1, sh.K1 / group }), @@ -23146,7 +23159,7 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int hi->stride[0] = t.stride[0] * 2; hi->data = (char*)t.data + t.stride[0] * bits / 8; }; - const int wbits = w8 ? 8 : w5 ? 5 : 4, sbits = g64 ? 8 : 16; + const int wbits = w8 ? 8 : w6 ? 6 : w5 ? 5 : 4, sbits = g64 ? 8 : 16; RadTensor c4w[4], c4s[4]; halves(ts[2], wbits, &c4w[0], &c4w[2]); halves(ts[3], sbits, &c4s[0], &c4s[2]); @@ -23190,6 +23203,20 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int moe_dec_variants(pl, r4, a4, d_y, (size_t)(Tr * N), fk2, what4); } +static void moe_w6_cases(const Plugin& pl) { + const MoeW4Shape sh[] = { + { "w6 gate/up", 256, 256, 128, 256, 2, 5 }, + { "w6 down sorted", 256, 256, 256, 128, 1, 6, true }, + }; + for (const auto& s : sh) + for (int64_t t : { (int64_t)24, (int64_t)200 }) + moe_w4_gemm(pl, t, s, 2, false, true, 2, 0, 128, true); + /* Flash-Next TP2's actual down geometry, including the odd width and top-k=10. */ + const MoeW4Shape qfn = { "Flash-Next TP2 down", 2560, 384, 2560, 256, 1, 20, true }; + for (int64_t t : { (int64_t)10, (int64_t)200 }) + moe_w4_gemm(pl, t, qfn, 2, false, true, 10, 0, 128, true); +} + /* The four-class grouped GEMM, each class at its own geometry, against a host decode. * * moe_w4_gemm's four-class pass pairs geometries (0 with 2, 1 with 3), with class 0 always wide. @@ -32911,8 +32938,12 @@ static void device_phase(const Plugin& pl) { for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) moe_w4_gemm(pl, t, sh, 2, true); } + moe_w6_cases(pl); } + /* Also expose the W6 tests alone while retaining them in the normal W4 row's test. */ + if (sel("moe_gemm_w6nl")) moe_w6_cases(pl); + /* The grouped GEMM against an int8 activation: the same shapes through each row's forms. */ { static const MoeW4Shape kShapes8[] = { diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index d0f58249..1048ce5c 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -295,6 +295,7 @@ static CbForm cb_form(const RadParam* p, int n_p) { if (s && !std::strcmp(s, "w4nl64a8h")) return CbForm{ 4, 64, RAD_F8E4M3, true }; if (s && !std::strcmp(s, "w4nl32a8h")) return CbForm{ 4, 32, RAD_F8E4M3, true }; if (s && !std::strcmp(s, "w5nl64a8h")) return CbForm{ 5, 64, RAD_F8E4M3, true }; + if (s && !std::strcmp(s, "w6nl64a8h")) return CbForm{ 6, 64, RAD_F8E4M3, true }; /* The same stored experts under their names against an int8 activation. */ if (s && !std::strcmp(s, "w4nl64a8i8h")) return CbForm{ 4, 64, RAD_F8E4M3, true }; if (s && !std::strcmp(s, "w4nl32a8i8h")) return CbForm{ 4, 32, RAD_F8E4M3, true }; @@ -318,7 +319,7 @@ static int cb_check(const RadParam* p, int n_p, int operand, const RadEncoding* const RadEncPlane& b = enc->plane[sel[1]]; if (codes) return !std::strcmp(a.role, "codes") && a.kind == RAD_PLANE_TILED && - a.dtype == (f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) && + a.dtype == (f.bits == 6 ? (uint32_t)RAD_U6 : f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) && a.block[0] == 1 && a.block[1] == 1 && !std::strcmp(b.role, "table") && b.kind == RAD_PLANE_TABLE && b.dtype == RAD_F32 && b.extent[0] == 1 && b.extent[1] == ((int64_t)1 << f.bits) @@ -368,7 +369,7 @@ static const RadPlanesHeader* cb_joined(const RadTensor& t) { * `row_bytes` apart, the layout rad_planes.h keeps. */ struct CbTensor { RadTensor t; /* `data`: the codes plane, from the tile's first weight row */ - float tab[32]; + float tab[64]; int64_t cols = 0, row_bytes = 0; int bits = 0; }; @@ -385,13 +386,13 @@ struct LdCb { * codes not covering [n, k]. A u4 or u5 entry is always joined: only its table says what a code * means. */ static int cb_codes(const RadTensor& w, int64_t n, int64_t k, CbTensor* out) { - if (w.dtype != RAD_U4 && w.dtype != RAD_U5) return 0; + if (w.dtype != RAD_U4 && w.dtype != RAD_U5 && w.dtype != RAD_U6) return 0; const RadPlanesHeader* h = rad_planes_header(w.data); const RadPlanesEntry *ec = nullptr, *et = nullptr; const void* codes = h ? rad_planes_find(w.data, "codes", &ec) : nullptr; const void* tab = h ? rad_planes_find(w.data, "table", &et) : nullptr; if (!codes || !tab || h->n_planes != 2) return RAD_E_DTYPE; - const int bits = ec->dtype == RAD_U4 ? 4 : ec->dtype == RAD_U5 ? 5 : 0; + const int bits = ec->dtype == RAD_U4 ? 4 : ec->dtype == RAD_U5 ? 5 : ec->dtype == RAD_U6 ? 6 : 0; if (!bits || ec->kind != RAD_PLANE_TILED || ec->block[0] != 1 || ec->block[1] != 1 || et->kind != RAD_PLANE_TABLE || et->dtype != RAD_F32 || et->rows * et->cols != ((int64_t)1 << bits)) diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index c0bca2e8..bace7e35 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -2340,7 +2340,7 @@ int ref_unrelayout_gemm_q_m2(const RadParam*, int, int, const RadEncoding*, cons #define DT_FLOAT "bf16 f16 f32 fp8_e4m3 fp8_e5m2 i8 i32, chosen per operand from its own dtype" #define DT_ANY "any dtype rad_types.h names, per operand" -#define DT_FLOAT_CB DT_FLOAT "; or u4 / u5 codes into an f32 table, joined (w4nl* / w5nl*)" +#define DT_FLOAT_CB DT_FLOAT "; or u4 / u5 / u6 codes into an f32 table, joined (w4nl* / w5nl* / w6nl*)" static const RadKernelInfo kKernels[] = { SIMPLE("ref_rmsnorm", "rmsnorm", "norm", "root-mean-square norm with a gain", DT_FLOAT, diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 2db2b433..f88b1b70 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -2117,7 +2117,7 @@ static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) { if (is("fp8a8") || is("fp8a8f32")) return { g, g }; if (is("mxfp4a8")) return { 1, 32 }; if (is("w4a8") || is("w4a8h") || is("w4nla8h")) return { 1, g }; - if (is("w4nl64a8h") || is("w5nl64a8h")) return { 1, g / 2 }; + if (is("w4nl64a8h") || is("w5nl64a8h") || is("w6nl64a8h")) return { 1, g / 2 }; if (is("w4nl32a8h")) return { 1, g / 4 }; if (is("i8a8") || is("i8a8h") || is("w4a8i8") || is("w4a8i8h")) return { 1, g }; if (is("w4nl64a8i8h")) return { 1, g / 2 }; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index cfd253ac..39347d62 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -2663,12 +2663,24 @@ TEST(flashnext_trellis_gate_and_w5nl_down_use_separate_activation_formats) { rad_enc_copy_str(r8.transform, "fwht128"); REQUIRE(rad_enc_valid(&r8)); + for (int gate_bits : { 4, 5 }) for (int down_bits : { 5, 6 }) { + RadEncoding gateq = tq, downq = w5; + gateq.plane[0].dtype = gate_bits == 4 ? RAD_U4 : RAD_U5; + downq.plane[0].dtype = down_bits == 5 ? RAD_U5 : RAD_U6; + downq.plane[3].extent[1] = 1 << down_bits; + REQUIRE(rad_enc_valid(&gateq)); + REQUIRE(rad_enc_valid(&downq)); for (int rank = 0; rank < 2; ++rank) { RadModelMeta meta = qwen4exp_meta(); RadBuildCtx c = build_ctx(rank, 2); c.max_tok = 64; c.max_seqs = 2; c.max_spec = 0; c.max_ctx = 4096; RadBuilder b; - b.encs = { { "ffn_gate_up_exps", tq }, { "ffn_down_exps", w5 }, + const RadEncoding plain = rad_enc_plain(RAD_BF16); + b.encs = { { "blk.1.ffn_gate_up_exps.3.weight", plain }, + { "blk.1.ffn_down_exps.3.weight", plain }, + { "blk.1.ffn_gate_up_exps.10.weight", plain }, + { "blk.1.ffn_down_exps.10.weight", plain }, + { "ffn_gate_up_exps", gateq }, { "ffn_down_exps", downq }, { "ssm_inz.weight", tq }, { "attn_qg.weight", tq } }; for (const char* name : { "qsa_qk.weight", "attn_k.weight", "attn_v.weight", "attn_output.weight", "ssm_out.weight", @@ -2678,7 +2690,10 @@ TEST(flashnext_trellis_gate_and_w5nl_down_use_separate_activation_formats) { const auto& m = qwen4exp_fp8::g_model[rank]; const auto& moe = m.layers[0].mlp; CHECK_EQ(moe.fmt[0], 11); - CHECK_EQ(moe.fmt[1], 7); + CHECK_EQ(moe.fmt[1], down_bits == 5 ? 7 : 12); + CHECK_EQ(m.layers[1].mlp.prot.size(), (size_t)2); + CHECK_EQ(m.layers[1].mlp.fmt[0], 11); + CHECK_EQ(m.layers[1].mlp.fmt[1], down_bits == 5 ? 7 : 12); CHECK(m.a_eff.q && m.a_eff.s && m.a_eff.q8 && m.a_eff.s8); CHECK_EQ(moe.gq_exp.a.cq(), m.a_eff.q); CHECK_EQ(moe.gq_exp.a.cs(), m.a_eff.s); @@ -2691,7 +2706,8 @@ TEST(flashnext_trellis_gate_and_w5nl_down_use_separate_activation_formats) { CHECK_EQ(down->reads[0], m.a_eff.q); bool gate_i8 = false, down_w5 = false; for (const auto& p : gate->p) gate_i8 |= p.key == "dtype" && p.sval == "i8a8h"; - for (const auto& p : down->p) down_w5 |= p.key == "dtype" && p.sval == "w5nl64a8h"; + for (const auto& p : down->p) + down_w5 |= p.key == "dtype" && p.sval == (down_bits == 5 ? "w5nl64a8h" : "w6nl64a8h"); CHECK(gate_i8); CHECK(down_w5); @@ -2724,6 +2740,7 @@ TEST(flashnext_trellis_gate_and_w5nl_down_use_separate_activation_formats) { CHECK_EQ(dn_issue->opd[1].offset, quant_issue->opd[2].offset); CHECK(gu_issue->opd[0].handle != quant_issue->opd[1].handle); } + } } /* The MTP-only expert tap must see history rows even in chunks that would ordinarily diff --git a/tests/quant_test.cpp b/tests/quant_test.cpp index a945ac07..49046b2b 100644 --- a/tests/quant_test.cpp +++ b/tests/quant_test.cpp @@ -282,6 +282,39 @@ TEST(gptq_with_a_hessian_lowers_the_output_error) { CHECK(gc.planes[1] == g.planes[1]); } +TEST(w6nl_gptq_and_coordinate_descent_accept_bf16_domain_hessians) { + NEED_LIBQUANT(); + const int64_t R = 16, C = 128, T = 4096; + std::vector h((size_t)(C * C), (float)T * 0.25f); + for (int64_t i = 0; i < C; ++i) h[(size_t)(i * C + i)] += (float)T; + const TempDir td("rad_w6nl_gptq"); + REQUIRE(!td.path.empty()); + REQUIRE(write_gram(td.path + "/gram.r0.blk.3.ffn_down_exps.bin", C, T, h)); + Opts o; + o.s("table", "w6nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32") + .s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128") + .s("rule", "search").i("cd", 3).s("calib", td.path.c_str()); + const std::vector w = draw(R * C, 770, 1.0f); + const Quantised q = quantise(quantizer("gptq"), o, "blk.3.ffn_down_exps.17.weight", R, C, w); + REQUIRE_EQ(q.status, RAD_OK); + CHECK_EQ(q.enc.plane[0].dtype, (uint32_t)RAD_U6); + CHECK_EQ(q.planes[0].size(), (size_t)(R * C * 6 / 8)); + CHECK_EQ(q.enc.plane[3].extent[1], 64LL); + for (int i = 0; i < 64; ++i) { + float value = 0.0f; + std::memcpy(&value, q.planes[3].data() + i * sizeof(float), sizeof value); + const uint8_t fp8 = rad_f32_to_fp8e4m3(value); + CHECK_EQ(rad_load_f32(&fp8, RAD_F8E4M3, 0), value); + if (i >= 32) { + float positive = 0.0f; + std::memcpy(&positive, q.planes[3].data() + (i - 32) * sizeof(float), sizeof positive); + CHECK_EQ(value, -positive); + } + } + const std::vector decoded = decode(q, R, C); + CHECK(rel_err(w, decoded) < 0.2); +} + /* ------------------------------------------------------------------ recipes, compiled * * A rule's options are typed by its quantiser's own table before declare runs, so a misspelt key or @@ -337,7 +370,10 @@ TEST(every_shipped_recipe_compiles_and_its_grids_are_accepted) { REQUIRE(!calib.path.empty()); const char* old = std::getenv("CALIB"); const std::string saved = old ? old : ""; + const char* old_mtp = std::getenv("MTP_CALIB"); + const std::string saved_mtp = old_mtp ? old_mtp : ""; setenv("CALIB", calib.path.c_str(), 1); + setenv("MTP_CALIB", calib.path.c_str(), 1); int files = 0, rules = 0; std::error_code ec; @@ -391,6 +427,7 @@ TEST(every_shipped_recipe_compiles_and_its_grids_are_accepted) { CHECK(rules >= 250); std::filesystem::current_path(cwd, ec); if (old) setenv("CALIB", saved.c_str(), 1); else unsetenv("CALIB"); + if (old_mtp) setenv("MTP_CALIB", saved_mtp.c_str(), 1); else unsetenv("MTP_CALIB"); } /* ------------------------------------------------------------------ GPTQ against the textbook @@ -660,6 +697,7 @@ TEST(round_to_nearest_stores_the_nearest_code_on_every_grid) { "table=iq4nl,group=32,scale=f16", "table=w4nl,group=128,scale=bf16,transform=fwht128", "table=w5nl,group=64,scale=fp8_e4m3,scale2=f32", + "table=w6nl,group=64,scale=fp8_e4m3,scale2=f32,transform=fwht128,rule=search", "table=binary,group=32,scale=f16,rule=search", "table=ternary,group=32,scale=bf16", "table=-1.5;-0.25;0;0.5;2,group=32,scale=f32", diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 36cd6620..5f821093 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -4907,12 +4907,66 @@ TEST(op_moe_gemm_q_mod4) { * (w4nl64a8h/w5nl64a8h) or 32 (w4nl32a8h). The oracle inverts a relaid weight into exactly this * description (core/runtime/oracle.cpp). The final case is one last-class expert at K = 128 whose * 64-wide halves scale by 2 and 3 under one 0.5 activation scale; any other grid reads differently. */ +TEST(op_moe_gemm_q_reads_six_bit_codebook_experts) { + constexpr int64_t N = 2, K = 128; + T codes0(RAD_U6, {N, K}), codes1(RAD_U6, {N, K}); + T table(RAD_F32, {1, 64}), scale(RAD_F8E4M3, {N, 2}), level(RAD_F32, {1, 1}); + std::vector levels(64); + for (int c = 0; c < 64; ++c) levels[(size_t)c] = c < 32 ? (float)(c + 1) : (float)(31 - c); + table.f(levels); scale.f({ 1, 2, 2, 1 }); level.f({ 0.5f }); + for (int64_t n = 0; n < N; ++n) for (int64_t k = 0; k < K; ++k) { + const int base = (int)((k % 32 + (k / 64) * 32 + n * 5) % 64); + rad_store_code(codes0.mem.data() + n * (K * 6 / 8), RAD_U6, k, base); + rad_store_code(codes1.mem.data() + n * (K * 6 / 8), RAD_U6, k, (base + 3) % 64); + } + RadEncoding enc{}; + rad_enc_clear(&enc); + rad_enc_copy_str(enc.scheme, "affine"); + rad_enc_copy_str(enc.transform, "fwht128"); + rad_enc_add_plane(&enc, "codes", RAD_U6, 1, 1); + rad_enc_add_plane(&enc, "scale", RAD_F8E4M3, 1, 64); + rad_enc_add_plane(&enc, "scale.1", RAD_F32, 0, 0); + rad_enc_add_table(&enc, "table", RAD_F32, 1, 64); + const int cs[] = { 0, 3 }, ss[] = { 1, 2 }; + RadTensor cp0[] = { codes0.t, table.t }, cp1[] = { codes1.t, table.t }, sp[] = { scale.t, level.t }; + RadLayout cl{}, sl{}; + REQUIRE_EQ(rad_planes_layout(&enc, cs, cp0, 2, &cl), RAD_OK); + REQUIRE_EQ(rad_planes_layout(&enc, ss, sp, 2, &sl), RAD_OK); + std::vector even((size_t)cl.bytes), odd((size_t)cl.bytes), scales((size_t)sl.bytes); + REQUIRE_EQ(rad_planes_relayout(&enc, cs, cp0, 2, even.data(), cl.bytes), RAD_OK); + REQUIRE_EQ(rad_planes_relayout(&enc, cs, cp1, 2, odd.data(), cl.bytes), RAD_OK); + REQUIRE_EQ(rad_planes_relayout(&enc, ss, sp, 2, scales.data(), sl.bytes), RAD_OK); + T input(RAD_F32, {2, K}), as(RAD_F32, {2, 1}), sorted(RAD_I32, {2}); + T off(RAD_I32, {3}), out(RAD_F32, {2, N}); + T w0(RAD_U6, {1, N, K}), w1(RAD_U6, {1, N, K}); + T s0(RAD_F8E4M3, {1, N, K}), s1(RAD_F8E4M3, {1, N, K}); + input.f(std::vector((size_t)(2 * K), 1.0f)); as.f({1, 1}); + sorted.n({0, 1}); off.n({0, 1, 2}); + A a; + a.t(input).t(as).t(w0).t(s0).t(sorted).t(off).t(w1).t(s1).t(out) + .i("M", 2).i("N", N).i("K", K).i("n_expert", 2).i("top_k", 1).i("group", 128) + .s("a_order", "token").s("dtype", "w6nl64a8h"); + void* p0[] = { even.data() }, *p1[] = { odd.data() }, *ps[] = { scales.data() }; + a.ts[2].data = p0; a.ts[3].data = ps; a.ts[6].data = p1; a.ts[7].data = ps; + for (int i : { 2, 3, 6, 7 }) a.ts[(size_t)i].stride[0] = 0; + REQUIRE_EQ(run("moe_gemm_q", a), RAD_OK); + for (int e = 0; e < 2; ++e) for (int n = 0; n < N; ++n) { + float want = 0; + for (int k = 0; k < K; ++k) { + const int code = ((k % 32 + (k / 64) * 32 + n * 5) + e * 3) % 64; + const float subscale = n == 0 ? (k < 64 ? 1.0f : 2.0f) : (k < 64 ? 2.0f : 1.0f); + want += levels[(size_t)code] * subscale * 0.5f; + } + CHECK_EQ(out.at(e * N + n), want); + } +} + TEST(op_moe_gemm_q_scale_grid_by_dtype) { struct Want { const char* dt; int64_t rows, cols; }; /* N 256, K 512, group 128; the last class at N 128, K 256. */ const Want wants[] = { { "fp8a8", 2, 4 }, { "w4a8", 256, 4 }, { "w4a8h", 256, 4 }, { "w4nla8h", 256, 4 }, { "w4nl64a8h", 256, 8 }, { "w5nl64a8h", 256, 8 }, - { "w4nl32a8h", 256, 16 }, { "mxfp4a8", 256, 16 } }; + { "w6nl64a8h", 256, 8 }, { "w4nl32a8h", 256, 16 }, { "mxfp4a8", 256, 16 } }; for (const char* op : { "moe_gemm_q", "moe_gemm_q_mod4" }) { const RadKernelInfo* k = kern(op); REQUIRE(k != nullptr && k->opd_shape != nullptr); diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index e22b5c19..7e8f980f 100644 --- a/tests/relayout_parity_test.cpp +++ b/tests/relayout_parity_test.cpp @@ -687,11 +687,68 @@ std::vector moe_formats() { { "w4nl64a8h", nl("w4nl", 64), { "codes", "table" }, { "scale", "scale.1" } }, { "w4nl32a8h", nl("w4nl", 32), { "codes", "table" }, { "scale", "scale.1" } }, { "w5nl64a8h", nl("w5nl", 64), { "codes", "table" }, { "scale", "scale.1" } }, + { "w6nl64a8h", nl("w6nl", 64), { "codes", "table" }, { "scale", "scale.1" } }, }; } } /* namespace */ +TEST(w6nl_all_codes_have_independent_bit_planes_and_round_trip) { + NEED_LIBQUANT(); + constexpr int64_t N = 64, K = 256; + Opts qopt; + qopt.s("table", "w6nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32") + .s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128"); + Quantised q = quantise(quantizer("rtn"), qopt, "blk.0.ffn_down_exps.0.weight", N, K, + draw(N * K, 187, 1.0f)); + REQUIRE_EQ(q.status, RAD_OK); + REQUIRE_EQ(q.enc.plane[0].dtype, (uint32_t)RAD_U6); + const int64_t row = rad_enc_row_bytes(RAD_U6, K); + for (int64_t n = 0; n < N; ++n) + for (int64_t k = 0; k < K; ++k) + rad_store_code(q.planes[0].data() + n * row, RAD_U6, k, (int)((k + n * 17) % 64)); + Opts kp; + kp.i("N", N).i("K", K).i("group", 128).s("dtype", "w6nl64a8h"); + Selection s = select(q, N, K, { "codes", "table" }); + RadLayout L{}; + REQUIRE_EQ(nMoeW4.layout(kp.data(), kp.n(), B, &q.enc, s.sel.data(), s.t.data(), 2, &L), RAD_OK); + REQUIRE_EQ(L.bytes, N * K * 6 / 8); + std::vector packed((size_t)L.bytes); + REQUIRE_EQ(nMoeW4.relayout(kp.data(), kp.n(), B, &q.enc, s.sel.data(), s.t.data(), 2, + packed.data(), L.bytes), RAD_OK); + for (int64_t n = 0; n < N; ++n) for (int64_t k = 0; k < K; ++k) { + const uint8_t* r = packed.data() + n * K * 6 / 8; + const int want = (int)((k + n * 17) % 64); + const int lo = (r[(k / 8) * 4 + k % 4] >> ((k % 8 / 4) * 4)) & 15; + uint32_t h = 0, sign = 0; + std::memcpy(&h, r + K / 2 + (k / 32) * 4, 4); + std::memcpy(&sign, r + K / 2 + K / 8 + (k / 32) * 4, 4); + const uint32_t bit = 8u * (uint32_t)(k % 4) + 7u - (uint32_t)((k % 32) / 4); + CHECK_EQ(lo | (int)(((h >> bit) & 1u) << 4) | (int)(((sign >> bit) & 1u) << 5), want); + } + std::vector> backbuf; + Selection back = select(q, N, K, { "codes", "table" }, &backbuf); + REQUIRE_EQ(nMoeW4.unrelayout(kp.data(), kp.n(), B, &q.enc, back.sel.data(), packed.data(), + L.bytes, back.t.data(), 2), RAD_OK); + CHECK(backbuf[0] == q.planes[0]); + CHECK(backbuf[1] == q.planes[(size_t)s.sel[1]]); + /* A table with the right shape but different values must never reach the hard-coded GPU LUT. */ + float bad = 0.0f; + std::memcpy(q.planes[(size_t)s.sel[1]].data(), &bad, sizeof bad); + s = select(q, N, K, { "codes", "table" }); + CHECK_EQ(nMoeW4.relayout(kp.data(), kp.n(), B, &q.enc, s.sel.data(), s.t.data(), 2, + packed.data(), L.bytes), RAD_E_DTYPE); + Selection scale = select(q, N, K, { "scale", "scale.1" }); + RadLayout LS{}; + REQUIRE_EQ(nMoeW4.layout(kp.data(), kp.n(), BSCALE, &q.enc, scale.sel.data(), scale.t.data(), 2, + &LS), RAD_OK); + std::vector scales((size_t)LS.bytes); + const float wrong_scale = 0x1p-12f; + std::memcpy(q.planes[(size_t)scale.sel[1]].data(), &wrong_scale, sizeof wrong_scale); + CHECK_EQ(nMoeW4.relayout(kp.data(), kp.n(), BSCALE, &q.enc, scale.sel.data(), scale.t.data(), 2, + scales.data(), LS.bytes), RAD_E_DTYPE); +} + /* The four-class hooks are the two-class hooks extended. moe_gemm_q_mod4's class q is operands 2/3 * at N/K for q = 0 and 2q+4/2q+5 at N_q/K_q after it, and each is stored and read back exactly as * moe_gemm_q's hooks store an expert of that geometry: codes and scales, in every four-bit format, diff --git a/tools/fit_w6nl.py b/tools/fit_w6nl.py new file mode 100644 index 00000000..78a07931 --- /dev/null +++ b/tools/fit_w6nl.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Fit a candidate W6NL E4M3-exact codebook without loading/serving a model. +Samples BF16 down-projection weight rows from safetensors in disjoint layer sets. +This is a weight-distribution pilot, not held-out activation-weighted GPTQ validation. +""" +import argparse, json, struct, pathlib +import numpy as np +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('checkpoint', type=pathlib.Path, help='original BF16 checkpoint directory') +ROOT = parser.parse_args().checkpoint +INDEX = json.loads((ROOT / 'model.safetensors.index.json').read_text())['weight_map'] + +def sample(layers, seed): + rng = np.random.default_rng(seed) + chunks = [] + for layer in layers: + name = f'model.language_model.layers.{layer}.mlp.experts.down_proj' + path = ROOT / INDEX[name] + with path.open('rb') as f: + n = struct.unpack('> 3, b & 7 + if exponent == 0: return mant * 2**-9 + return (1 + mant/8) * 2**(exponent-7) + +def score(h, vals, scale, x): + u = np.asarray(vals, dtype=np.float64)/scale + i = np.searchsorted((u[1:]+u[:-1])/2, x) + return float(np.sum(h*(x-u[i])**2)/h.sum()) + +def fit(h): + x=(np.arange(len(h))+.5)/len(h) + centers = np.linspace(0.01, 0.99, 32) + for _ in range(2500): + i=np.searchsorted((centers[1:]+centers[:-1])/2,x) + counts=np.bincount(i, weights=h, minlength=32) + sums=np.bincount(i, weights=h*x, minlength=32) + new=np.divide(sums, counts, out=centers.copy(), where=counts>0) + if np.max(np.abs(new-centers)) < 1e-9: break + centers=new + i=np.searchsorted((centers[1:]+centers[:-1])/2,x) + counts=np.bincount(i, weights=h, minlength=32) + vals=np.array([e4(b) for b in range(1,127)],dtype=np.float64) + best=None + for scale in np.arange(20.,80.01,.5): + # Find 32 strictly increasing, exactly representable positive fp8 levels. + cost=counts[:,None]*(centers[:,None]-vals[None,:]/scale)**2 + dp=cost[0].copy(); parents=[] + for j in range(1,32): + prev=np.r_[np.inf, dp[:-1]] + arg=np.minimum.accumulate(prev) + inds=np.empty(len(vals),np.int32); k=-1; m=np.inf + for z,p in enumerate(prev): + if p= scale * .98) & (vals <= scale * 1.02),dp,np.inf) + z=int(np.argmin(eligible)); chosen=[z] + for parent in reversed(parents): + z=int(parent[z]); chosen.append(z) + chosen=chosen[::-1] + if min(chosen)<0: continue + table=vals[chosen] + err=score(h,table,scale,x) + if best is None or err