Merge hugypufy/radiance m2xfp: M2XFP4 weights (upstream PR #203)

The M2XFP4 encoding (e2m1 codes, e8m0 per-32 scales, a u8 per-subgroup metadata plane, learned
Givens rotations): libref and libavx kernels, libr4d HIP kernels, the packer and the tests, as on
the branch (8 commits on 9eaf10d, radiance 1.11.0). Taken for Qwen3.8-27B-DFLASH2-PARO-M2XFP4,
the container used for testing and optimisation from now on; merged without conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-10-23 23:09:18 +02:00
commit d3609e585d
68 files changed
+4847 -193

No files matched your search

+92
View File
@@ -4390,3 +4390,95 @@ A sanitised replay of the whole fixture. Host code only -- see the note in the
- 0 report(s)
## The M2XFP4 GEMMs
Hand-written section, 2026-10-20, beside the generated report above. The M2
analogue of the OCP-MXFP4 x fp8 stack (arXiv 2601.19213 §4.4.2, the paper's
weight-side Sg-EM): two rows, `gemm_m2xfp4a8_decode` (M <= 128, the decode band)
and `gemm_m2xfp4a8_tiled` (prefill), at the quantiser-own encoding `m2xfp4` --
one more plane than MXFP4, everything else the OCP rows' plumbing.
**Encoding and decode.** Per group of 32 columns the weight carries the MXFP4
planes -- e2m1 codes and an E8M0 exponent whose adaptive bias b in {-1,0,1} the
quantiser already folded into the stored byte -- plus one meta byte holding four
two-bit subgroup multipliers, subgroup s covering columns [8s, 8s+8). The exact
weight is `e2m1mag[c&7] . sign(c) . 2^(scale-127) . (1 + k_s/4)`. The fold of the
OCP rows applies unchanged (`r4d_mxfp4.h`): `d = Wref[n] - E8M0[n][blk]` against
the row-maximum reference goes through a table, `2^(Wref[n]-127)` once in the
epilogue -- Wref is still the row's largest exponent byte, so d >= 0 holds for
every block, and the largest element any table cell then holds is the x1.75
magnitude 10.5 . 2^-d, an e4m3 normal at every d >= 0. `r4d_m2xfp4.h`'s
`kM2xfp4Mag[16][4][2]` is the mxfp4 table with the second index: its k = 0 rows
are `kMxfp4Mag` byte for byte; k = 1, 2 are exact wherever the product is normal;
k = 3 rounds the odd-mantissa magnitudes (1.5, 3, 6 land on the tie's even side,
2.5, 5, 10 scaled) -- at most 2^-4.4 relative on those elements, accepted here
because the CPU decode and the reference stay exact. The unpack is the same four
v_perm_b32 per eight weights, one table row [d][k_s].
**Memory organization.** The relayout (`r4d_layout.cpp`, m2xfp4) stores the codes
in the skinny kernels' WMMA fragment order and appends the meta plane to the same
stored blob in the exponent plane's [K/32][N] order and row pitch -- one byte per
(weight row, 32 of K), read beside the exponent byte with the staging geometry
the scales already use, so the weight stream grows by one byte per sixteen. The
weight operand takes the container's `codes` and `meta` planes; `bscale` and
`bref` are the OCP rows' own arrangements and derivations. Split-K, the
last-arriver reduction, the scratch contract, the concurrency promise (counters
keyed on the output) and the ks/bk/nt and tn tunables are the OCP rows', with
this row's own state.
**Coverage.** `r4d_emu_m2xfp4` holds the table to arithmetic over every
(d, k, magnitude) cell and the unpack to it over every code, then runs both
kernels against an f64 reference of the exact decode at the FP8 WMMA's tolerance
(both activation scale grids, a zero block, both K slabs, the one-fragment form
and the split law). `r4d_selftest --case gemm_m2xfp4a8_decode` (and `_tiled`)
runs the rows on the card through their own relayout, including parts and both
grids, at the tolerance above plus the k = 3 margin (4e-2 rel_l2).
The same encoding is served on the host by libref's and libavx's `gemm_nt_q`
m2 arms (the concatenated canonical planes; ref_gemm.cpp's gemm_m2), which the
row checker holds to the quantiser's own decode.
**Speed.** rad-kbench reaches the rows: `data/kernels_m2xfp4_m{1,8,16,128}.rkb`
are recorded from a skeleton of an m2xfp4 27B container (weights drawn from
seeds, one file a --max-tok pass, replayed together; the mx side comes from
`--record-rows` over the same cases, which re-encodes the weight between the
mx/m2 families -- tools/rad_kbench.cpp's reencode_gemmx_weight). The numbers
below are `--timing-only --report` cold medians, each launch reading its rotated
weights from memory, gfx1201:
| shape | M | mxfp4 us | m2 us | delta |
|---|---|---|---|---|
| N=1024 K=5120 | 1 | 11.3 | 13.3 | +17.5% |
| N=1024 K=5120 | 16 | 13.9 | 15.8 | +13.8% |
| N=1024 K=5120 | 128 | 44.3 | 44.7 | +0.8% |
| N=5120 K=6144 | 1 | 32.1 | 38.3 | +19.2% |
| N=5120 K=6144 | 16 | 34.1 | 40.2 | +17.9% |
| N=5120 K=6144 | 128 | 100.9 | 104.5 | +3.6% |
| N=5120 K=17408 | 1 | 78.5 | 86.7 | +10.5% |
| N=5120 K=17408 | 16 | 89.7 | 100.5 | +12.0% |
| N=5120 K=17408 | 128 | 211.2 | 222.8 | +5.5% |
| N=12288 K=5120 | 1 | 56.4 | 59.3 | +5.3% |
| N=12288 K=5120 | 128 | 113.8 | 124.7 | +9.6% |
| N=16384 K=5120 | 64 | 94.6 | 103.0 | +8.9% |
| N=16384 K=5120 | 128 | 156.8 | 169.1 | +7.8% |
| N=34816 K=5120 | 1 | 150.1 | 167.8 | +11.8% |
| N=34816 K=5120 | 16 | 157.1 | 173.8 | +10.7% |
| N=34816 K=5120 | 64 | 206.2 | 223.1 | +8.2% |
| N=34816 K=5120 | 128 | 354.7 | 370.5 | +4.4% |
An earlier harness that drove the row's own ABI launch with the meta plane as a
separate 5-6 MiB buffer measured +0.7-3.6% at M <= 16: that buffer sat warm in
L2, and in the engine -- and in a cold kbench pass, where the meta rides the
weight blob and rotates with it -- the M <= 16 premium is 5-19% instead. Past
the DTM 1 -> 2 band switch at M = 17 the extra byte hides again (0.4-10%); the
whole-M-ladder fixtures carry 1, 2, 4, 8, 9, 16, 18, 36, 64, 65, 128.
One tuning attempt was made at the M >= 64 points where the delta exceeds 8%:
staging the slab's exponent and meta bytes into LDS once (wide coalesced loads
replacing the duplicated scalar global reads the unpack loop makes). It was
reverted: the W-stage's paired-row store writes one row past sW for the last
row pair -- a latent out-of-bounds LDS store the original layout absorbed --
and beside newly staged LDS it corrupts the staged bytes; guarding that slot
changed the error without removing it, and the residual mismatch stayed
undiagnosed. The numbers above are the unmodified kernel.
+11 -2
View File
@@ -41,8 +41,9 @@ here is such a choice.
- Where an op takes `dtype`, it is a string naming the operand combination, so a weight format and
an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`, `u8`, `fp8_e4m3`,
`fp8a8`, `fp8a8f32`, `fp8a16`, `i8a8`, `i8a8h`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`,
`w4a16`, `w8a16`, `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`, and the
codebook expert forms `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` (`docs/MOE-W4.md`).
`w4a16`, `w8a16`, `w2a8`, `mxfp4a8`, `m2xfp4`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`,
and the codebook expert forms `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`
(`docs/MOE-W4.md`).
- `w4a8h` is `w4a8` with a `group`-wide Walsh–Hadamard along K baked into the stored weight
(`docs/MOE-W4.md`).
- `i8a8` is an i8 weight with a bf16 scale per (row, 128 of K) against an int8 activation on
@@ -714,6 +715,14 @@ At `i8a8` they are `quant_act_i8g`'s row-major codes and per-(row, 128 of K) sca
weight with a bf16 scale per (row, 128 of K); at `mxfp4a8`, `quant_act_fp8`'s pair against e2m1
codes with an E8M0 exponent per (row, 32 of K).
At `m2xfp4` -- the `m2xfp4` quantiser's own scheme, not an affine grid -- `b` is that scheme's
codes and meta planes concatenated as stored (the codes rows, then the meta rows; the form the
core's selection reader hands out, core/format/encoding.cpp) and `b_scale` the E8M0 plane as at
`mxfp4a8`. The exact element is `e2m1(code) . 2^(e-127) . (1 + k_s/4)`, `k_s` the meta byte's
two-bit field over subgroups of eight columns (libquant's `lq_m2xfp.cpp`); the host rows take the
weight's group at that eight and fold the multiplier into the scale stream, libr4d's rows fold it
into their staging table. `b_ref` is the mxfp4 grid's, accepted and ignored.
`a_sum` removes an asymmetric grid's zero point and `b_ref` is the per-row reference exponent an
MXFP4 kernel folds its block exponents against. `b_ref` is derived from `b_scale` and does not
change the product. Both host libraries accept `b_ref` beside an e2m1 weight and ignore it, and
+100 -8
View File
@@ -2,14 +2,15 @@
Every flag of every tool, with examples. Start with [GUIDE.md](GUIDE.md).
Six binaries and the `rad-export` script are installed beside `radiance`; the shell harnesses
live in `scripts/`:
Six binaries and the `rad-export` and `rad-pack-m2xfp4` scripts are installed beside `radiance`;
the shell harnesses live in `scripts/`:
| | |
|---|---|
| [`rad-info`](#rad-info) | print what a `.rad` container holds. Loads no plugins |
| [`rad-convert`](#rad-convert) | safetensors or GGUF in, `.rad` out, quantised by a recipe |
| [`rad-export`](#rad-export) | a finetune (merged checkpoint or LoRA adapter) to a `.rad`, with the base model's own recipe |
| [`rad-pack-m2xfp4`](#rad-pack-m2xfp4) | a ParoQuant M2XFP4 fine-tune to a `.rad`, its packed planes imported rather than re-quantised |
| [`rad-kbench`](#rad-kbench) | correctness, completeness and speed of every kernel library |
| [`rad-tune`](#rad-tune) | benchmark each kernel's tunable space at this model's shapes, on this machine |
| [`rad-schemas`](#rad-schemas) | print and diff the op schemas plugins declare |
@@ -167,6 +168,14 @@ output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf1
blk.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
```
A checkpoint whose `quantization_config` names a form rad-convert imports (a ParoQuant release at
`int5-bitplane`, AWQ int4, MXFP4 or M2XFP4, Quark's MXFP4, GPTQ/`auto-round`, compressed-tensors'
int4, NVFP4, ModelOpt) is written plane by plane instead: the codes, scales and metadata bytes as
they ship, the learned rotations as the encoding's `givens` tables, nothing dequantised or
re-quantised. Those weights need no rule -- a rule that matches one would ask a quantiser to read
codes as floats, and is refused -- so a recipe beside them covers only what the checkpoint does
not ship in a form the architecture declares.
A pattern is a glob over the whole name: `*` crosses dots, `?` is one character. `$NAME` (or
`${NAME}`) in an option is taken from the environment; an unset variable is refused. `--quant`
adds rules ahead of the file's:
@@ -185,10 +194,11 @@ also matches a norm leaves the norm as it is.
| `autoround` | sign-gradient descent on a rounding offset per value and a range factor per block, against the Hessian; `iters` steps of N·K² multiply-adds each |
| `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform |
| `ggml` | `type=` one of llama.cpp's formats (q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m), chosen by llama.cpp's own search, imatrix-weighted; the codes are byte for byte llama.cpp's, stored as each type's affine planes. iq2_xxs, iq2_xs and iq1_s need `--imatrix` |
| `m2xfp4` | M2XFP: MXFP4 whose group of 32 also carries one metadata byte of four 2-bit subgroup extra mantissas, each a subgroup of 8 columns refining the shared exponent to (1 + k/4) . 2^E; the subgroups' k and the exponent's bias in {-1, 0, 1} (`adaptive=1`, the default; `adaptive=0` pins the bias at 0) are the least squared error choices, the OCP exponent rule, rounding, zero groups and short final groups otherwise the MXFP4 grid's; 4.5 bits an element, weights only, decoded by the quantiser itself (arXiv 2601.19213) |
| `cast` | a float weight in another float dtype (`dtype=` f32, bf16, f16, fp8_e4m3, fp8_e5m2), no scale |
| `import` | rad-convert's own, not a plugin: the numbers a quantised release ships, in the spelling the kernels read, instead of quantising again. `codes=uN` makes a symmetric grid's signed codes unsigned under a zero point of 2^(N-1); `zero=` is the zero plane's dtype (u4, u8); `scale=` the scale's (f16, bf16, f32), each shipped scale rounded to nearest; `block=RxC` repeats an FP8 scale shipped per row or per tensor over that block grid. It reads an imported integer grid (GPTQ, CT-INT4) or an FP8 weight with a scale per row or per tensor, refuses any other quantised form by name, and keeps a plain float weight as it is. The run reports per rule how many weights it re-expressed and how many scales the new dtype rounded |
Every quantiser except `ggml`, `cast` and `import` takes the grid options:
Every quantiser except `ggml`, `m2xfp4`, `cast` and `import` takes the grid options:
| option | |
|---|---|
@@ -204,7 +214,8 @@ Every quantiser except `ggml`, `cast` and `import` takes the grid options:
| `clamp` | a signed code's range, `full` or `sym` |
Examples: MXFP4 is `codes=fp4_e2m1 group=32 scale=e8m0`; NVFP4 is `codes=fp4_e2m1 group=16
scale=fp8_e4m3 scale2=f32`; NF4 is `table=nf4 group=64`; a K-quant-like grid is `codes=i4
scale=fp8_e4m3 scale2=f32`; its metadata-augmented cousin is the `m2xfp4` quantiser itself; NF4 is
`table=nf4 group=64`; a K-quant-like grid is `codes=i4
group=32 scale=u6 scale2=f16 group2=256`; a ternary BitNet weight is `table=ternary`.
A container can hold only what some kernel reads. The converter checks every planned encoding
@@ -388,6 +399,84 @@ is `UNSLOTH_HOOK_OUTPUT=<path of the .rad>`, which a trainer UI can list with th
---
## rad-pack-m2xfp4
```
rad-pack-m2xfp4 SRC [-o OUT.rad] [--recipe FILE] [--draft DIR] [--rad-convert PATH]
[--home DIR] [--jobs N] [--convert-with 'CMD {model} {result_dir} {out}']
[--model BASE] [--hf-out DIR] [--convert-path FROM=TO ...]
[--verify-only] [--list] [--skip-tables]
SRC a converted ParoQuant M2XFP4 checkpoint, or a `paroquant.cli.optimize`
result directory (quant_grid.json + per-module .pt)
-o, --out FILE the container (default: SRC's folder name + .rad, beside SRC)
--convert-with C run `paroquant.cli.convert --mode real` through C first, with {model}
{result_dir} {out} substituted; a result directory needs it and --model
--model BASE the donor checkpoint convert loads (the fine-tune's weights are in the
result directory, not in BASE)
--hf-out DIR where --convert-with writes (default: SRC/hf), as this machine sees it
--convert-path FROM=TO a prefix the convert runtime spells differently (docker exec of a
container whose /models is this machine's ~/models), applied to {model},
{result_dir} and {out}. Repeatable
--recipe FILE rad-convert's recipe for the weights the checkpoint does not ship quantised
(data/recipes/q38-27b-paro-m2xfp4-df2.recipe)
--draft DIR a drafter merged as dflash.*
--verify-only skip rad-convert and check the container at -o against the checkpoint
--list print the container's m2xfp4 entries and stop
--skip-tables check the three code planes only, not the rotation tables
```
A ParoQuant M2XFP4 fine-tune is a set of `paroquant.cli.optimize` per-module files: trained
weights, the learned rotation and the grid's exponent bias, not packed planes. Two steps turn it
into a container, and this script owns the seam:
1. `paroquant.cli.convert --mode real` re-derives each module's codes under the M2XFP4 grid the
optimizer trained with and writes an ordinary Hugging Face checkpoint: `X.weight` (e2m1
nibbles `[N, K/2]`), `X.weight_scale` (e8m0 `[N, K/32]`), `X.weight_meta` (u8 `[N, K/32]`, four
2-bit subgroup multipliers a byte) and the rotation (`X.theta`, `X.pairs`, `X.channel_scales`),
with `quantization_config.quant_method = "paroquant_m2xfp4"`. It needs a GPU; the script runs it
when it is handed a result directory and `--convert-with`.
2. `rad-convert` imports those planes -- `Import::ParoM2` in core/format/checkpoint.cpp: the codes,
exponents and metadata bytes become the weight's three planes byte for byte, the rotation
becomes the encoding's `givens` tables, and the GEMM is the plain M2XFP4 one over an activation
`givens_dense_quant` rotates first. It is CPU-only, so it runs beside a serving GPU.
Then it reads the container back and proves the seam: every `m2xfp4` entry's three planes are
byte-identical to its checkpoint tensors, and the rotation tables are the checkpoint's
(`t.scale` = 1/channel_scales in f32, `t.pairs` offset to whole-row columns, `t.angle` widened,
`t.dense` the stages composed over groups of 128 in f64 and rounded once).
A mismatch exits non-zero; it is not a warning. Loading the container also deserves
`rad-kbench -m`: its cases run over the container's own bytes in the layout the kernel asked for.
```bash
# the full model, once the fine-tune lands (convert needs a GPU; the rest does not). The
# container's mounts are spelled differently from this machine's; -u keeps the checkpoint's files
# this user's, and every path the script hands it is translated by --convert-path.
rad-pack-m2xfp4 /media/zee/ai/paro-out-ft-m2xfp4/Qwen3.8-27B-fp16 \
--model /media/zee/ai/paro-stage/Qwen3.8-27B-fp16 \
--convert-with 'docker exec -u 1000:1000 paro_stage2 python3 -m paroquant.cli.convert \
--model {model} --result-dir {result_dir} --output-path {out} --mode real' \
--convert-path /media/zee/ai/paro-out-ft-m2xfp4=/out \
--convert-path /media/zee/ai/paro-stage=/staging \
--convert-path /home/zee/models=/models \
--hf-out /home/zee/models/paro-ft-m2xfp4-hf --draft /home/zee/models/hf/Qwen3.8-27B-DFlash2 \
--recipe data/recipes/q38-27b-paro-m2xfp4-df2.recipe \
-o /home/zee/models/rad/q38-27b-paro-m2xfp4.rad
# and the pack alone, from the checkpoint the convert left, plus its check
rad-pack-m2xfp4 /home/zee/models/paro-ft-m2xfp4-hf \
-o /home/zee/models/rad/q38-27b-paro-m2xfp4.rad \
--recipe data/recipes/q38-27b-paro-m2xfp4-df2.recipe --draft /home/zee/models/hf/Qwen3.8-27B-DFlash2
rad-pack-m2xfp4 --list -o /home/zee/models/rad/q38-27b-paro-m2xfp4.rad
```
The recipe (`data/recipes/q38-27b-paro-m2xfp4-df2.recipe`) covers what the checkpoint does not ship
in a form the architecture declares -- f32 norm casts, the bf16 embedding, the head, the drafter's
own linears -- and names no trunk linear, which are imported. The alternative shortcut, `convert
--mode pseudo` (dequantised fp16 weights) then a `m2xfp4` recipe rule, re-quantises every weight in
the unrotated basis: it needs no import, but it is a second lossy step and its planes are not the
fine-tune's.
## rad-kbench
Checks every kernel every loaded library supplies against the reference library's answers,
@@ -467,10 +556,13 @@ on an eighth of the rows.
`--rerecord FILE` writes the replayed fixtures' cases again with the reference's current answers
in the current format, each case keeping the laws it was recorded with. `--record-rows FILE`
moves the fixtures' cases into the constraints of every row of the libraries under test (another
band, tuned point or dtype) and records the reference there, described afresh: a fixture that
reaches rows no container selects, to replay with `--all-rows`. A row whose geometry would change
a weight's shape needs a container, and is listed.
moves the fixtures' cases into the constraints of every row of the libraries under test and
records the reference at every distinct geometry that lands there -- one case serves every row
sharing it, so a band's whole M ladder is covered -- described afresh: a fixture that reaches
rows no container selects, to replay with `--all-rows`. The gemm_nt_q mx/m2 pair re-encodes
between the two families (codes and exponents are the same planes; the meta plane is drawn
beside them), so an m2xfp4 recording can drive the OCP rows and vice versa. A row whose
geometry would change a weight's shape needs a container, and is listed.
### Verdicts