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

+1
View File
@@ -6,3 +6,4 @@ compile_commands.json
/sync-jarvis.sh
__pycache__/
.cache/
/paper/
+23
View File
@@ -240,6 +240,24 @@ endforeach()
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/LICENSE.qwen-community-1.0.txt
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME qwen-community.LICENSE)
# The M2XFP4 rows at the 27B trunk's own geometries: no in-tree container carries the encoding,
# so this is recorded from a skeleton of an m2xfp4 conversion (weights drawn from seeds) at the
# band edges a max-tok pass lands on -- one file a pass, replayed together. Re-record with
#
# rad-kbench -m <m2-container.rad> --max-cases 1 --max-tok <1|8|16|128> \
# --record data/kernels_m2xfp4_m<tok>.rkb
#
set(RAD_M2XFP4_FIXTURES "")
foreach(tok 1 8 16 128)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_m2xfp4_m${tok}.rkb)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_m2xfp4_m${tok}.rkb
${RAD_PLUGIN_OUT}/kernels_m2xfp4_m${tok}.rkb COPYONLY)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_m2xfp4_m${tok}.rkb
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
list(APPEND RAD_M2XFP4_FIXTURES ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m${tok}.rkb)
endif()
endforeach()
# The downloader behind `radiance --model <owner/name>` (core/hf_model.cpp). The engine looks in
# <bin>/../libexec/radiance/, so the build tree mirrors that layout.
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
@@ -254,6 +272,11 @@ install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/tools/rad-export
DESTINATION ${CMAKE_INSTALL_BINDIR})
# rad-pack-m2xfp4 (a ParoQuant M2XFP4 fine-tune to a .rad, through the import) drives rad-convert
# and checks its output; it is Python, like rad-export.
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/tools/rad_pack_m2xfp4.py
DESTINATION ${CMAKE_INSTALL_BINDIR} RENAME rad-pack-m2xfp4)
# rad_add_plugin() and rad_hipify(), shared with the installed package config. The variables it
# expects are all set above.
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/RadAddPlugin.cmake)
+57
View File
@@ -0,0 +1,57 @@
# M2XFP ("MXFP4v2") on radiance — work record + resume runbook
_Updated: 2026-10-23 09:00 — PROJECT COMPLETE. Winner: FT-SEED1 (KL mean 0.02107, −39.4 % vs RTN; top-1 94.15 %; GSM8K 94.0 %). Results dashboard: /home/zee/models/rad/m2xfp4-results.html._
## FINAL RESULTS (2026-10-23)
| Lane | KL mean | median | top-1 | PPL | GSM8K | Verdict |
|---|---|---|---|---|---|---|
| **SEED1 (seed 1, fold=kernel)** | **0.02107** | 0.00630 | 94.15 % | 7.6569 | **94.0 %** | **WINNER** — container `/media/zee/ai/radiance/containers/q38-27b-m2xfp4-ft-SEED1.rad` |
| MAIN (seed 0, fold=kernel) | 0.02194 | 0.00652 | 94.17 % | 7.6435 | — | keeper |
| EXACT (seed 0, fold=exact) | 0.02203 | 0.00696 | 94.01 % | 7.6814 | — | fold=exact bought nothing |
Baselines: RTN 0.0348 / AWQ 0.0599 / old MXFP4 grid 0.0754. Winner serve: depth-7 DFlash2 drafter, 83 tok/s single-stream (+29 % vs RTN), GSM8K 94.0 % with speculation active. Winner KL/GSM8K artifacts: kld-SEED1-vs-bf16.json, gsm8k-m2xfp4-ft-seed1.json.
Fixed en route (committed 2a7d5c3): packer verifier now accepts rule-quantized drafter planes (plain transform) and fused row-joins (ffn_gate_up/ssm_inz) — all containers proven byte-exact. KL scoring needs `--host-pool-mib 10240 --max-num-seqs 1 --max-model-len 40000` (the df2 container + default serve sizing OOMs one card; m2xfp4's per-piece rotations cannot be TP-split, so single-GPU only). hip4 (50:00) is runtime-invisible to host processes since ~08:00 (docker sees it fine) — do not schedule there; it needs a reboot, and the box must not be rebooted.
## RESUME AFTER BOOT (in order) — v2, crash-aware
```bash
cd /home/zee/code/llm && task stop-llama-swap # cold-starts vLLM onto GPUs at boot
docker rm -f paro_s2_MAIN paro_s2_EXACT paro_s2_SEED1 2>/dev/null
mkdir -p /tmp/night # /tmp is tmpfs — tooling must be recreated after every boot
cd /home/zee/code/vllm/ggz14/paroquant
# launch STAGGERED (90s apart — simultaneous 52G mmaps storm amdgpu SVM):
**hip2 = 0000:2c:00.0 is the newest R9700 — prefer it for the heaviest training/compute lanes. AMENDED 2026-10-23 00:40 (user): 0000:03:00.0 (trx pcie 1, hip0) is the LAST to use.** Order: hip2 (2c) → hip1 (27) → hip0 (03) → hip3 (50).
# (+90s) same + PARO_HIP_VISIBLE=1 M2XFP4_FOLD=exact PARO_NAME=paro_s2_EXACT FT_RESULTS=/media/zee/ai/paro-out-ft-m2xfp4-exact OUT=Qwen3.8-27B-PARO-M2XFP4-FT-EXACT > /tmp/ft-EXACT.log
# (+180s) same + PARO_HIP_VISIBLE=2 PARO_SEED=1 PARO_NAME=paro_s2_SEED1 FT_RESULTS=/media/zee/ai/paro-out-ft-m2xfp4-seed1 OUT=Qwen3.8-27B-PARO-M2XFP4-FT-SEED1 > /tmp/ft-SEED1.log
# watchdogs: recreate /tmp/night/watch-lane.sh (frozen-progress, phase-aware) + lanes.tsv; run one per lane
```
Watch: `watch -n 10 -c /tmp/ft-live.sh` (files %, bar, ETA, tripwire count, RAM).
## CRASH 2026-10-22 14:24 — amdgpu SVM workqueue lockup
Hard freeze, no OOM (0 hits), no GPU reset, no clean shutdown. Last kernel line: `workqueue: svm_range_restore_work [amdgpu] hogged CPU for >10000us 19 times`. Trigger: 3 concurrent torch FT processes (52 G mmap each) on the now-5-GPU box + a 4th radiance process probing devices. Mitigations in force: staggered lane starts; NO host radiance serve while lanes run (converts/serves go through docker with an explicit HIP pin); no 52 G pre-fault `cat`; kernel tripwire armed on `svm_range_restore_work|soft lockup`. If it recurs: drop to 2 lanes (SEED1 is the sacrificial one — MAIN + EXACT carry the quality story).
## GPU PREFERENCE (user, 2026-10-22 20:55)
**hip2 = 0000:2c:00.0 is the newest R9700 — prefer it for the heaviest training/compute lanes** on any future cold start or lane restart (current run keeps its placement mid-flight; a move re-pays ~1 h capture+replay). Order for new lanes: hip2 first, then hip1, then hip0. hip3 = W6600, never; 50:00 off-limits (runtime-invisible).
## ROOT CAUSES FOUND TODAY (all evidence-backed — do not re-litigate)
1. **GPU wedges → driver resets** = LACT **−100 mV undervolt** under sustained load. Fixed by user at 11:00 (all R9700s 0 offset / 0 clock offset / 250 W). Zero resets since, across 3 concurrent FTs. **Do not re-undervolt while training.**
2. Rotation kernel is innocent: 2,597,710 isolated calls / 45 min / zero wedges (donor tensors, real shapes).
3. Fixed red herrings (real bugs, not the wedge): stale root-owned JIT cache (`docker run --rm -v /home/zee/.cache/paroquant:/c alpine rm -rf /c/torch_extensions`); `PARO_ROT_KERNEL`/`PARO_SEED` env now passed into docker (stage2.sh); container name parameterised (`PARO_NAME`); my leftover `attn_implementation: eager` in the staged config reverted to SDPA (it was a 2–5× brake); `rocm-smi` absent post-reboot → amd-smi fallback in gpu_guard.
## HARDWARE RULES
**Device map AFTER the 2026-10-23 13:00 reboot** (hipGetDeviceCount lists FOUR gfx1201 cards; the W6600 is not enumerated by this runtime): **0 = 0000:03:00.0, 1 = 0000:27:00.0, 2 = 0000:2c:00.0, 3 = 0000:50:00.0** (the PCIe3 trx40 card — usable again, verified serving PARO-DFlash2 at 32.5 GiB). 0000:45:00.0 W6600 (gfx1032, desktop) is not exposed by HIP: never use. Before the reboot 50:00 was invisible to host processes and the map read 0/1/2/3 for 03/27/2c/45 — enumeration renumbered. LACT currently 0/0/250 W.
## COMPLETED AND VERIFIED (committed 12:46)
- m2xfp4 end-to-end: libquant quantiser (adaptive Sg-EM; `wide` is a no-op on real weights), gfx1201 WMMA kernels + host rows, arch wiring (`rad_block_dflash2.h:560`), spec/docs.
- RTN quality vs bf16 (32,367 pos): **KL 0.0348 / median 0.0121 / top-1 92.39 % / PPL 7.6976**; AWQ-MXFP4 0.0599/89.78 %; MXFP4-RTN excluded (kept).
- Stability: counters-in-scratch (m2/mx/fp8a8) + aql fences → 9,457-request soak, 0 faults.
- DFlash2 drafter m2xfp4: acceptance 62 % @2k → 52 % @32k; decode 156–160 tok/s; prefill ~2.5k tok/s.
- ParoQuant m2xfp4 grid (parity vs libquant), torch fallback rotation (≤1.6 ULP, never hangs), packer `tools/rad_pack_m2xfp4.py` + `Import::ParoM2`.
- Repos committed: radiance (codeberg hugypufy), vllm fork (github zedbytes), paroquant-src (local only — origin is upstream z-lab, no push rights).
## REMAINING
1. Finish the three FTs (MAIN ~5 h of layers left at ~5.8 min/layer after resume overhead; variants ~6.5 h).
2. Convert each at 400 files → pack (`tools/rad_pack_m2xfp4.py SRC --recipe data/recipes/q38-27b-paro-m2xfp4-df2.recipe --draft /home/zee/models/hf/Qwen3.8-27B-DFlash2 -o ...rad`) → serve → KL vs `kld-bf16` → pick winner (expect mean 0.030–0.032).
3. df2 re-bake with winner trunk; acceptance + 30–60 min abort soak; GSM8K 200 + concurrency sweep.
4. Long soak; MoE m2xfp4 (Flash-Next); activation Elem-EM (W4A4); block-parallel FT tooling (next FT ~2.5–3× faster).
## KEY PATHS
fp16 base /media/zee/ai/paro-stage/Qwen3.8-27B-fp16 (52 G, SDPA) · donor /home/zee/models/Qwen3.8-27B-PARO/model.safetensors · KL ref /home/zee/models/rad/kld-bf16 · containers /media/zee/ai · py-spy /src/.pyspy/bin/py-spy in-container
+2 -2
View File
@@ -661,8 +661,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.h}, {w.coef});
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
* fp8a8 tile, so an MXFP4 gate_up takes the pair. */
if (!w_gu[i].mx)
* fp8a8 tile, so an MXFP4 or M2XFP4 gate_up takes the pair. */
if (!w_gu[i].mx && !w_gu[i].m2x)
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
+1 -1
View File
@@ -110,7 +110,7 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
* Declared over int8 codes, only a host kernel would take it, and that would pin the layer's
* weights to the host. */
if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx &&
!gate_up.paro5 && !gate_up.w4 && !gate_up.i8)
!gate_up.m2x && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8)
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q, w.h.s },
gq_ffn.want_x
+159 -7
View File
@@ -708,6 +708,11 @@ struct LinearFP8 {
* view whose layout hook reduces it). Read from the weight's encoding. */
bool mx = false;
rad_weight wref = 0;
/* The M2XFP4 sibling (libquant `m2xfp4`): the MXFP4 weight plus one metadata byte a group,
* read by `gemm_nt_q` at dtype m2xfp4 with the same E4M3 pair, `b_scale` and `b_ref` as MXFP4's
* are, the meta plane riding the weight operand's stored blob. Read from the weight's
* encoding. */
bool m2x = false;
/* Rotated (ParoQuant) variant of `mx`: the same GEMM over an activation that
* `givens_dense_quant` makes from the bf16 plane (channel scale, dense per-group rotation and
* E4M3 quantiser in one pass), once per independently rotated part of a fused projection
@@ -870,6 +875,34 @@ inline bool linear_is_mxfp4(const RadEncoding& e) {
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
}
/* The M2XFP4 sibling (arXiv 2601.19213, the paper's weight-side Sg-EM): the MXFP4 weight plus one
* metadata byte per group of 32, four 2-bit subgroup extra mantissas that refine the exponent to
* (1 + k/4) . 2^E (libquant's `m2xfp4` quantiser; libr4d's m2xfp4 layout hook). The exponent byte
* carries the adaptive bias; the GEMM applies nothing beyond the planes. */
inline bool linear_is_m2xfp4(const RadEncoding& e) {
if (!rad_enc_is(&e, "m2xfp4") || e.n_planes != 3 || e.transform[0]) return false;
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *mt = rad_enc_plane(&e, "meta");
return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[0] == 1 && e.plane[0].block[1] == 1 &&
sc && sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP && mt &&
mt->dtype == RAD_U8 && mt->block[0] == 1 && mt->block[1] == RAD_MX_GROUP;
}
/* A rotated weight with M2XFP4 planes (ParoQuant's `m2xfp4` grid): the scheme's three planes in the
* basis of a "givens" transform, whose tables are views of the weight's planes. Read exactly like
* linear_is_paro_mxfp4 -- the meta plane rides the weight operand's stored blob -- over an
* activation the rotation makes. */
inline bool linear_is_paro_m2xfp4(const RadEncoding& e) {
if (!rad_enc_is(&e, "m2xfp4") || 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"), *mt = rad_enc_plane(&e, "meta"),
*pr = rad_enc_plane(&e, "t.pairs"), *an = rad_enc_plane(&e, "t.angle"),
*rs = rad_enc_plane(&e, "t.scale");
return pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32 &&
e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[0] == 1 && e.plane[0].block[1] == 1 &&
sc && sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP && mt &&
mt->dtype == RAD_U8 && mt->block[0] == 1 && mt->block[1] == RAD_MX_GROUP;
}
/* A rotated weight (ParoQuant): an affine encoding in the basis of a "givens" transform, with the
* rotation tables as planes (int32 column pairs, f32 angles, f32 channel scales; one set per part
* of a fused projection). The GEMM reads the codes as stored; the activation is rotated first. */
@@ -924,7 +957,8 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc));
/* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or
* quantises it. */
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc));
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc) ||
linear_is_paro_m2xfp4(enc));
reads_x = g.w_bf16 || plain || probed_i8 || rotated || (known && linear_is_w4(enc));
return RAD_OK;
}
@@ -1277,6 +1311,91 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
return RAD_E_DTYPE;
}
/* ---- M2XFP4 weight over the E4M3 pair: the MXFP4 weight's views plus the metadata plane,
* which rides the weight operand -- the declared view takes codes and meta together, and the
* stored blob carries the meta in its tail (libr4d's m2xfp4 layout). The exponent plane is
* `b_scale` and `b_ref` as MXFP4's is; the row parts, the shape bounds and the column-shard
* rule are the MXFP4 ones.
*
* A rotated weight (ParoQuant) carries the same planes in the basis its "givens" tables name,
* so it is declared exactly like the rotated MXFP4 one: `givens_dense_quant` makes the E4M3
* pair from the input's bf16 plane, once per rotated part, and the GEMM meets copy p with part
* p's rows. `paro` makes step() issue that rotation first. */
const bool m2rot = known && linear_is_paro_m2xfp4(enc);
const bool m2 = known && (linear_is_m2xfp4(enc) || m2rot);
if (m2) {
m2x = true;
paro = m2rot;
if (m2rot) {
if (!a.x) {
fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 weight, rotated and quantised "
"from its input's bf16 plane, and its input has none\n", wn);
return RAD_E_DTYPE;
}
if (g.world > 1 || span_hi > 0) {
fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 weight; its rotation is per "
"projection and is not cut by a tensor-parallel shard (world %d)\n",
wn, g.world);
return RAD_E_UNSUPPORTED;
}
} else if (!a.q || !a.s) {
fprintf(stderr, "radiance: '%s' is an M2XFP4 weight read against its input's E4M3 "
"pair, and its input has none\n", wn);
return RAD_E_DTYPE;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an M2XFP4 weight takes rows in "
"16s and K in whole %d-column activation scale blocks\n",
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles"));
int64_t pb1 = 0, pb2 = 0;
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
if (m2rot) {
std::vector<int64_t> cut;
for (int64_t p : rot_part_rows) cut.push_back(p);
if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p);
RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2));
rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { hi, rot_parts * K });
rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32,
{ hi, rot_parts * (K / RAD_FP8_BLOCK) });
if (!rot_q || !rot_s) return RAD_E_INVAL;
rot_dense = decl_dense(b, nm, base, wn, enc, K, grp);
if (!rot_dense) return RAD_E_INVAL;
op_rot = decl_dense_op(b, g, a, "fp8", 1, hi, { rot_q, rot_s });
if (!op_rot) return RAD_E_INVAL;
}
const char* sn = nm.f("%s.scale", base);
const char* rn = nm.f("%s.ref", base);
w = decl_view(b, wn, nullptr, "codes,meta", RAD_FP4E2M1, { N, K }, access, shard, grp,
rp.w, rp.n);
ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
if (!w || !ws || !wref) return RAD_E_INVAL;
if (span_hi > 0) {
const bool col = shard == RAD_SHARD_COL;
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
"%d-column activation scale block\n", base, (long long)span_lo,
(long long)span_hi, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
const int64_t lo = col ? span_lo / RAD_MX_GROUP : span_lo;
const int64_t hi_n = col ? span_hi / RAD_MX_GROUP : span_hi;
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi_n));
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi_n));
}
/* A rotated weight reads its own rotated pair, a plain one the producer's. */
op = decl_gemm_q(b, 1, hi, RAD_MX_GROUP, "m2xfp4", pb1, pb2, { w, ws, wref },
{ m2rot ? rot_q : a.q, m2rot ? rot_s : a.s }, y);
return op ? RAD_OK : RAD_E_INVAL;
}
/* ---- OCP-MXFP4 weight over the E4M3 pair. Three views: codes, exponents as `b_scale`, and
* the same plane as `b_ref`. Row parts apply as is (the exponent grid is one row tall); column
* slices must be whole 128s, the activation's scale block. */
@@ -1476,9 +1595,10 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (mx) {
if (mx || m2x) {
/* A rotated weight first rotates its input into its own codes, `rot_parts` copies side by
* side; a plain weight reads the producer's. */
* side; a plain weight reads the producer's. An M2XFP4 weight runs the same issue: it
* takes the operands MXFP4's does, its meta riding the weight operand's stored blob. */
const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s;
const int64_t ak = rot_parts * K;
if (paro)
@@ -1513,6 +1633,11 @@ struct DenseFP8 {
* works against the same E4M3 activation pair. */
rad_weight ref = 0;
bool mx = false;
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 weight plus one metadata byte a group, read by
* `gemm_nt_q` at dtype m2xfp4 with the same views and the same `b_ref`. The meta plane rides
* the weight operand's stored blob (libr4d's m2xfp4 layout), so the declared weight takes the
* codes and meta planes together. */
bool m2x = false;
/* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */
bool mapped = false;
@@ -1545,11 +1670,18 @@ struct DenseFP8 {
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
}
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi.
* `split_n`, when set, is the stored width a row slice takes its K split from (docs/OPS.md). */
/* `gemm_nt_q` over this weight, `fp8a8`, `mxfp4a8` or `m2xfp4` as it was declared, ranged
* M 1..hi. `split_n`, when set, is the stored width a row slice takes its K split from
* (docs/OPS.md). */
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes,
int64_t split_n = 0) const {
if (m2x)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "m2xfp4")),
RAD_WEIGHTS(w, s, ref)),
reads, writes);
if (mx)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
@@ -1569,8 +1701,8 @@ struct DenseFP8 {
RAD_WEIGHTS(w, s)),
reads, writes);
}
/* The op's trailing `b_ref` operand: the reference view for MXFP4, absent for fp8. */
RadOperand bref() const { return mx ? RAD_W(ref) : RAD_NONE; }
/* The op's trailing `b_ref` operand: the reference view for MXFP4 and M2XFP4, absent for fp8. */
RadOperand bref() const { return mx || m2x ? RAD_W(ref) : RAD_NONE; }
};
inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
@@ -1586,6 +1718,26 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
RadEncoding enc{};
mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc);
/* ---- M2XFP4: the MXFP4 views plus the metadata plane riding the weight operand, the
* same bounds. */
m2x = weight_enc(b, wn, &enc) && linear_is_m2xfp4(enc);
if (m2x) {
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an M2XFP4 weight takes rows "
"in 16s and K in whole %d-column activation scale blocks\n",
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles"));
w = decl_view(b, wn, nullptr, "codes,meta", RAD_FP4E2M1, { N, K }, access, shard, grp,
rp.w, rp.n);
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
return w && s && ref ? RAD_OK : RAD_E_INVAL;
}
if (mx) {
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows "
+32 -3
View File
@@ -598,6 +598,8 @@ struct Stream {
bool agent_only = false; /* rad_xp_stream_create: never a system-scope acquire */
std::atomic<int> gates{0}; /* closed gates (rad_stream_gate) on this queue */
std::atomic<int> fault{0};
int unordered_run = 0; /* played packets in a row without the barrier bit */
bool unordered_warned = false;
char* bounce = nullptr; /* pinned, for pageable copies */
std::mutex bounce_mu;
/* Chained launches (RadKernelChainFn): the completion counter every block of a chained kernel
@@ -933,12 +935,18 @@ inline int reserve(Stream* s, uint64_t* out) {
inline void publish(Stream* s, uint64_t idx, uint16_t header, uint16_t setup) {
s->wr = idx + 1;
hsa_queue_store_write_index_relaxed(s->q, idx + 1);
_mm_sfence(); /* the argument slot, written before the header */
s->unordered_run = 0; /* an offered packet: every reclamation proof holds */
_mm_sfence(); /* the packet body and the argument slot are write-combined
VRAM: globally visible before the index below exposes
the packet to the GPU (a torn kernarg read faults on the
device with a stripped high pointer bit) */
__atomic_store_n(reinterpret_cast<uint32_t*>(
static_cast<hsa_kernel_dispatch_packet_t*>(s->q->base_address) +
(idx & s->mask)),
(uint32_t)header | ((uint32_t)setup << 16), __ATOMIC_RELEASE);
/* The index is what exposes the packet to the GPU: only after the fence and the
* header, or the packet processor can read a half-written argument block. */
hsa_queue_store_write_index_relaxed(s->q, idx + 1);
hsa_signal_store_relaxed(s->q->doorbell_signal, (hsa_signal_value_t)idx);
}
@@ -1163,6 +1171,17 @@ struct PlayRun {
uint64_t next = 0; /* the write index after the last packet written */
int unrung = 0;
bool foreign = true; /* the next packet's queue has packets this thread did not play */
uint32_t seen[4] = {UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX};
int n_seen = 0;
/* True for the first dispatch this play writes on each queue, whatever its record says.
* reserve()'s argument-slot proof needs an ordered packet after any the reuse may race:
* a slot is reused once the read index passes the packet that held it, and only an
* ordered packet after that one makes the index mean "it completed". */
bool first_on(const Stream* q) {
for (int i = 0; i < n_seen; ++i) if (seen[i] == q->id) return false;
if (n_seen < 4) seen[n_seen++] = q->id;
return true;
}
void ring() {
if (!unrung) return;
@@ -1235,12 +1254,22 @@ struct PlayRun {
/* A dispatch carrying a record keeps the bit: its completion must cover everything before
* it on the queue, which an unordered dispatch's does not. A chained kernel behind another chained one
* on this queue waits in its prologue instead. */
bool ordered = foreign || !r.overlap || done.handle;
bool ordered = first_on(s) || foreign || !r.overlap || done.handle;
/* Not while a plain packet may still run: a played plain kernel the overlap analysis let
* start early (it touched nothing in flight) adds nothing to the counter, so a chained
* kernel that reads its output and sits behind a chained one (a cache read beside a
* collective, say) would wait for the chained blocks only. */
if (chain && s->prev_chained && !s->plain_inflight && !foreign && !done.handle) ordered = false;
/* The bound the slot proof rests on. Say so once if it is ever crossed, rather than tear
* an argument block silently. */
if (ordered) {
s->unordered_run = 0;
} else if (++s->unordered_run > kTapeOverlapRun && !s->unordered_warned) {
s->unordered_warned = true;
RAD_WARN("queue %u: %d played packets in a row carry no barrier bit, past the %d the "
"argument-slot proof tolerates; a kernarg block may be reused while a kernel "
"still reads it", s->id, s->unordered_run, kTapeOverlapRun);
}
const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, ordered);
__atomic_store_n(reinterpret_cast<uint32_t*>(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16),
__ATOMIC_RELEASE);
+82 -3
View File
@@ -1111,6 +1111,17 @@ void Checkpoint::detect_import() {
else
import_why_ = "ParoQuant's MXFP4 here is not format mxfp4 with 32-element blocks and "
"rotation groups of 128, which is the one this reads";
} else if (qm == "paroquant_m2xfp4") {
/* The same rotated planes on libquant's `m2xfp4` grid: e2m1 codes, an e8m0 exponent per 32
* of K, and one metadata byte a group whose four 2-bit subgroup multipliers refine that
* exponent to (1 + k/4) . 2^E. `mx_block` states the group the planes are cut in and
* `subgroup` the columns one multiplier covers. */
if (qc("format") == "m2xfp4" && qc("mx_block") == "32" && qc("subgroup") == "8" &&
qc("group_size") == "128")
import_ = Import::ParoM2;
else
import_why_ = "ParoQuant's M2XFP4 here is not format m2xfp4 with 32-element groups, "
"8-element subgroups and rotation groups of 128, which is the one this reads";
}
/* Rename the tool's quantization_config: plugins read that key as the served format
* (qwen35_fp8 checks quant_method is "fp8"), while an imported checkpoint states each weight's
@@ -1175,10 +1186,13 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK;
}
if (import_ == Import::QuarkMx || import_ == Import::ParoMx) {
if (import_ == Import::QuarkMx || import_ == Import::ParoMx || import_ == Import::ParoM2) {
/* Quark's MXFP4 is `fp4_e2m1*e8m0[1x32]` as stored: two codes per byte (element 2j in the
* low nibble), one biased exponent per 32 of K. The view only renames dtypes and the
* logical width. Excluded layers are plain tensors. */
* logical width. Excluded layers are plain tensors. ParoQuant's M2XFP4 grid carries one
* more plane (`weight_meta`, [N, K/32] u8) that is handed to the weight through
* import_meta: its bytes are the encoding's third plane as they ship. */
const bool m2 = import_ == Import::ParoM2;
const SrcTensor* w = find(name);
const SrcTensor* e = w ? find(name + "_scale") : nullptr;
if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND;
@@ -1186,6 +1200,11 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
e->shape[0] != w->shape[0] || e->shape[1] * 32 != w->shape[1] * 2)
return refuse(RAD_E_SHAPE, "'" + e->name + "' is not the [N, K/32] exponent plane of '" +
w->name + "'");
const SrcTensor* mt = m2 ? find(name + "_meta") : nullptr;
if (m2 && (!mt || mt->rad_dtype != RAD_U8 || mt->shape != e->shape))
return refuse(RAD_E_FORMAT, "'" + w->name + "' has no [N, K/32] u8 '" + name +
"_meta' beside its exponent plane, which the checkpoint's "
"m2xfp4 grid stores the subgroup multipliers in");
SrcTensor c = *w;
c.rad_dtype = RAD_FP4E2M1;
c.shape = { w->shape[0], w->shape[1] * 2 };
@@ -1196,6 +1215,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
sliced_.push_back(std::move(x));
*scale = &sliced_.back();
imported_[name] = { *codes, *scale };
if (mt) imported_meta_[name] = mt;
return RAD_OK;
}
@@ -1472,6 +1492,11 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK;
}
const SrcTensor* Checkpoint::import_meta(const std::string& name) const {
auto it = imported_meta_.find(name);
return it == imported_meta_.end() ? nullptr : it->second;
}
int Checkpoint::open(const std::string& path) {
path_ = path;
const bool gguf = path.size() > 5 && path.compare(path.size() - 5, 5, ".gguf") == 0;
@@ -1594,7 +1619,8 @@ std::string ckpt_tensor_of(const SrcTensor& t) {
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
std::unordered_set<std::string>* hit) {
bool any = false;
for (const auto* list : { &w.pieces, &w.scales, &w.pq_pairs, &w.pq_theta, &w.pq_scale })
for (const auto* list : { &w.pieces, &w.scales, &w.pq_pairs, &w.pq_theta, &w.pq_scale,
&w.pq_meta })
for (const SrcTensor* t : *list) {
if (!t) continue;
const std::string n = ckpt_tensor_of(*t);
@@ -2115,6 +2141,34 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&out->enc, "scale", RAD_F32, 1, 16);
}
} else if (dt == RAD_FP4E2M1 && scaled && ck.imports() == Checkpoint::Import::ParoM2) {
/* ParoQuant's M2XFP4: the MXFP4 planes byte for byte -- e2m1 codes, an e8m0 exponent per
* 32 of K -- plus the scheme's metadata byte a group (one per 32, four 2-bit subgroup
* multipliers), in the rotated basis the checkpoint trained, with the rotation beside them
* (paro_attach). Joined only along rows: every plane follows the pieces row by row. */
bool fits = d == 0 || out->pieces.size() == 1;
for (size_t k = 0; k < out->pieces.size() && fits; ++k) {
const SrcTensor* mt = ck.import_meta(out->pieces[k]->name);
fits = mt && out->scales[k] && out->scales[k]->rad_dtype == RAD_E8M0;
if (fits) out->pq_meta.push_back(mt);
}
if (!fits) {
out->pq_meta.clear();
out->why = "its M2XFP4 pieces are joined along a column, or a piece has no metadata "
"plane beside its exponents";
} else {
out->imported = true;
out->trivial = false;
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "m2xfp4");
rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&out->enc, "scale", RAD_E8M0, 1, 32);
rad_enc_add_plane(&out->enc, "meta", RAD_U8, 1, 32);
const int rc = paro_attach(ck, out, why);
if (rc != RAD_OK) return rc;
out->why = "it is ParoQuant M2XFP4, which rad-convert imports with its rotation tables "
"-- serve the container it writes";
}
} else if (dt == RAD_FP4E2M1 && scaled) {
/* Quark's MXFP4 byte for byte: codes and exponents are the planes of
* `fp4_e2m1*e8m0[1x32]`. Joined only along rows (gate and up). */
@@ -2741,6 +2795,31 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
}
return RAD_OK;
}
if (w.paro && std::strncmp(w.enc.plane[k].role, "meta", RAD_ENC_STR) == 0) {
/* The M2XFP4 grid's metadata byte a group, as stored: [N][K/32], one byte a group, the
* subgroup multipliers packed in it (subgroup s in bits [2s, 2s+2)). The checkpoint packs
* along N the way the plane does, so a row is a memcpy. */
int64_t base = 0;
for (size_t p = 0; p < w.pieces.size() && p < w.pq_meta.size(); ++p) {
const SrcTensor& m = *w.pq_meta[p];
const int64_t Np = w.pieces[p]->shape[0];
/* The pieces view is the logical [N, K] codes; one metadata byte covers 32 of K. */
const int64_t ng = w.pieces[p]->shape[1] / 32;
if (m.shape.size() != 2 || m.shape[0] != Np || m.shape[1] != ng)
return refuse(RAD_E_SHAPE, "'" + m.name + "' is not the [" + std::to_string(Np) +
", " + std::to_string(ng) + "] metadata plane of '" +
w.pieces[p]->name + "'; a stacked form it cannot be "
"sliced out of is refused rather than packed");
const int64_t lo = std::max(r0, base), hi = std::min(r0 + nr, base + Np);
if (hi > lo) {
std::memcpy(o, (const uint8_t*)m.data + (lo - base) * ng,
(size_t)((hi - lo) * ng));
o += (hi - lo) * ng;
}
base += Np;
}
return RAD_OK;
}
if (w.paro && std::strncmp(w.enc.plane[k].role, "t.", 2) == 0) {
/* A rotation table, built a row at a time: pairs converted from group-local to whole-row
* columns, angles widened, the channel scale inverted (the checkpoint multiplies the
+12 -4
View File
@@ -156,7 +156,8 @@ public:
* quantization_config at open. Gptq: AutoRound's `auto_round:auto_gptq` export and GPTQ v1
* (zero point stored less one). QuarkMx: Quark's MXFP4 (fp4 weights, per_group 32, e8m0
* scales, no per-layer overrides). ParoMx: ParoQuant's `paroquant_mxfp4` (Quark's codes and
* exponents in a rotated basis, rotations beside them). CtInt4, Nvfp4, CtFp8:
* exponents in a rotated basis, rotations beside them). ParoM2: ParoQuant's
* `paroquant_m2xfp4` (those planes plus the scheme's metadata byte a group). CtInt4, Nvfp4, CtFp8:
* compressed-tensors' pack-quantized int4 (symmetric, or asymmetric with a zero point), a
* release with an nvfp4-pack-quantized group, and one whose groups are all float-quantized FP8
* (detect_import). ModelOpt: NVIDIA ModelOpt's NVFP4, FP8, or both per layer
@@ -165,7 +166,7 @@ public:
* An unreadable form of these stays None, with the reason in import_refusal(). The
* quantization_config keys are then renamed `imported_quantization_config.*`, since they
* describe the tool, not a served format. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8,
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoM2, ParoI5, ParoI4, Nvfp4, CtFp8,
ModelOpt };
Import imports() const { return import_; }
const std::string& import_refusal() const { return import_why_; }
@@ -178,6 +179,10 @@ public:
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
std::string* why);
/* The metadata plane an imported `name` carries, when its form has one (ParoM2): [N, K/32] u8,
* one byte a group, as `weight_meta` ships it. Null for every other form. */
const SrcTensor* import_meta(const std::string& name) const;
private:
/* `owner` is the index's weight_map, if any: a tensor it places in another shard is skipped
* here. */
@@ -209,6 +214,8 @@ private:
bool ct_asym_ = false; /* CtInt4: the config states asymmetric weights */
/* import_piece's answers by name, so a weight resolved twice reuses its views. */
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
/* The metadata plane of an imported form that has one (ParoM2), by name. */
std::unordered_map<std::string, const SrcTensor*> imported_meta_;
};
/* ================================================================== logical weights */
@@ -250,9 +257,10 @@ struct CkptWeight {
/* ParoQuant MXFP4 (Import::ParoMx), also `imported`: written plane by plane through
* ckpt_plane_rows. Planes 0 and 1 are Quark's codes and exponents byte for byte; the rest are
* the "givens" transform's tables, built from `pq_pairs`/`pq_theta`/`pq_scale`, one set per
* piece (a row part: gate and up, or q, k and v, each rotated separately). */
* piece (a row part: gate and up, or q, k and v, each rotated separately). Import::ParoM2 is
* the same plus plane 3, the scheme's metadata byte a group, from `pq_meta`. */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale, pq_meta;
/* A weight-normalised tensor (RAD_MAP_WNORM): `pieces` is its direction v alone, and every
* element of v with first index i reads times wnorm_scale[i] = g_i / ||v_i||. Not trivial
* (the values change), so a recipe rule stores it. */
+34
View File
@@ -434,6 +434,40 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
return RAD_OK;
}
}
/* Codes with the metadata planes of a quantiser's own scheme, without the scale: the
* selected planes' canonical bytes concatenated, as stored. Read by a kernel that decodes
* the scheme itself beside the scale stream another operand carries (an m2xfp4 weight's
* codes+meta view, whose E8M0 exponent plane is the b_scale operand); there is nothing to
* decode here, because the scale is what the selection leaves out. */
if (!rad_enc_is(&e, "plain") && !rad_enc_is(&e, "affine") && dt == RAD_U8) {
int codes = -1;
bool meta = true;
for (int k = 0; k < n_sel && meta; ++k) {
const RadEncPlane& p = e.plane[sel[k]];
if (p.kind != RAD_PLANE_TILED || p.block[0] != 1 || p.block[1] < 1 ||
rad_enc_role_in_chain(p.role, "scale"))
meta = false;
else if (!std::strcmp(p.role, "codes")) {
if (codes >= 0 || p.block[1] != 1) meta = false; /* one code a value */
else codes = k;
}
}
if (meta && codes >= 0) {
int64_t bytes = 0;
for (int k = 0; k < n_sel; ++k)
bytes += rows[k] * rad_enc_row_bytes(e.plane[sel[k]].dtype, cols[k]);
if (bytes != n)
return refuse("its planes hold " + std::to_string(bytes) +
" bytes and the reader wants " + std::to_string(n));
uint8_t* dst = (uint8_t*)out;
for (int k = 0; k < n_sel; ++k) {
const int64_t rb = rad_enc_row_bytes(e.plane[sel[k]].dtype, cols[k]);
std::memcpy(dst, data[k], (size_t)(rows[k] * rb));
dst += rows[k] * rb;
}
return RAD_OK;
}
}
if (n_sel != e.n_planes)
return refuse("it takes " + std::to_string(n_sel) + " of its encoding's " +
std::to_string(e.n_planes) + " planes, which decode to nothing on their own");
@@ -0,0 +1,4 @@
# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
# A row listed here and not reached fails the replay; regenerate with
# --coverage-write when a row is added or deliberately retired.
gemm_m2xfp4a8_decode
@@ -0,0 +1,4 @@
# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
# A row listed here and not reached fails the replay; regenerate with
# --coverage-write when a row is added or deliberately retired.
gemm_m2xfp4a8_decode
@@ -0,0 +1,4 @@
# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
# A row listed here and not reached fails the replay; regenerate with
# --coverage-write when a row is added or deliberately retired.
gemm_m2xfp4a8_decode
@@ -0,0 +1,4 @@
# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
# A row listed here and not reached fails the replay; regenerate with
# --coverage-write when a row is added or deliberately retired.
gemm_m2xfp4a8_decode
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+31
View File
@@ -0,0 +1,31 @@
# q38-27b-m2xfp4-df2.recipe -- Qwen3.8-27B trunk + DFlash2 drafter at M2XFP4.
# f32 norm casts: the qwen35_fp8 plugin declares these norms RAD_F32 and the
# mapped tier cannot widen bf16 at load.
blk.*.attn_norm.weight cast dtype=f32
blk.*.attn_q_norm.weight cast dtype=f32
blk.*.attn_k_norm.weight cast dtype=f32
blk.*.ffn_norm.weight cast dtype=f32
dflash.blk.*.attn_norm.weight cast dtype=f32
dflash.blk.*.attn_q_norm.weight cast dtype=f32
dflash.blk.*.attn_k_norm.weight cast dtype=f32
dflash.blk.*.ffn_norm.weight cast dtype=f32
blk.*.ssm_ab.weight cast dtype=bf16
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
dflash.fc.weight m2xfp4
dflash.blk.*.attn_q.weight m2xfp4
dflash.blk.*.attn_k.weight m2xfp4
dflash.blk.*.attn_v.weight m2xfp4
dflash.blk.*.attn_output.weight m2xfp4
dflash.blk.*.ffn_gate_up.weight m2xfp4
dflash.blk.*.ffn_down.weight m2xfp4
blk.*.attn_qg.weight m2xfp4
blk.*.attn_q.weight m2xfp4
blk.*.attn_k.weight m2xfp4
blk.*.attn_v.weight m2xfp4
blk.*.attn_output.weight m2xfp4
blk.*.ssm_inz.weight m2xfp4
blk.*.ssm_out.weight m2xfp4
blk.*.ffn_gate_up.weight m2xfp4
blk.*.ffn_down.weight m2xfp4
v.* cast dtype=bf16
+19
View File
@@ -0,0 +1,19 @@
# q38-27b-m2xfp4.recipe -- Qwen3.8-27B trunk at M2XFP4, no drafter.
# f32 norm casts: the qwen35_fp8 plugin declares these norms RAD_F32 and the
# mapped tier cannot widen bf16 at load.
blk.*.attn_norm.weight cast dtype=f32
blk.*.attn_q_norm.weight cast dtype=f32
blk.*.attn_k_norm.weight cast dtype=f32
blk.*.ffn_norm.weight cast dtype=f32
blk.*.ssm_ab.weight cast dtype=bf16
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
blk.*.attn_qg.weight m2xfp4
blk.*.attn_q.weight m2xfp4
blk.*.attn_k.weight m2xfp4
blk.*.attn_v.weight m2xfp4
blk.*.attn_output.weight m2xfp4
blk.*.ssm_inz.weight m2xfp4
blk.*.ssm_out.weight m2xfp4
blk.*.ffn_gate_up.weight m2xfp4
blk.*.ffn_down.weight m2xfp4
v.* cast dtype=bf16
+19
View File
@@ -0,0 +1,19 @@
# q38-27b-m2xfp4.recipe -- Qwen3.8-27B trunk at M2XFP4, no drafter.
# f32 norm casts: the qwen35_fp8 plugin declares these norms RAD_F32 and the
# mapped tier cannot widen bf16 at load.
blk.*.attn_norm.weight cast dtype=f32
blk.*.attn_q_norm.weight cast dtype=f32
blk.*.attn_k_norm.weight cast dtype=f32
blk.*.ffn_norm.weight cast dtype=f32
blk.*.ssm_ab.weight cast dtype=bf16
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
blk.*.attn_qg.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.ssm_inz.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.ssm_out.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
v.* cast dtype=bf16
@@ -0,0 +1,45 @@
# q38-27b-paro-m2xfp4-df2.recipe -- a ParoQuant M2XFP4 Qwen3.8-27B (quant_method
# paroquant_m2xfp4) with the DFlash2 drafter.
#
# tools/rad_pack_m2xfp4.py <paroqant result dir> --model <donor> --recipe \
# data/recipes/q38-27b-paro-m2xfp4-df2.recipe --draft <DFlash2> -o q38-27b-paro-m2xfp4-df2.rad
#
# The trunk's linears are imported as they ship, and need no rule: e2m1 codes, an E8M0 exponent a 32
# of K and the scheme's metadata byte a group (four 2-bit subgroup multipliers, subgroup s in bits
# [2s, 2s+2)), stored in the ROTATED basis ParoQuant trained them in, with the rotations beside
# them as the encoding's "givens" transform (abi/rad_encoding.h): per projection the Givens pairs
# and angles of krot stages inside groups of 128 columns, and the channel scales. A fused gate|up or
# qkv|z keeps one set of tables a checkpoint tensor (parts). rad-convert writes them as planes of
# the weight; the GEMM is the plain M2XFP4 one, and the activation is rotated in front of it
# (givens_dense_quant) -- nothing is re-quantised, so the weights are the fine-tune's to the bit.
#
# What the checkpoint does NOT ship in a form the architecture declares gets a rule. `convert`
# loads the donor fp16, so everything it does not re-quantise is fp16 where the plugin declares
# bf16 or f32: `cast` rounds once. The head is quantised as in every recipe here; the MTP head is
# not read, since the DFlash2 drafter displaces it. THE DRAFTER is made as small as its acceptance
# allows, as in q38-27b-m2xfp4-df2.recipe.
blk.*.attn_norm.weight cast dtype=f32
blk.*.attn_q_norm.weight cast dtype=f32
blk.*.attn_k_norm.weight cast dtype=f32
blk.*.ffn_norm.weight cast dtype=f32
dflash.blk.*.attn_norm.weight cast dtype=f32
dflash.blk.*.attn_q_norm.weight cast dtype=f32
dflash.blk.*.attn_k_norm.weight cast dtype=f32
dflash.blk.*.ffn_norm.weight cast dtype=f32
blk.*.ssm_ab.weight cast dtype=bf16
blk.*.ssm_conv1d.weight cast dtype=bf16
token_embd.weight cast dtype=bf16
v.* cast dtype=bf16
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
dflash.fc.weight m2xfp4
dflash.blk.*.attn_q.weight m2xfp4
dflash.blk.*.attn_k.weight m2xfp4
dflash.blk.*.attn_v.weight m2xfp4
dflash.blk.*.attn_output.weight m2xfp4
dflash.blk.*.ffn_gate_up.weight m2xfp4
dflash.blk.*.ffn_down.weight m2xfp4
@@ -0,0 +1,51 @@
# q38-27b-paro-m2xfp4-mtp.recipe -- a ParoQuant M2XFP4 Qwen3.8-27B (quant_method
# paroquant_m2xfp4) with the base model's STANDARD MTP head instead of a DFlash2 drafter.
# The MTP head ({mtp.layers.0.*, mtp.fc, mtp.norm, mtp.pre_fc_norm_*, mtp.draft_head})
# is grafted from the bf16 release; blk.64 is its transformer block, so its linears take
# the rtn rule ahead of the trunk's m2xfp4 imports (first matching rule decides).
#
# tools/rad_pack_m2xfp4.py <paroqant result dir> --model <donor> --recipe \
# data/recipes/q38-27b-paro-m2xfp4-df2.recipe --draft <DFlash2> -o q38-27b-paro-m2xfp4-df2.rad
#
# The trunk's linears are imported as they ship, and need no rule: e2m1 codes, an E8M0 exponent a 32
# of K and the scheme's metadata byte a group (four 2-bit subgroup multipliers, subgroup s in bits
# [2s, 2s+2)), stored in the ROTATED basis ParoQuant trained them in, with the rotations beside
# them as the encoding's "givens" transform (abi/rad_encoding.h): per projection the Givens pairs
# and angles of krot stages inside groups of 128 columns, and the channel scales. A fused gate|up or
# qkv|z keeps one set of tables a checkpoint tensor (parts). rad-convert writes them as planes of
# the weight; the GEMM is the plain M2XFP4 one, and the activation is rotated in front of it
# (givens_dense_quant) -- nothing is re-quantised, so the weights are the fine-tune's to the bit.
#
# What the checkpoint does NOT ship in a form the architecture declares gets a rule. `convert`
# loads the donor fp16, so everything it does not re-quantise is fp16 where the plugin declares
# bf16 or f32: `cast` rounds once. The head is quantised as in every recipe here; the MTP head is
# not read, since the DFlash2 drafter displaces it. THE DRAFTER is made as small as its acceptance
# allows, as in q38-27b-m2xfp4-df2.recipe.
blk.*.attn_norm.weight cast dtype=f32
blk.*.attn_q_norm.weight cast dtype=f32
blk.*.attn_k_norm.weight cast dtype=f32
blk.*.ffn_norm.weight cast dtype=f32
dflash.blk.*.attn_norm.weight cast dtype=f32
dflash.blk.*.attn_q_norm.weight cast dtype=f32
dflash.blk.*.attn_k_norm.weight cast dtype=f32
dflash.blk.*.ffn_norm.weight cast dtype=f32
blk.64.*.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
blk.*.ssm_ab.weight cast dtype=bf16
blk.*.ssm_conv1d.weight cast dtype=bf16
token_embd.weight cast dtype=bf16
v.* cast dtype=bf16
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
dflash.fc.weight m2xfp4
dflash.blk.*.attn_q.weight m2xfp4
dflash.blk.*.attn_k.weight m2xfp4
dflash.blk.*.attn_v.weight m2xfp4
dflash.blk.*.attn_output.weight m2xfp4
dflash.blk.*.ffn_gate_up.weight m2xfp4
dflash.blk.*.ffn_down.weight m2xfp4
+26
View File
@@ -0,0 +1,26 @@
# q38-2b-distill-m2xfp4.recipe -- empero-ai/Qwen3.8-2B-Distill (the bf16 release) with every 2D
# trunk linear at M2XFP4, the metadata-augmented MXFP4 of arXiv 2601.19213: an OCP E2M1 code an
# element, an E8M0 exponent a group of 32 and one metadata byte a group whose four 2-bit subgroup
# extra mantissas refine the exponent to (1 + k/4) . 2^E, the exponent's bias in {-1, 0, 1}
# searched with the subgroups by least squared error (4.5 bits an element). The quantiser is
# libquant's `m2xfp4`, adaptive=1 by default; adaptive=0 pins the bias at 0.
#
# rad-convert /home/zee/models/hf/Qwen3.8-2B-Distill \
# --recipe data/recipes/q38-2b-distill-m2xfp4.recipe \
# -o /home/zee/models/rad/q38-2b-distill-m2xfp4.rad
#
# Everything the rules do not name stays bf16 as the checkpoint holds it: the norms, the embedding
# and lm_head (the 27B containers put the head at block fp8 -- one rule, add it here if wanted),
# the delta net's a/b projection (32 rows, kept as the other q38 recipes keep it), the vision
# tower and the router. Rank-1 weights a pattern happens to match are declined by the quantiser
# and kept as they are. The first rule that matches a weight decides it.
blk.*.attn_qg.weight m2xfp4
blk.*.attn_q.weight m2xfp4
blk.*.attn_k.weight m2xfp4
blk.*.attn_v.weight m2xfp4
blk.*.attn_output.weight m2xfp4
blk.*.ssm_inz.weight m2xfp4
blk.*.ssm_out.weight m2xfp4
blk.*.ffn_gate_up.weight m2xfp4
blk.*.ffn_down.weight m2xfp4
+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
+98
View File
@@ -3607,6 +3607,84 @@ void planes_cases(const Check& ck, std::vector<Hand>& hs, Broken& broken) {
hs.push_back(std::move(h));
}
/* ---- M2XFP4, the m2xfp4 quantiser's own scheme over the E4M3 pair ------------------------- *
* Codes across their whole range, E8M0 exponents over a few binades with a zero group among
* them, meta bytes across their whole range so every subgroup multiplier appears. The weight
* operand joins codes and meta as their concatenated bytes -- the codes rows, then the meta
* rows -- while `b_scale` and `b_ref` are the exponent plane as it lies. The oracle is the
* quantiser's own decode (libquant's lq_m2xfp.cpp): e2m1 . 2^(e-127) . (1 + k/4) against the
* activation's codes and per-128 scales, summed in double. N = 40 and 41 are not multiples of
* the drivers' row blocks; K = 384 is three activation scale blocks and a twelfth group, and
* M = 13, 17 the small-M paths' 8 + 4 + 1 rows and one past them. */
{
const float kE2M1[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
for (int64_t N : { 40, 41 })
for (int64_t M : { 1, 13, 17 }) {
const int64_t K = 384, kb = K / 32, akb = K / 128;
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "m2xfp4");
rad_enc_add_plane(&e, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&e, "scale", RAD_E8M0, 1, 32);
rad_enc_add_plane(&e, "meta", RAD_U8, 1, 32);
Planes w(e, N, K);
w.fill(0, [](int64_t r, int64_t c) {
return (float)hint(257, r * 61 + c, 0, 15);
});
auto ebyte = [](int64_t r, int64_t g) {
return (uint8_t)(g % 7 == 3 ? 0 : 118 + (r + g) % 6); /* a zero group among them */
};
auto mbyte = [kb](int64_t r, int64_t g) {
return (uint8_t)hint(259, r * kb + g, 0, 255);
};
for (int64_t r = 0; r < N; ++r)
for (int64_t g = 0; g < kb; ++g) {
w.row_at(1, r)[g] = ebyte(r, g);
w.row_at(2, r)[g] = mbyte(r, g);
}
const std::vector<RadParam> p =
rp({ { "M", M }, { "N", N }, { "K", K }, { "group", 32 } }, { { "dtype", "m2xfp4" } });
std::vector<uint8_t> j;
uint32_t jdt = 0;
std::string why;
if (!join_both(ck, "gemm_nt_q", p, 2, w, { 0, 2 }, &j, &jdt, &why)) {
broken.why.push_back(std::string("gemm_nt_q m2xfp4: ") + why);
continue;
}
/* The activation's exact e4m3 codes (integers the dtype holds) and f32 scales. */
auto acode = [](int64_t t) { return (float)hint(252, t, -13, 13); };
auto ascal = [akb](int64_t t) { return 0.003f * (float)(1 + (t / akb) % 5); };
std::vector<float> af((size_t)(M * K));
for (int64_t m = 0; m < M; ++m)
for (int64_t k = 0; k < K; ++k)
af[(size_t)(m * K + k)] = acode(m * K + k) * ascal(m * akb + k / 128);
const std::string nm = std::string("m2xfp4, M=") + std::to_string(M) + ", N=" +
std::to_string(N);
Hand h(nm.c_str(), "gemm_nt_q", 8e-3);
h.dense(RAD_F8E4M3, { M, K }, acode)
.dense(RAD_F32, { M, akb }, ascal);
h.raw(RAD_U8, { N * (K / 2 + kb) }, j.data());
h.raw(RAD_E8M0, { N, kb }, w.data[1].data());
h.dense(RAD_BF16, { M, N }, zero, true)
.none()
.raw(RAD_E8M0, { N, kb }, w.data[1].data());
h.pi("M", M).pi("N", N).pi("K", K).pi("group", 32).ps("dtype", "m2xfp4");
std::vector<float> W((size_t)(N * K));
for (int64_t r = 0; r < N; ++r)
for (int64_t k = 0; k < K; ++k) {
const int64_t c = hint(257, r * 61 + k, 0, 15);
const uint8_t mb = mbyte(r, k >> 5);
const float km = 1.0f + 0.25f * (float)((mb >> (2 * ((k & 31) >> 3))) & 3);
W[(size_t)(r * K + k)] = (c & 8 ? -kE2M1[c & 7] : kE2M1[c & 7]) *
std::ldexpf(1.0f, (int)ebyte(r, k >> 5) - 127) * km;
}
h.oracle_opd = 4;
h.oracle_tol = 8e-3;
h.oracle = oracle_gemm(af, K, W, M, N, K, [](int64_t) { return 0; });
hs.push_back(std::move(h));
}
}
/* ---- refusals ------------------------------------------------------------------------ *
* A zero-point grid's `b_scale` that is not joined has no zero to read: both refuse. */
{
@@ -3666,6 +3744,26 @@ bool planes_refusals(const Check& ck, int* run) {
zp(RAD_U4, RAD_U8, 128, nullptr), { 2, 1 }, RAD_E_DTYPE });
rs.push_back({ "scale and zero at fp8a8", "gemm_nt_q", 3, gq("fp8a8"),
zp(RAD_U4, RAD_U8, 128, nullptr), { 1, 2 }, RAD_E_DTYPE });
const auto gq32 = [&](const char* dt) {
return P({ { "M", 4 }, { "N", 256 }, { "K", 256 }, { "group", 32 } }, dt);
};
const auto m2enc = [] {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "m2xfp4");
rad_enc_add_plane(&e, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&e, "scale", RAD_E8M0, 1, 32);
rad_enc_add_plane(&e, "meta", RAD_U8, 1, 32);
return e;
};
rs.push_back({ "m2xfp4 over affine planes", "gemm_nt_q", 2, gq32("m2xfp4"),
zp(RAD_U4, RAD_U8, 32, nullptr), { 0, 2 }, RAD_E_DTYPE });
rs.push_back({ "m2xfp4 with codes but no meta", "gemm_nt_q", 2, gq32("m2xfp4"), m2enc(), { 0 },
RAD_E_DTYPE });
rs.push_back({ "m2xfp4's scale plane alone", "gemm_nt_q", 3, gq32("m2xfp4"), m2enc(), { 1 },
RAD_E_UNSUPPORTED });
rs.push_back({ "m2xfp4's reference plane alone", "gemm_nt_q", 6, gq32("m2xfp4"), m2enc(), { 1 },
RAD_E_UNSUPPORTED });
bool ok = true;
for (R& r : rs) {
for (const Lib* lib : { ck.ref, ck.lib }) {
+54
View File
@@ -299,6 +299,45 @@ static int gemm_q_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Sc
return gemm_drive(ma, mb, SA, SB, Y, bias, M, N, K);
}
/* gemm_nt_q at dtype m2xfp4, the m2xfp4 quantiser's own scheme (libquant): `b` is the weight's
* codes and meta planes concatenated as stored (avx_planes.h's m2 arm -- the codes rows, then the
* meta rows), `b_scale` the E8M0 exponent plane [N, K/32] and `b_ref` the same plane, as the
* mxfp4 grid's. The exact element is e2m1 code . 2^(e-127) . (1 + k_s/4), the subgroup multiplier
* k_s the meta byte's two-bit field [2s, 2s+2) over subgroups s of eight columns: the product
* runs with the weight's group at that eight and the meta folded into the scale stream
* (Scales::m2), the same law ref states element by element (ref_gemm.cpp's gemm_m2) and
* libr4d's staging table applies on the card. */
static int gemm_m2(const RadTensor* A, const RadTensor* as_, const RadTensor* B,
const RadTensor* bs_, const RadTensor* Y, int64_t M, int64_t N, int64_t K) {
if (A->dtype != RAD_F8E4M3 || B->dtype != RAD_U8 || B->rank != 1) return RAD_E_DTYPE;
if (!as_ || !bs_ || bs_->rank < 2) return RAD_E_DTYPE;
if (K <= 0 || K % 32 || N <= 0) return RAD_E_SHAPE;
if (numel(B) != N * (K / 2 + K / 32)) return RAD_E_SHAPE;
Scales SB = make_scales(bs_, N, K, true);
if (!SB.p || SB.group != 32 || SB.rblk != 1) return RAD_E_SHAPE;
SB.group = 8;
SB.e8m0 = true;
SB.m2 = true;
SB.m2_meta = (const uint8_t*)B->data + N * (K / 2);
SB.m2_mrs = K / 32;
/* The codes as their own [N, K] operand over the concatenation's head: nibble elements, a
* row K/2 bytes, dense. */
RadTensor Bc{};
Bc.data = B->data;
Bc.dtype = RAD_FP4E2M1;
Bc.rank = 2;
Bc.shape[0] = N;
Bc.shape[1] = K;
Bc.stride[0] = K;
Bc.stride[1] = 1;
Scales SA = make_scales(as_, M, K, false);
const Mat ma = as_mat(A, K), mb = as_mat(&Bc, K);
return gemm_q_drive(ma, mb, &SA, &SB, Y, nullptr, M, N, K);
}
/* gemm_nt_bias's epilogue (docs/OPS.md): activation of the stored product, then the residual add,
* each step read from and stored to the output's dtype (the unfused chain, as in libref). */
static void gemm_epilogue(const RadTensor* Y, const RadTensor* res, int act, int64_t M, int64_t N) {
@@ -975,6 +1014,20 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
* to the grids that remove a zero through it, `b_ref` to an e2m1 weight. */
const avxp::ZpGrid* zg = avxp::zp_grid(p_str(a, "dtype", nullptr));
if (zg && bias_operand) return RAD_E_UNSUPPORTED;
/* M2XFP4: the quantiser's own scheme, decoded by gemm_m2 from its concatenated planes (whose
* byte count is its own, not N x K). Parts (pb1/pb2) are the rotated grids'; the m2 declare
* makes none, and a case carrying them is declined rather than answered unsplit, as libref
* declines them. Its `b_ref` is the mxfp4 grid's, accepted and ignored beside the scheme. */
if (!bias_operand && p_str(a, "dtype", nullptr) &&
std::strcmp(p_str(a, "dtype", nullptr), "m2xfp4") == 0) {
if (rad_arg_in(a, 5)) return RAD_E_UNSUPPORTED; /* a_sum belongs to the asym grids */
if (p_int(a, "pb1", 0) > 0 || p_int(a, "pb2", 0) > 0) return RAD_E_UNSUPPORTED;
const int64_t K = p_int(a, "K", 0), N = p_int(a, "N", 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
return gemm_m2(A, as_, B, bs_, Y, M, N, K);
}
if (!bias_operand) {
if (rad_arg_in(a, 5) && (!zg || zg->act != avxp::ZP_I8_ROW)) return RAD_E_UNSUPPORTED;
if (rad_arg_in(a, 6) && B->dtype != RAD_FP4E2M1) return RAD_E_UNSUPPORTED;
@@ -988,6 +1041,7 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE;
if (bias && numel(bias) < N) return RAD_E_SHAPE;
/* quant_act_i8's codes arrive with the middle two dwords of every 16-byte step exchanged;
* exchange them back into a contiguous copy. */
RadTensor Ac;
+25 -2
View File
@@ -84,7 +84,20 @@ struct Scales {
uint32_t dt;
int64_t rs, cs, group, rblk;
bool e8m0;
/* M2XFP4 (libquant's `m2xfp4`, lq_m2xfp.cpp): `group` is 8, so `g` names a subgroup of
* eight columns. The E8M0 byte is one per four subgroups and the meta plane's two-bit field
* refines it, the scale of subgroup g being e8m0(scale[g >> 2]) . (1 + k/4) with k the
* field's value -- the quantiser's own decode, stated where this folds it into the product. */
const uint8_t* m2_meta = nullptr; /* [rows][K/32] meta bytes, canonical rows */
int64_t m2_mrs = 0; /* bytes between meta rows */
bool m2 = false;
inline float grp(int64_t row, int64_t g) const {
if (m2) {
const int64_t gi = g >> 2;
const int64_t i = (rblk > 1 ? row / rblk : row) * rs + gi * cs;
const int k = (m2_meta[row * m2_mrs + gi] >> (2 * (g & 3))) & 3;
return rad_e8m0_to_f32(((const uint8_t*)p)[i]) * (1.0f + 0.25f * (float)k);
}
const int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs;
if (e8m0) {
const uint8_t e = ((const uint8_t*)p)[i];
@@ -95,6 +108,17 @@ struct Scales {
/* Groups [g0, g0 + n) of `row` into dst, the same values grp() returns, with the dtype
* resolved once rather than per scale. */
inline void row_groups(int64_t row, int64_t g0, int64_t n, float* dst) const {
if (m2) {
const int64_t rr = rblk > 1 ? row / rblk : row;
const uint8_t* b = (const uint8_t*)p;
for (int64_t g = 0; g < n; ++g) {
const int64_t gi = g0 + g;
const int k = (m2_meta[row * m2_mrs + (gi >> 2)] >> (2 * (gi & 3))) & 3;
dst[g] = rad_e8m0_to_f32(b[rr * rs + (gi >> 2) * cs]) *
(1.0f + 0.25f * (float)k);
}
return;
}
const int64_t base = (rblk > 1 ? row / rblk : row) * rs + g0 * cs;
const uint8_t* b = (const uint8_t*)p;
if (cs == 1) {
@@ -112,8 +136,7 @@ struct Scales {
for (int64_t g = 0; g < n; ++g)
dst[g] = rad_bf16_to_f32(((const uint16_t*)p)[base + g * cs]);
} else if (dt == RAD_F16) {
for (int64_t g = 0; g < n; ++g)
dst[g] = rad_f16_to_f32(((const uint16_t*)p)[base + g * cs]);
for (int64_t g = 0; g < n; ++g) dst[g] = rad_f16_to_f32(((const uint16_t*)p)[base + g * cs]);
} else if (dt == RAD_F32) {
for (int64_t g = 0; g < n; ++g) dst[g] = ((const float*)p)[base + g * cs];
} else {
+101 -2
View File
@@ -159,12 +159,67 @@ static inline int avx_layout_mtp(const RadParam*, int, int operand, const RadEnc
return layout_scaled(operand, 4, 5, enc, sel, planes, n, out);
}
/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the grid `dtype` names. */
/* M2XFP4, the `m2xfp4` quantiser's own scheme (libquant): three TILED planes over 32-column
* groups, and gemm_nt_q's weight operand takes the codes and the meta. Their stored form is the
* two planes' canonical bytes concatenated -- the codes' rows, then the meta's -- the form the
* core's selection reader hands a kernel that decodes the scheme itself beside the scale stream
* another operand carries (core/format/encoding.cpp), and the one both libraries' m2 arms read.
* libref/ref_planes.h states the same rules. */
static inline bool m2_enc_planes(const RadEncoding* enc) {
if (!rad_enc_is(enc, "m2xfp4")) return false;
/* A rotated weight (ParoQuant) carries the same three planes in the basis its "givens"
* transform names, with the rotation's tables beside them; the rotation is the activation's,
* so the planes are read as they are. */
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
const RadEncPlane* mt = rad_enc_plane(enc, "meta");
const bool planes = enc->plane[0].kind == RAD_PLANE_TILED &&
enc->plane[0].dtype == RAD_FP4E2M1 && enc->plane[0].block[0] == 1 &&
enc->plane[0].block[1] == 1 && sc && mt && sc->kind == RAD_PLANE_TILED &&
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == 32 &&
mt->kind == RAD_PLANE_TILED && mt->dtype == RAD_U8 && mt->block[0] == 1 &&
mt->block[1] == 32;
if (!planes) return false;
if (!enc->transform[0]) return enc->n_planes == 3;
return enc->n_planes >= 6 && rad_enc_plane(enc, "t.pairs") &&
rad_enc_plane(enc, "t.angle") && rad_enc_plane(enc, "t.scale");
}
/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the grid `dtype` names. At `m2xfp4`
* the weight operand takes codes and meta concatenated (above); the scale and reference operands
* are single planes, stored as they are. */
static inline int avx_layout_gemm_q(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
const char* dt = rad_param_gets(p, n_p, "dtype", nullptr);
if (dt && std::strcmp(dt, "m2xfp4") == 0) {
const long long group = rad_param_geti(p, n_p, "group", 0);
const long long N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
if (!m2_enc_planes(enc) || group != 32 || N <= 0 || K <= 0 || K % 32)
return RAD_E_DTYPE;
if (operand == 2) {
if (!sel_roles(enc, sel, n, "codes", "meta")) return RAD_E_DTYPE;
if (planes[0].shape[0] != N || planes[0].shape[1] != K ||
planes[1].shape[0] != N || planes[1].shape[1] != K / 32)
return RAD_E_SHAPE;
out->tag = "m2.codes.meta";
out->dtype = RAD_U8;
out->rank = 1;
out->shape[0] = N * (K / 2 + K / 32);
out->align = 0;
out->bytes = out->shape[0];
return RAD_OK;
}
if (operand == 3 || operand == 6) {
if (n != 1 || sel[0] < 0 || sel[0] >= enc->n_planes ||
std::strncmp(enc->plane[sel[0]].role, "scale", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
return RAD_E_UNSUPPORTED; /* one plane, stored as it is */
}
return RAD_E_UNSUPPORTED;
}
if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr));
const ZpGrid* zg = zp_grid(dt);
const long long group = rad_param_geti(p, n_p, "group", 0);
if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
@@ -182,6 +237,50 @@ static inline int avx_layout_gemm_q(const RadParam* p, int n_p, int operand,
return rad_planes_layout(enc, sel, planes, n, out);
}
/* gemm_nt_q's own relayout: the m2 arm's concatenated form beside the zero-point grids' joined
* one, each as its layout hook laid it out. */
template <RadLayoutFn L>
static int avx_relayout_gemm_q(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst,
int64_t dst_bytes) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (lay.tag && std::strcmp(lay.tag, "m2.codes.meta") == 0) {
if (dst_bytes != lay.bytes) return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
for (int i = 0; i < n; ++i) {
const int64_t rb = rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
const int64_t b = planes[i].shape[0] * rb;
std::memcpy(d, planes[i].data, (size_t)b);
d += b;
}
return RAD_OK;
}
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
}
template <RadLayoutFn L>
static int avx_unrelayout_gemm_q(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (lay.tag && std::strcmp(lay.tag, "m2.codes.meta") == 0) {
if (src_bytes != lay.bytes) return RAD_E_SHAPE;
const uint8_t* s = (const uint8_t*)src;
for (int i = 0; i < n; ++i) {
const int64_t rb = rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
const int64_t b = planes[i].shape[0] * rb;
std::memcpy(planes[i].data, s, (size_t)b);
s += b;
}
return RAD_OK;
}
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
}
template <RadLayoutFn L>
static int avx_relayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst,
+11 -3
View File
@@ -1385,6 +1385,14 @@ static int avx_moe_cb_unrelayout(const RadParam* p, int n_p, int operand, const
avxp::avx_relayout_planes<avxp::lay>, nullptr, avxp::avx_unrelayout_planes<avxp::lay>, \
nullptr }
/* gemm_nt_q: its zero-point grids join scale and zero (avx_planes.h) while its m2xfp4 arm
* concatenates codes and meta, so the row carries the hook's own relayout pair. */
#define ROWL_GQ(nm, opname, fam, what, dts, fn, lay) \
{ nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \
nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, fn, nullptr, avxp::lay, \
avxp::avx_relayout_gemm_q<avxp::lay>, nullptr, avxp::avx_unrelayout_gemm_q<avxp::lay>, \
nullptr }
#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*)"
@@ -1547,9 +1555,9 @@ SIMPLE("avx_gated_quant_fp8", "gated_quant_fp8", "quant",
SIMPLE("avx_gemm_nt", "gemm_nt", "gemm", "C = A B^T, f32 accumulate, cache-blocked", DT_FLOAT,
L(gemm_nt)),
SIMPLE("avx_gemm_nt_bias", "gemm_nt_bias", "gemm", "C = A B^T + bias", DT_FLOAT, L(gemm_nt_bias)),
ROWL("avx_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; u2 / u4 / u5 codes with an f16 scale "
"and integer zero per group, joined; f32 accumulate", L(gemm_nt_q), avx_layout_gemm_q),
ROWL_GQ("avx_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands",
"i8 / fp8 / float A; w4, w2, mxfp4, m2xfp4, i8 or float B; u2 / u4 / u5 codes with an f16 "
"scale and integer zero per group, joined; f32 accumulate", L(gemm_nt_q), avx_layout_gemm_q),
SIMPLE("avx_gemm_nt_q_bias", "gemm_nt_q_bias", "gemm", "quantised C = A B^T + bias",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", L(gemm_nt_q_bias)),
SIMPLE("avx_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base rows untouched",
+254
View File
@@ -0,0 +1,254 @@
/* lq_m2xfp.cpp -- the `m2xfp4` quantiser: M2XFP, a metadata-augmented Microscaling format
* (Weiming Hu et al., "M2XFP: A Metadata-Augmented Microscaling Data Format for Efficient
* Low-bit Quantization", ASPLOS '26, arXiv 2601.19213), weight side only -- the paper's
* Sg-EM scheme, subgroup-level extra mantissa with an adaptive shared scale.
*
* An OCP MXFP4 group of 32 columns carries, beside its E8M0 exponent, one metadata byte: four
* 2-bit extra mantissas, one a subgroup of 8 columns. Subgroup s (columns [8s, 8s+8)) refines the
* group's shared scale to (1 + k/4) . 2^E with k its two bits, so a group decodes as
*
* w[j] = e2m1(codes[j]) . 2^(scale[g] - 127) . (1 + k_s/4), g = j/32, s = (j%32)/8,
*
* 4.5 bits an element. The three planes sit apart, as the paper's memory organisation keeps them
* (its §5.2): codes fp4_e2m1 [1 x 1] as a bit stream along the row (abi/rad_encoding.h), the scale
* e8m0 [1 x 32] and the metadata u8 [1 x 32] one byte a group, the metadata packed little-endian,
* subgroup s in bits [2s, 2s+2). The scheme is "m2xfp4", which the core does not decode; the
* quantiser's own decode hook reads it back (abi/rad_quant.h).
*
* The search is the paper's §4.4.2, Eqs. 3-4, hierarchical because a subgroup's k is chosen
* independently once the bias is fixed and only the bias couples the subgroups. E0 is the OCP
* rule floor(log2(amax / 4)); the group's scale candidates are 2^(E0+b), b in {-1, 0, 1}, and
* each subgroup's are (1 + k/4) times the group's, k in {0, 1, 2, 3}. For a bias, every
* subgroup takes the k of least squared error against its own 8 columns; the group takes the
* bias of least squared error over the four. adaptive=0 pins the bias at 0 and searches the
* subgroups only, which is where a container that wants the plain exponent still wants the
* refinement; wide=1 widens adaptive's sweep to b in {-2, ..., 2}, still lowest-first so a tie
* keeps the lowest bias. The bias costs nothing stored: it is absorbed into the exponent byte.
*
* Conventions shared with the MXFP4 grid (`rtn codes=fp4_e2m1 group=32 scale=e8m0`,
* lq_grid.cpp's rule=mx), whose containers this format is a superset of:
* - E0 is taken as the f32 exponent field of amax less 129, exactly as rule=mx takes it (for
* every normal amax that is floor(log2(amax)) - 2); the paper's reference takes floor(log2
* of an amax clamped to 1e-8, which differs only below the f32 normals;
* - a zero group stores scale byte 0 and zero codes, rule=mx's exponent-floor clamp; the
* reference's clamp gives a different byte whose codes and decode are the same zeros;
* - codes round to nearest, ties to the even code -- f32_to_e2m1, the same rounding the grid
* quantises with (and the reference's nudged midpoints);
* - the exponent byte is clamped to [0, 254]; 255 is E8M0's NaN;
* - a final group shorter than 32 columns is its own group over the columns it has, the way
* the grid quantises a row's tail (the reference requires a whole number of groups).
*
* Under the (b=0, k=0) candidate every group reproduces rule=mx's scale and codes exactly, so
* an adaptive weight's error is that plain MXFP4's or better, group by group.
*
* The error summed is in double; the per-candidate dequantised value is computed exactly as the
* decode computes it (the code through rad_fp4e2m1_to_f32, times the candidate's scale), so what
* the search minimises is what a reader gets. Rows are independent, so the stored bytes do not
* depend on the thread count.
*/
#include "lq_m2xfp.h"
#include "lq_common.h"
#include "lq_quant.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace lq {
namespace {
const char kScheme[] = "m2xfp4";
const RadQuantOption kM2xfpOptions[] = {
{ "adaptive", RAD_P_INT, "1",
"1: search the group's exponent bias b in {-1, 0, 1} beside the subgroups (the paper's "
"Eq. 4); 0: the bias pinned at 0, the subgroup search still on" },
{ "wide", RAD_P_INT, "0",
"1: widen adaptive's bias search to b in {-2, -1, 0, 1, 2}; 0: {-1, 0, 1}. Ignored at "
"adaptive=0, which pins the bias at 0 whatever the sweep width" },
};
/* One subgroup's least squared error over k, with k itself through `best` when asked: the
* subgroups of one bias are independent (the paper's Eq. 4 inner argmin). The dequantised value
* is the code through the same table the decode reads, times the candidate's scale. */
double subgroup_sse(const float* w, int64_t b0, int64_t b1, float s, int* best) {
double best_sse = -1.0;
int best_k = 0;
for (int k = 0; k < 4; ++k) {
const float sm = s * (1.0f + 0.25f * (float)k);
double sse = 0.0;
for (int64_t i = b0; i < b1; ++i) {
const float dq = rad_fp4e2m1_to_f32(f32_to_e2m1(w[i] / sm)) * sm;
const double d = (double)dq - (double)w[i];
sse += d * d;
}
if (best_sse < 0.0 || sse < best_sse) {
best_sse = sse;
best_k = k;
}
}
if (best) *best = best_k;
return best_sse;
}
/* One row's group of [c0, c1): the OCP exponent of its amax, the bias of least subgroup error,
* then the winning bias's subgroups, whose k go into the metadata byte and whose codes and
* exponent byte go into the planes. Ties keep the first candidate, the k and then the b of
* lowest index, as the paper's argmin does. */
void quant_group(const float* w, int64_t c0, int64_t c1, int adaptive, int wide, uint8_t* codes,
uint8_t* scale, uint8_t* meta, uint32_t codes_dt) {
float amax = 0.0f;
for (int64_t c = c0; c < c1; ++c) {
const float a = w[c] < 0.0f ? -w[c] : w[c];
if (a > amax) amax = a;
}
/* E0 = floor(log2(amax / 4)), as rule=mx takes it: the exponent field less emax + 127. A
* zero group keeps -127, the field's underflow, whose byte clamps to 0 like rule=mx's. */
int e0 = -127;
if (amax > 0.0f) {
uint32_t u;
std::memcpy(&u, &amax, 4);
e0 = (int)((u >> 23) & 0xFFu) - 127 - 2;
}
/* The bias: every subgroup's best k given it, summed over the group (the paper averages the
* four, the same argmin). adaptive=0 sees only b = 0; wide sweeps b over {-2, ..., 2}
* instead of {-1, 0, 1}, lowest first either way, so a tie keeps the lowest bias as the
* paper's argmin does. */
const int lo = adaptive ? (wide ? -2 : -1) : 0;
const int hi = adaptive ? (wide ? 2 : 1) : 0;
int best_b = 0;
double best_err = -1.0;
for (int b = lo; b <= hi; ++b) {
const float s = rad_e8m0_to_f32((uint8_t)clampi(e0 + b + 127, 0, 254));
double err = 0.0;
for (int64_t c = c0; c < c1; c += 8)
err += subgroup_sse(w, c, c + 8 < c1 ? c + 8 : c1, s, nullptr);
if (best_err < 0.0 || err < best_err) {
best_err = err;
best_b = b;
}
}
/* The winning bias's scale, its subgroups' k, and the codes those k were chosen against. */
const int e8 = clampi(e0 + best_b + 127, 0, 254);
const float s = rad_e8m0_to_f32((uint8_t)e8);
uint8_t mb = 0;
for (int sl = 0; sl < 4; ++sl) {
const int64_t c = c0 + 8 * sl;
if (c >= c1) break; /* a short final group's absent subgroups */
int k = 0;
subgroup_sse(w, c, c + 8 < c1 ? c + 8 : c1, s, &k);
mb |= (uint8_t)k << (2 * sl);
const float sm = s * (1.0f + 0.25f * (float)k);
for (int64_t j = c; j < c + 8 && j < c1; ++j)
rad_store_code(codes, codes_dt, j, (int)f32_to_e2m1(w[j] / sm));
}
*scale = (uint8_t)e8;
*meta = mb;
}
int m2xfp_encoding(const RadParam*, int, const RadQuantWeight* w, RadEncoding* out) {
if (declines(w)) return RAD_E_UNSUPPORTED;
if (!w || w->cols <= 0 || w->rows <= 0) return RAD_E_SHAPE;
rad_enc_clear(out);
rad_enc_copy_str(out->scheme, kScheme);
/* The three streams of the paper's §5.2: the codes, the group's exponent, the group's
* metadata -- a final group shorter than 32 columns covers the columns it has. The codes and
* the scale carry the MXFP4 grid's dtypes, whose bytes these are; the exponent byte is an
* E8M0 biased exponent, never the integer a bare u8 would read as. */
rad_enc_add_plane(out, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(out, "scale", RAD_E8M0, 1, 32);
rad_enc_add_plane(out, "meta", RAD_U8, 1, 32);
return RAD_OK;
}
/* Groups are column-local and rows independent, so a call may take any rows: one, as the MXFP4
* grid's row block is, and the converter streams by its band, not by the format. */
int64_t m2xfp_row_block(const RadParam*, int, const RadQuantWeight*) { return 1; }
int m2xfp_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
int64_t rows, void* const* planes) {
if (!w || w->cols <= 0 || w->rows <= 0) return RAD_E_SHAPE;
if (row0 < 0 || rows < 0 || row0 + rows > w->rows) return RAD_E_SHAPE;
const int adaptive = (int)rad_param_geti(o, n_o, "adaptive", 1);
const int wide = (int)rad_param_geti(o, n_o, "wide", 0);
const int64_t C = w->cols;
const int64_t ng = (C + 31) / 32; /* groups a row, the last one maybe short */
uint8_t* codes = (uint8_t*)planes[0];
uint8_t* scale = (uint8_t*)planes[1];
uint8_t* meta = (uint8_t*)planes[2];
const int64_t codes_row = rad_enc_row_bytes(RAD_FP4E2M1, C);
const uint32_t codes_dt = RAD_FP4E2M1; /* the plane's dtype: same four bits as u4 */
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < rows; ++r) {
const float* wr = src + r * C;
uint8_t* cr = codes + r * codes_row;
uint8_t* sr = scale + r * ng;
uint8_t* mr = meta + r * ng;
for (int64_t g = 0; g < ng; ++g)
quant_group(wr, g * 32, std::min(g * 32 + 32, C), adaptive, wide, cr, sr + g, mr + g,
codes_dt);
}
return RAD_OK;
}
/* The encoding's own decode (abi/rad_quant.h): the equation of the scheme, the only place the
* core cannot follow it. RAD_E_UNSUPPORTED for an encoding this quantiser did not write. */
int m2xfp_decode(const RadEncoding* e, const RadQuantWeight* w, const void* const* planes,
int64_t row0, int64_t rows, float* out) {
if (!rad_enc_is(e, kScheme) || e->n_planes != 3) return RAD_E_UNSUPPORTED;
const RadEncPlane* p = e->plane;
if (p[0].dtype != RAD_FP4E2M1 || p[0].kind != RAD_PLANE_TILED || p[0].block[0] != 1 ||
p[0].block[1] != 1 || std::strcmp(p[0].role, "codes") != 0)
return RAD_E_UNSUPPORTED;
for (int i = 1; i < 3; ++i)
if (p[i].dtype != (i == 1 ? RAD_E8M0 : RAD_U8) || p[i].kind != RAD_PLANE_TILED ||
p[i].block[0] != 1 || p[i].block[1] != 32 ||
(i == 1 ? std::strcmp(p[i].role, "scale") != 0
: std::strcmp(p[i].role, "meta") != 0))
return RAD_E_UNSUPPORTED;
if (!w || w->cols <= 0) return RAD_E_SHAPE;
const int64_t C = w->cols;
const int64_t ng = (C + 31) / 32;
const uint8_t* codes = (const uint8_t*)planes[0];
const uint8_t* scale = (const uint8_t*)planes[1];
const uint8_t* meta = (const uint8_t*)planes[2];
const int64_t codes_row = rad_enc_row_bytes(RAD_FP4E2M1, C);
for (int64_t r = 0; r < rows; ++r) {
const uint8_t* cr = codes + (row0 + r) * codes_row;
const uint8_t* sr = scale + (row0 + r) * ng;
const uint8_t* mr = meta + (row0 + r) * ng;
float* orow = out + r * C;
for (int64_t j = 0; j < C; ++j) {
const uint8_t c = (uint8_t)rad_load_bits(cr, 4, j);
const uint8_t mb = mr[j >> 5];
const int k = (mb >> (2 * ((j & 31) >> 3))) & 3;
orow[j] = rad_fp4e2m1_to_f32(c) * rad_e8m0_to_f32(sr[j >> 5]) *
(1.0f + 0.25f * (float)k);
}
}
return RAD_OK;
}
} // namespace
const RadQuantizerInfo& m2xfp_info() {
static const RadQuantizerInfo q = {
"m2xfp4",
"M2XFP: OCP 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 exponent itself searched over a bias {-1, 0, 1}, widened to "
"{-2, ..., 2} by wide=1, and absorbed into its byte (adaptive=0 pins the bias at 0); "
"4.5 bits an element, weights only, adapted from arXiv 2601.19213",
kM2xfpOptions, (int)(sizeof kM2xfpOptions / sizeof kM2xfpOptions[0]),
m2xfp_encoding, m2xfp_row_block, m2xfp_quantize, m2xfp_decode,
};
return q;
}
} // namespace lq
+12
View File
@@ -0,0 +1,12 @@
/* lq_m2xfp.h -- the `m2xfp4` quantiser: M2XFP, a metadata-augmented Microscaling format
* (arXiv 2601.19213), weight side only. lq_m2xfp.cpp says how it quantises and decodes.
*/
#pragma once
#include "rad_quant.h"
namespace lq {
/* The quantiser's table row, for lq_registry.cpp. */
const RadQuantizerInfo& m2xfp_info();
} // namespace lq
+1
View File
@@ -81,5 +81,6 @@ inline int64_t gather_units(const float* w, int64_t N, int64_t K, int64_t unit,
const RadQuantizerInfo& awq_info();
const RadQuantizerInfo& autoround_info();
const RadQuantizerInfo& paroquant_info();
const RadQuantizerInfo& m2xfp_info();
} /* namespace lq */
+7 -3
View File
@@ -4,11 +4,14 @@
* grid point, `gptq` feeds each column's rounding error into later columns, `awq` scales the input
* channels the activations say matter, `autoround` descends on the rounding itself and `paroquant`
* first learns a rotation of the input channels. They share the grid options, so anything added to
* the grid is available to all. Two are not over a grid: `ggml` writes llama.cpp's formats by
* llama.cpp's own searches (lq_ggml.h), and `cast` converts a weight to another float dtype.
* the grid is available to all. Three are not over a grid: `ggml` writes llama.cpp's formats by
* llama.cpp's own searches (lq_ggml.h), `cast` converts a weight to another float dtype, and
* `m2xfp4` quantises on the MXFP4 grid itself but stores a metadata plane beside it, a scheme of
* its own that it decodes (lq_m2xfp.h).
*/
#include "lq_ggml.h"
#include "lq_gptq.h"
#include "lq_m2xfp.h"
#include "lq_quant.h"
#include "lq_common.h"
#include "rad_plugin.h"
@@ -244,6 +247,7 @@ const std::vector<const RadQuantizerInfo*>& table() {
v.push_back(&autoround_info());
v.push_back(&paroquant_info());
v.push_back(&ggml_quantizer);
v.push_back(&m2xfp_info());
return v;
}();
return t;
@@ -256,7 +260,7 @@ const RadPluginInfo kInfo = {
"the built-in quantisers: round-to-nearest, GPTQ, AWQ, AutoRound and ParoQuant over any "
"integer, float or codebook grid, with grouped, blocked, two-level and shared-exponent scales "
"and a Hadamard, permutation or Givens transform; llama.cpp's legacy, K- and I-quants by its "
"own searches; and a plain float cast (spec.md §4.5)",
"own searches; M2XFP's metadata-augmented MXFP4; and a plain float cast (spec.md §4.5)",
"host"
};
+4
View File
@@ -148,6 +148,10 @@ set(R4D_UNITS
"r4d_gemm_mxfp4a8_nt_m64|"
"r4d_gemm_mxfp4a8_tiled|"
"r4d_gemm_mxfp4a8_decode|"
# M2XFP4 (arXiv 2601.19213 §4.4.2): the decode and tiled rows at the m2xfp4 encoding, one meta
# plane more. Same bands and fold as the OCP rows; the meta multipliers ride r4d_m2xfp4.h's table.
"r4d_gemm_m2xfp4a8_tiled|"
"r4d_gemm_m2xfp4a8_decode|"
# Block-scaled FP8 (the format Qwen3.8-27B-FP8 ships in). The 128x128 block is fixed by the
# checkpoint, and the entry points reject a mismatch.
"r4d_gemm_fp8a16_nt_m1|"
+26 -2
View File
@@ -598,6 +598,30 @@ int r4d_gemm_mxfp4a8_tiled_group(void);
// scratch, which only the plugin ABI provides.
int r4d_gemm_mxfp4a8_decode_max_m(void);
// M2XFP4 weight, fp8 activation: the MXFP4 rows at the paper's weight-side Sg-EM (arXiv 2601.19213
// §4.4.2). Beside each E8M0 exponent per 32 K (whose adaptive bias the quantiser already folded
// in) the weight carries one meta byte per (row, 32 of K): four two-bit subgroup multipliers, the
// subgroup s covering columns [8s, 8s+8) of the group, value k_s in 0..3. The exact weight is
// e2m1mag[c&7] * sign(c) * 2^(scale-127) * (1 + k_s/4); r4d_m2xfp4.h folds it into the same e4m3
// staging bytes through a second table index, so the fold, the Wref epilogue and the activation
// scale grids are the MXFP4 kernels'. `wm` is the [K/32][N] meta plane, `ldws` its row pitch (0 =
// N); the k=3 multipliers on odd-mantissa codes round as r4d_m2xfp4.h documents, <= 2^-4 relative.
void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws, long wm, long wref, long c,
int M, int K, int N, int TN, int as_group, int as_rs, long stream,
int ldws = 0, int ldc = 0);
void r4d_m2xfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda = 0);
long r4d_m2xfp4a8_tile_a_bytes(int M, int K);
int r4d_gemm_m2xfp4a8_tiled_group(void);
// The decode band (M <= 128) is r4d_rad_gemm_m2xfp4a8_decode only, as for mxfp4a8: the split
// partial and the arrival counters are the plugin ABI's. The raw entry takes the scratch that
// carries both: the fp32 split partial with the counters in its tail (m2d_partial_bytes; null
// runs unsplit only at KS 1).
void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws, long wm, long wref, long c,
int M, int K, int N, int KS, int BK, int NT, int as_group,
int as_rs, long scratch, long scratch_bytes, long stream,
int lda = 0, int ldws = 0, int ldc = 0);
int r4d_gemm_m2xfp4a8_decode_max_m(void);
// ---- Block-scaled FP8, as checkpoints ship it -------------------------------------------------
//
// Reads the weight as safetensors stores it: `<linear>.weight` F8_E4M3 row-major [N][K] and
@@ -633,8 +657,8 @@ int r4d_gemm_fp8a16_nt_m1_block(void);
int r4d_gemm_fp8a16_nt_m1_max_m(void);
// `a` is E4M3 [M][K] with `ascale` f32 [M][ceil(K/128)], r4d_quant_act_fp8's output. `scratch` is
// the split-K partial plane; 0 runs the launch unsplit (correct, slower). Size it with the query,
// which returns 0 when this shape will not split.
// the split-K partial planes with the finisher's arrival counters in the tail; 0 runs the launch
// unsplit (correct, slower). Size it with the query, which always includes the counters.
//
// Split-K is not bit-comparable across settings: ksplit repartitions K, so the accumulation order
// differs. Two runs of the same binary still agree.
+46 -6
View File
@@ -257,7 +257,10 @@ enum {
/* The same GEMM's 5-bit expert weight: per row, R4D_DT_MOEW4's nibble plane of the codes' low
* four bits (the magnitude), then the sign bits, one dword per 32 elements in the order the
* kernel merges them (r4d_layout.cpp, moew5_row). A row is 5K/8 bytes. */
R4D_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8
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
};
/* The grouped MoE GEMM's code tables, as the four dwords w4_e4m3's byte permutes read
@@ -343,18 +346,55 @@ struct R4dMvCfg { int rb; };
/* The MXFP4 tiled GEMM's one axis: compiled arms of one template. 0 is the M crossover (TN=4 from
* M >= 2048), which needs M. */
static const int64_t kMxTn[] = { 0, 2, 4 };
static const RadTunable tGemmMxfp4Tiled[] = {
{ "tn", kMxTn, (int)(sizeof kMxTn / sizeof kMxTn[0]), 0,
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 2048" },
};
/* The MXFP4 decode GEMM's axes. 0 on each is the kernel's own rule (r4d_gemm_mxfp4a8_decode.hip);
* `nt` 1 streams the weight past the caches, 2 loads it plainly. The M2XFP4 rows declare the same
* axes (r4d_rows.cpp) and resolve them through the same readers below, which sit in this header so
* a kernel unit links without the declaration side -- the r4d_emu build compiles the units alone. */
static const int64_t kMxDecKs[] = { 0, 1, 2, 4, 8, 16 };
static const int64_t kMxDecBk[] = { 0, 64, 128 };
static const int64_t kMxDecNt[] = { 0, 1, 2 };
static const RadTunable tGemmMxfp4Decode[] = {
{ "ks", kMxDecKs, (int)(sizeof kMxDecKs / sizeof kMxDecKs[0]), 0, "split-K workgroups a column block. 0 = the fill rule" },
{ "bk", kMxDecBk, (int)(sizeof kMxDecBk / sizeof kMxDecBk[0]), 0, "K slab in bytes. 0 = 128, or 64 for a wide unsplit DTM 4" },
{ "nt", kMxDecNt, (int)(sizeof kMxDecNt / sizeof kMxDecNt[0]), 0, "weight loads: 1 non-temporal, 2 plain. 0 = by weight size" },
};
/* The tuned configuration (r4d_rows.cpp's TUNE), inline so the kernel units carry it: the core
* appends the row's tuned point to RadArgs::p; a key absent falls to the axis default above. */
static inline int64_t r4d_tune_i(const RadArgs* a, const RadTunable* tab, int n, const char* key) {
long long v = 0;
if (rad_args_geti(a, key, &v)) return v;
for (int i = 0; i < n; ++i)
if (!std::strcmp(tab[i].key, key)) return tab[i].deflt;
return 0;
}
extern "C" {
/* -- the tuned configuration (r4d_rows.cpp) --
*
* The core picked a point in the space the row declared and appended it to RadArgs::p. These read
* it back, falling to the axis's default (defined once, in the RadTunable table) when a caller
* supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot
* fail: the loader refuses a plugin whose default is not one of the axis's values. */
* it back, falling to the axis's default (defined once, above) when a caller supplied none, so a
* checker with no tuned key runs what an untuned install runs. They cannot fail: the loader
* refuses a plugin whose default is not one of the axis's values. */
void r4d_cfg_gemm (const RadArgs*, struct R4dGemmCfg*);
void r4d_cfg_tiled (const RadArgs*, struct R4dTileCfg*);
void r4d_cfg_prefill(const RadArgs*, struct R4dTileCfg*);
void r4d_cfg_mxfp4_tiled(const RadArgs*, struct R4dMxTileCfg*);
void r4d_cfg_mxfp4_decode(const RadArgs*, struct R4dMxDecCfg*);
inline void r4d_cfg_mxfp4_tiled(const RadArgs* a, struct R4dMxTileCfg* out) {
out->tn = (int)r4d_tune_i(a, tGemmMxfp4Tiled, (int)(sizeof tGemmMxfp4Tiled / sizeof tGemmMxfp4Tiled[0]), "tn");
}
inline void r4d_cfg_mxfp4_decode(const RadArgs* a, struct R4dMxDecCfg* out) {
out->ks = (int)r4d_tune_i(a, tGemmMxfp4Decode, (int)(sizeof tGemmMxfp4Decode / sizeof tGemmMxfp4Decode[0]), "ks");
out->bk = (int)r4d_tune_i(a, tGemmMxfp4Decode, (int)(sizeof tGemmMxfp4Decode / sizeof tGemmMxfp4Decode[0]), "bk");
out->nt = (int)r4d_tune_i(a, tGemmMxfp4Decode, (int)(sizeof tGemmMxfp4Decode / sizeof tGemmMxfp4Decode[0]), "nt");
}
void r4d_cfg_split (const RadArgs*, struct R4dSplitCfg*);
void r4d_cfg_ar (const RadArgs*, struct R4dArCfg*);
/* Whether the four-rank fused junction takes its tail form from 5 rows (the row's `tail` axis). */
+32 -41
View File
@@ -15,7 +15,8 @@
// 2. The weight is the WMMA A operand on both tiles, so D is C^T of `C[M,N] = A[M,K] @ W[N,K]^T`
// and a lane's eight accumulator slots are eight weight rows of one activation row.
// 3. Split-K uses the caller's scratch (nothing on a launch path allocates), sized by
// r4d_gemm_fp8a8_nt_m16_scratch(). The summation order is fixed.
// r4d_gemm_fp8a8_nt_m16_scratch(): the split partial planes with the finisher's arrival
// counters in the tail. The summation order is fixed.
// 4. C is bf16, like every GEMM in this library.
//
// Load-bearing: the padded LDS row pitch (r4d_fp8_wmma.h `lds_pitch`), the one-K-tile-ahead
@@ -35,7 +36,6 @@
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <mutex>
#include <type_traits>
@@ -560,9 +560,9 @@ __device__ __forceinline__ void gemm_fp8a8_body(
// The z loop runs in fixed ascending order with no atomic on an accumulator, so the result is
// bit-identical to the separate reduce and deterministic.
//
// The counters are a small allocation keyed on (stream, output) (`split_ctr`), not the caller's
// scratch, which other ops overwrite. The self-reset keeps them zero, which is sound only while
// launches sharing a counter block never overlap; see split_ctr.
// The counters are the caller's scratch tail past the split partials (see kMaxCtr), zeroed
// beside each launch: the engine hands the op a scratch slice no unordered launch shares, and
// the self-reset keeps them zero through the launch.
if (ck && Ctr) {
// Every thread's stores must be visible device-wide before the arrival is published: a
// per-thread fence, then the barrier.
@@ -844,36 +844,15 @@ void gemm_8a8_prefill_kernel(const uint8_t* __restrict__ A, const float* __restr
// Double-buffering the narrow tile is ~10% slower even where it fits (MW = 2): the tile is short
// of LDS, not waiting on the barrier.
// The finisher's arrival counters, one per grid.x column (see the finisher). Zeroed once and kept
// zero by the finisher. If allocation fails, the caller falls back to the separate reduce kernel,
// which computes the same bytes.
// The finisher's arrival counters, one per grid.x column (see the finisher). They ride the op's
// scratch tail past the split partials, as the mxfp4 decode's counters do (mxd_partial_bytes): the
// scratch is a declared op buffer a recorded pass relocates with the other operands, where the
// per-(stream, output) library allocation this replaced (`split_ctr`) was a pointer baked into
// the recorded kernarg that a replaying pass could not relocate. Beyond kMaxCtr columns, a short
// scratch, or a failed zero, the separate reduce kernel computes the same bytes.
constexpr uint32_t kMaxCtr = 8192;
/* One counter block per (stream, output), so concurrent launches never share one (sharing would
* mean a hang or a wrong answer). Launches overlap across streams (`rad_lane`) or on one stream
* (rad_kernel_concurrent); overlapping launches on one stream write disjoint outputs, and launches
* sharing an output on one stream are ordered by their dependency. A step has a few dozen distinct
* outputs at fixed arena addresses, so this is a few dozen 32 KiB blocks, allocated once. A block
* is never freed: a recorded pass replays the pointer. */
unsigned int* split_ctr(RadStream s, const void* out) {
static std::mutex m;
static std::map<std::pair<RadStream, const void*>, unsigned int*> blocks;
std::lock_guard<std::mutex> lk(m);
const auto key = std::make_pair(s, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
/* Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has
* finished when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it
* runs on the null stream, which a non-blocking stream does not wait for, so wait here. */
if (hipMemset(p, 0, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, (unsigned int*)p);
return (unsigned int*)p;
}
// The narrow tile's wave count MW, which is its M tile: the wave grid is MW x 1, so a block covers
// MW*16 weight rows and the grid over N is N/(MW*16). The rule is fitted together with
// kSplitTarget (which shapes split decides whether narrow or wide blocks win) on the shapes the
@@ -998,9 +977,12 @@ extern "C" void r4d_gemm_fp8a8_pin_nt(int nt) {
g_nt_force.store(v, std::memory_order_relaxed);
}
// Bytes of f32 scratch one r4d_gemm_fp8a8_nt_m16 call needs, or 0 when it will not split. The
// caller may pass more, or none (the launch then runs unsplit: correct but slow, and unreported).
// The bound is max_m() so the query and the band cannot drift apart.
// Bytes of f32 scratch one r4d_gemm_fp8a8_nt_m16 call needs, or 0 when it will not split, plus
// the arrival counters (kMaxCtr words) in the tail, as the mxfp4 decode's mxd_partial_bytes.
// The caller may pass more, or none (the launch then runs unsplit: correct but slow, and
// unreported). The bound is max_m() so the query and the band cannot drift apart. The counters
// are reserved whether or not this bound splits: the launch decides its own split at its own M,
// and the counters must fit the arena this query sized.
//
// `split_n` (0: N) is the width the split is chosen for. The split depends on N alone, and it
// fixes the order K partials are summed in, so a row slice of a wider linear (N rows of a
@@ -1011,7 +993,8 @@ static long m16_scratch(int M, int K, int N, int split_n) {
uint32_t ck = 0;
const uint32_t k2 = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K,
(uint32_t)M, &ck);
return k2 > 1 ? (long)k2 * M * N * (long)sizeof(float) : 0;
return (k2 > 1 ? (long)k2 * M * N * (long)sizeof(float) : 0) +
(long)kMaxCtr * (long)sizeof(unsigned int);
}
extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) {
return m16_scratch(M, K, N, 0);
@@ -1068,10 +1051,18 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
* the arrival counter, and the finisher hangs. */
const bool full = ((uint32_t)N % fm == 0) && ((uint32_t)M % (nt * 16u) == 0) &&
(K % (int)kBlock == 0);
// The finisher needs one counter per column; beyond kMaxCtr or on allocation failure, the
// separate reduce kernel computes the same bytes.
unsigned int* const ctr =
(ksplit > 1 && gx <= kMaxCtr) ? split_ctr(stream, (const void*)c) : nullptr;
// The finisher's counters ride the scratch tail past the split partials and are zeroed here,
// so every launch enters with them zero however the last launch left them or whatever else
// wrote the arena. Beyond kMaxCtr columns, a short scratch, or a failed zero, the separate
// reduce kernel computes the same bytes.
unsigned int* ctr = nullptr;
const long ctr_bytes = (long)kMaxCtr * (long)sizeof(unsigned int);
if (ksplit > 1 && gx <= kMaxCtr && scratch && scratch_bytes >= need + ctr_bytes) {
ctr = (unsigned int*)(scratch + need);
if (hipMemsetAsync(ctr, 0, (size_t)gx * sizeof(unsigned int),
(hipStream_t)stream) != hipSuccess)
ctr = nullptr;
}
#define R4D_F8D(f, mw_, nt_, fk_, i8_) \
emit_rc = R4D_EMIT(stream, \
+651
View File
@@ -0,0 +1,651 @@
// r4d_gemm_m2xfp4a8_decode.hip - r4d_gemm_m2xfp4a8_decode: the M2XFP4 x fp8 GEMM for the decode
// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout,
// fold and split of r4d_gemm_mxfp4a8_decode, and the paper's weight-side Sg-EM (arXiv 2601.19213
// §4.4.2) on top: per group of 32 K the weight carries, beside its E8M0 exponent (whose adaptive
// bias is already folded in), one meta byte of four two-bit subgroup multipliers k_s. The exact
// weight is e2m1mag[c&7] * sign(c) * 2^(scale-127) * (1 + k_s/4); r4d_m2xfp4.h folds the
// (1 + k_s/4) * 2^-d into the e4m3 byte through a second table index, so the WMMA sees the same
// bytes it would for MXFP4 and everything downstream of the fold -- the Wref epilogue, the
// activation scale grids, the split -- is the mxfp4 kernel's unchanged.
//
// The meta byte is staged beside the exponent byte: one byte per (row, 32 of K), in the scale
// plane's [K/32][N] order and row pitch, in the tail of the same stored weight (the relayout
// appends it after the fragment-order codes, r4d_layout.cpp), so the staging reads it with the
// codes' and exponents' own geometry and the weight stream grows by one byte per sixteen -- the
// traffic the row gives up for the extra half stop of precision.
//
// The fold's bound: Wref[n] is the row's largest exponent byte as for MXFP4, so d >= 0 holds for
// every block, and the largest element any table cell then holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d
// -- an e4m3 normal at every d >= 0 (r4d_m2xfp4.h). Nothing else moves: the split, slab and load
// rule, the fused last-arriver reduction and its counters, the scratch contract and the
// concurrency promise are the mxfp4 decode row's, with this row's own state (its counters are
// keyed on the output, like the original's).
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_m2xfp4.h"
// bf16 output as uint16 pairs, the emulator-compatible spelling the MoE units use: the OCP rows
// read __hip_bfloat16 from hip_bf16.h, which the emulator's shim does not carry, and the bytes are
// the same -- bf16x2_rne_nan and f32_to_bf16 round as it does (r4d_common.h).
#include <cstdint>
#include <map>
#include <mutex>
#include <stdexcept>
#define R4D_M2D_DWN 8 // waves per block; the N tile is DWN*16 = 128 wide
#define R4D_M2D_MTILE 16
#define R4D_M2D_MAX_TM 8 // M <= 128
#define R4D_M2D_PAD 8
#define R4D_M2D_MAX_KS 16
#define R4D_M2D_MAX_N 36864 // the counter block's width; a 27B gate_up at TP=1 is 34816
typedef int m2d_v2i __attribute__((ext_vector_type(2)));
typedef unsigned m2d_u2 __attribute__((ext_vector_type(2)));
typedef unsigned m2d_u4 __attribute__((ext_vector_type(4)));
typedef float m2d_f4 __attribute__((ext_vector_type(4)));
template <bool NT, typename T>
static __device__ __forceinline__ T m2d_ld(const T* p) {
if constexpr (NT) return __builtin_nontemporal_load(p);
else return *p;
}
// ---- shared by both kernels: the scale grid at a 128 boundary, and the epilogue.
//
// The accumulator is C transposed: the WMMA takes the weight fragment as A and the activation as B
// (same register layout), so a lane's accumulator for M fragment i holds one row, m = 16i + col,
// and eight consecutive columns n0 + 16*wave + kb8 + e. A lane needs one activation scale per row,
// and writes its eight outputs as one 16-byte store (one 32-byte store of partials).
// The (row, 128) scale grid: thread t < ROWS owns row t, loads the next boundary's two scales a
// boundary early and writes s_prev / s_next to LDS at the boundary (published by the staging
// barrier). A zero next block keeps the carried scale; after a zero block the carried scale is
// looked up from the grid.
static __device__ __forceinline__ float m2d_ratio(float ns, float np, const float* __restrict__ row,
int kb) {
return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f;
}
template <int DTM>
static __device__ __forceinline__ void m2d_rescale(v8f (&acc)[DTM], const float* sR, int col) {
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const float r = sR[i * 16 + col];
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][e] *= r;
}
}
// The split's result: written to C when the accumulator covers all of K, else as an fp32 partial
// that the last block to arrive on this column block sums. `kb_end` is the block the split's last
// slab ends in (ABLK: the scale the accumulators are carried in).
template <int DTM, int DKS, bool ABLK>
static __device__ __forceinline__ void m2d_epilogue(
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
uint16_t* __restrict__ C, int M, int N, int ldc, int n0, int wave, int col, int kb8,
int ks, int kb_end, unsigned* s_last, float* sR) {
constexpr int NTHR = R4D_M2D_DWN * 32, BND = R4D_M2D_DWN * 16;
constexpr int ROWS = R4D_M2D_MTILE * DTM;
const int tid = threadIdx.x;
const int nb = n0 + wave * 16 + kb8; // this lane's eight columns; N % 16 == 0 keeps all or none
// Each row's final scale: the one the split's accumulators end in (ABLK), or the row's own. The
// K loop's closing barrier retired the last ratio reads.
if (tid < ROWS) {
const int m = tid < M ? tid : M - 1;
sR[tid] = ABLK ? r4d_mxfp4_carried(As + (size_t)m * as_rs, kb_end) : As[(size_t)m * as_rs];
}
__syncthreads();
float sc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) sc[i] = sR[i * 16 + col];
if constexpr (DKS == 1) {
if (nb < N) {
const m2d_u2 rb = *(const m2d_u2*)(Wref + nb);
float rf[8];
#pragma unroll
for (int e = 0; e < 8; ++e) rf[e] = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const int m = i * 16 + col;
if (m < M) {
// rounded as the bf16 store rounds, packed in whole registers (see bf16x2_rne_nan)
float v[8];
#pragma unroll
for (int e = 0; e < 8; ++e)
v[e] = ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i];
m2d_u4 o;
o.x = bf16x2_rne_nan(v[0], v[1]);
o.y = bf16x2_rne_nan(v[2], v[3]);
o.z = bf16x2_rne_nan(v[4], v[5]);
o.w = bf16x2_rne_nan(v[6], v[7]);
*(m2d_u4*)(C + (size_t)m * ldc + nb) = o;
}
}
}
return;
}
if (nb < N) {
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const int m = i * 16 + col;
if (m < M) {
m2d_f4 lo, hi;
#pragma unroll
for (int e = 0; e < 4; ++e) {
lo[e] = ABLK ? acc[i][e] * sc[i] : acc[i][e];
hi[e] = ABLK ? acc[i][e + 4] * sc[i] : acc[i][e + 4];
}
m2d_f4* dst = (m2d_f4*)(P + ((size_t)ks * M + m) * N + nb);
dst[0] = lo;
dst[1] = hi;
}
}
}
// Every thread's partial stores are ordered before the counter; then the last arriver reduces.
__threadfence();
__syncthreads();
if (tid == 0)
*s_last = __hip_atomic_fetch_add(&cnt[blockIdx.x], 1u, __ATOMIC_ACQ_REL,
__HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (*s_last != (unsigned)(DKS - 1)) return;
if (tid == 0) cnt[blockIdx.x] = 0u; // reset for the next launch
__threadfence(); // acquire, before reading the other partials
const int nhi = min(n0 + BND, N);
for (int nn = n0 + tid; nn < nhi; nn += NTHR) {
const float rf = __int_as_float((int)Wref[nn] << 23);
for (int m = 0; m < M; ++m) {
float sum = 0.f;
#pragma unroll
for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn];
C[(size_t)m * ldc + nn] = f32_to_bf16(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
}
}
}
/* Waves per SIMD for each tile shape (R4D_WAVES), by K block, M fragments and scale form: pins
* the register budget the tile was tuned at so a compiler release cannot change occupancy (LLVM 24
* would drop the DBK 64, three-fragment form from 16 waves to 12). Where a shape spilled at 256
* VGPRs, the budget is the one it reaches without spilling. The meta adds one global byte per
* staged pair to the fold's inputs and no register to the WMMA chain, so the budgets are the
* mxfp4 decode kernel's; the fold is a second table index, not a multiply. */
constexpr int m2d_waves(int dbk, int dtm, bool ablk) {
if (dbk == 64)
return dtm <= 3 ? 16 : dtm == 4 ? 12 : dtm == 5 ? 10 : dtm == 6 ? (ablk ? 9 : 10)
: dtm == 7 ? 9 : (ablk ? 8 : 9);
return dtm <= 3 ? 10 : dtm == 4 ? 8 : dtm == 5 ? (ablk ? 8 : 7) : dtm == 6 ? (ablk ? 8 : 6)
: 6;
}
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_M2D_DWN * 32) R4D_WAVES(m2d_waves(DBK, DTM, ABLK))
void r4d_gemm_m2xfp4a8_decode_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
float* __restrict__ P, unsigned* __restrict__ cnt, uint16_t* __restrict__ C,
int M, int K, int N, int as_rs, int lda, int ldws, int ldc) {
constexpr int DWN = R4D_M2D_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_M2D_MTILE * DTM;
constexpr int STR = DBK + R4D_M2D_PAD;
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
v8f acc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
float ns = 0.f, np = 0.f;
if constexpr (ABLK) {
// a split that starts mid-block meets its first boundary one slab in
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
for (int s = s_lo; s < s_hi; ++s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = m2d_ratio(ns, np, asrow, k0 >> 7);
}
// ---- A: ROWS x DBK bytes, clamped rows, 16 B a thread
#pragma unroll
for (int off = 0; off < ROWS * DBK; off += NTHR * 16) {
const int idx = off + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
*(m2d_u4*)(&sA[r * STR + c]) = *(const m2d_u4*)(A + (size_t)rc * lda + k0 + c);
}
}
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3.
// The k offset of the eight elements a lane stages is a multiple of 8 and DBK of 32, so one
// meta byte's two-bit field per row covers it whole (r4d_m2xfp4.h).
{
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
const int kstep0 = k0 / 16;
#pragma unroll
for (int off = 0; off < NTILES_T * KSTEPS_T * 32; off += NTHR * 2) {
const int sl = off + tid * 2;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8;
const int ksh = r4d_m2xfp4_kshift(kloc);
const int gn = n0 + r;
// gn is even and N % 16 == 0, so clamping to N - 2 keeps the 8 B read aligned and gc + 1 in
// bounds; the slot address is recomputed from the clamped row.
const int gc = gn < N - 2 ? gn : N - 2;
const int lanec = (lane_ & 16) | (gc & 15);
const m2d_u2 wv =
m2d_ld<NT>((const m2d_u2*)&Wp[((size_t)(gc >> 4) * ksteps_g + kstep0 + kst) * 32 +
lanec]);
const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP;
#pragma unroll
for (int q = 0; q < 2; ++q) {
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * ldws + gc + q]);
const int k = (Wm[(size_t)blk * ldws + gc + q] >> ksh) & 3;
unsigned int lo, hi;
r4d_m2xfp4_unpack8(q ? wv[1] : wv[0], d, k, &lo, &hi);
*(m2d_u2*)(&sW[(r + q) * STR + kloc]) = m2d_u2{lo, hi};
}
}
}
__syncthreads();
if constexpr (ABLK) {
if (bnd) m2d_rescale(acc, sR, col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
const int kk = step * 16 + kb8;
m2d_v2i af[DTM], wf;
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
m2d_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
}
// The one-fragment form (M <= 16), every single-sequence verify step. Same tile, fold and split as
// above, plus: the next slab's A, codes, exponents and meta bytes are loaded into registers while
// this slab computes, keeping loads in flight across barriers; a thread takes four adjacent slots
// (one 16 B load); and each row's reference exponent is read once. Bit-identical to the kernel
// above.
template <int DBK, int DKS, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_M2D_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12)
void r4d_gemm_m2xfp4a8_decode1_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
float* __restrict__ P, unsigned* __restrict__ cnt, uint16_t* __restrict__ C,
int M, int K, int N, int as_rs, int lda, int ldws, int ldc) {
constexpr int DTM = 1, VEC = 4;
constexpr int DWN = R4D_M2D_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_M2D_MTILE * DTM;
constexpr int STR = DBK + R4D_M2D_PAD;
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
constexpr int W_IT = NTILES_T * KSTEPS_T * 32 / (NTHR * VEC);
constexpr int A_IT = (ROWS * DBK + NTHR * 16 - 1) / (NTHR * 16);
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
v8f acc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
float ns = 0.f, np = 0.f;
if constexpr (ABLK) {
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
// per-thread slot geometry, fixed across slabs; the meta shift with it, since an eight-element
// slot's offset inside its 32-column group does not move
int s_r[W_IT], s_kst[W_IT], s_kloc[W_IT], s_gc[W_IT], s_lanec[W_IT], s_ksh[W_IT][VEC];
int s_ref[W_IT][VEC];
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
const int sl = it * NTHR * VEC + tid * VEC;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15);
const int gn = n0 + r;
const int gc = gn < N - VEC ? gn : N - VEC;
s_r[it] = r; s_kst[it] = kst; s_kloc[it] = kst * 16 + (lane_ >> 4) * 8;
s_gc[it] = gc; s_lanec[it] = (lane_ & 16) | (gc & 15);
#pragma unroll
for (int q = 0; q < VEC; ++q) {
s_ref[it][q] = (int)Wref[gc + q];
s_ksh[it][q] = r4d_m2xfp4_kshift(s_kloc[it]);
}
}
typedef unsigned wv_t __attribute__((ext_vector_type(VEC)));
wv_t rw[W_IT];
int rd[W_IT][VEC], rk[W_IT][VEC];
m2d_u4 ra[A_IT];
auto load = [&](int s) {
const int k0 = s * DBK;
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1;
ra[j] = *(const m2d_u4*)(A + (size_t)rc * lda + k0 + c);
}
}
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
const size_t slot =
((size_t)(s_gc[it] >> 4) * ksteps_g + kstep0 + s_kst[it]) * 32 + s_lanec[it];
rw[it] = m2d_ld<NT>((const wv_t*)&Wp[slot]);
const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP;
#pragma unroll
for (int q = 0; q < VEC; ++q) {
rd[it][q] = (int)Ws[(size_t)blk * ldws + s_gc[it] + q];
rk[it][q] = (int)Wm[(size_t)blk * ldws + s_gc[it] + q];
}
}
};
auto store = [&]() {
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
*(m2d_u4*)(&sA[r * STR + c]) = ra[j];
}
}
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
#pragma unroll
for (int q = 0; q < VEC; ++q) {
unsigned int lo, hi;
r4d_m2xfp4_unpack8(rw[it][q], r4d_mxfp4_fold_d(s_ref[it][q], rd[it][q]),
(rk[it][q] >> s_ksh[it][q]) & 3, &lo, &hi);
*(m2d_u2*)(&sW[(s_r[it] + q) * STR + s_kloc[it]]) = m2d_u2{lo, hi};
}
}
};
if (s_lo < s_hi) load(s_lo);
for (int s = s_lo; s < s_hi; ++s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = m2d_ratio(ns, np, asrow, k0 >> 7);
}
store();
__syncthreads();
if (s + 1 < s_hi) load(s + 1); // the next slab's loads fly across this slab's WMMAs
if constexpr (ABLK) {
if (bnd) m2d_rescale(acc, sR, col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
const int kk = step * 16 + kb8;
m2d_v2i af[DTM], wf;
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
m2d_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
}
namespace {
// The arrival counters now ride the op's scratch (m2d_partial_bytes); the per-output library
// allocation this replaced was a pointer a recorded pass could not relocate.
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule).
// The mxfp4 decode kernel's rule: the meta byte adds weight-stream traffic, not work at any of the
// points the rule trades, so the rule itself carries over. Shared by the launch and the scratch
// hook so the sized partial is the one written.
struct M2dPlan { int ks, bk; bool nt; };
M2dPlan m2d_plan(int M, int K, int N, int KS, int BK, int NT) {
const int nblk = (N + R4D_M2D_DWN * 16 - 1) / (R4D_M2D_DWN * 16);
const int tm = (M + R4D_M2D_MTILE - 1) / R4D_M2D_MTILE;
M2dPlan p;
int ks = 1;
const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40);
while (ks < R4D_M2D_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
while (ks < R4D_M2D_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
p.ks = KS > 0 ? KS : ks;
// 64-wide slabs where LDS per block would cost resident blocks: DTM 4 unsplit on 110+ column
// blocks, and DTM 8 on those or at a split of 4 or more.
const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4));
p.bk = BK > 0 ? BK : (slab64 ? 64 : 128);
p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20));
if (K % p.bk) { // a slab may not run past K
p.bk = 64;
if (p.ks == 2) p.ks = 4;
}
return p;
}
/* The scratch: the split partial when ks > 1, then the arrival counters. The counters live in
* the scratch rather than in a library-owned allocation because the scratch is a declared op
* buffer: a recorded pass relocates it with the other operands, while a pointer the library
* allocated itself is baked into the recorded kernarg and cannot be relocated. */
constexpr size_t m2d_ctr_count() { return R4D_M2D_MAX_N / (R4D_M2D_DWN * 16); }
long m2d_partial_bytes(int M, int N, int ks) {
return (ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0) +
(long)m2d_ctr_count() * (long)sizeof(unsigned);
}
void m2d_launch(long a, long ascale, long wq, long ws, long wm, long wref, long c, int M, int K,
int N, int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch,
long scratch_bytes, int lda, int ldws, int ldc) {
// A part of a partitioned weight reads windows of larger planes; 0 means the plane's own width,
// as r4d_gemm_mxfp4a8_nt_m64's launcher spells it.
if (!lda) lda = K;
if (!ldws) ldws = N;
if (!ldc) ldc = N;
if (M < 1 || M > R4D_M2D_MTILE * R4D_M2D_MAX_TM)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: M must be 1..128");
if (N < 16 || N % 16 || N > R4D_M2D_MAX_N)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: N must be a multiple of 16 up to 36864");
if (K < 64 || K % 64)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: K must be a multiple of 64");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the activation scale is per row or per "
"128 of K");
const M2dPlan pl = m2d_plan(M, K, N, KS, BK, NT);
const int ks = pl.ks, bk = pl.bk;
if (ks != 1 && ks != 2 && ks != 4 && ks != 8 && ks != 16)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: KS must be 1, 2, 4, 8 or 16");
if (bk != 64 && bk != 128)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: BK must be 64 or 128");
if (!scratch || scratch_bytes < m2d_partial_bytes(M, N, ks))
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the op's scratch is shorter than the split "
"partial and the arrival counters; the scratch hook sizes it");
float* P = (float*)scratch;
unsigned* cnt = (unsigned*)((unsigned char*)P +
(ks > 1 ? (size_t)ks * (size_t)M * (size_t)N * sizeof(float) : 0));
/* Every launch enters with the counters zero: the scratch is shared across ops, and a replayed
* pass writes the same slots. One 1.1 KiB memset beside the launch is not measurable. */
if (hipMemsetAsync(cnt, 0, m2d_ctr_count() * sizeof(unsigned), (hipStream_t)stream) != hipSuccess)
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: zeroing the arrival counters failed");
const bool ablk = as_group == 128, nt = pl.nt;
const int nblk = (N + R4D_M2D_DWN * 16 - 1) / (R4D_M2D_DWN * 16);
const int tm = (M + R4D_M2D_MTILE - 1) / R4D_M2D_MTILE;
hipStream_t st = (hipStream_t)stream;
dim3 grid(nblk, 1, ks), block(R4D_M2D_DWN * 32);
auto Ap = (const unsigned char*)a;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Mp = (const unsigned char*)wm;
auto Rp = (const unsigned char*)wref;
auto Cp = (uint16_t*)c;
#define M2D_L(BK_, KS_, TM_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_decode_kernel<BK_, KS_, TM_, NT_, AB_>), grid, block, 0, \
st, Ap, Sp, Wp, Zp, Mp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
#define M2D_L1(BK_, KS_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_decode1_kernel<BK_, KS_, NT_, AB_>), grid, block, 0, st, \
Ap, Sp, Wp, Zp, Mp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
#define M2D_AB(BK_, KS_, TM_, NT_) \
{ if (ablk) M2D_L(BK_, KS_, TM_, NT_, true); else M2D_L(BK_, KS_, TM_, NT_, false); }
#define M2D_NT(BK_, KS_, TM_) \
{ if (nt) M2D_AB(BK_, KS_, TM_, true) else M2D_AB(BK_, KS_, TM_, false) }
#define M2D_AB1(BK_, KS_, NT_) \
{ if (ablk) M2D_L1(BK_, KS_, NT_, true); else M2D_L1(BK_, KS_, NT_, false); }
#define M2D_NT1(BK_, KS_) { if (nt) M2D_AB1(BK_, KS_, true) else M2D_AB1(BK_, KS_, false) }
#define M2D_TM(BK_, KS_) \
{ switch (tm) { case 1: M2D_NT1(BK_, KS_) break; case 2: M2D_NT(BK_, KS_, 2) break; \
case 3: M2D_NT(BK_, KS_, 3) break; case 4: M2D_NT(BK_, KS_, 4) break; \
case 5: M2D_NT(BK_, KS_, 5) break; case 6: M2D_NT(BK_, KS_, 6) break; \
case 7: M2D_NT(BK_, KS_, 7) break; default: M2D_NT(BK_, KS_, 8) break; } }
#define M2D_KS(BK_) \
{ switch (ks) { case 1: M2D_TM(BK_, 1) break; case 2: M2D_TM(BK_, 2) break; \
case 4: M2D_TM(BK_, 4) break; case 8: M2D_TM(BK_, 8) break; \
default: M2D_TM(BK_, 16) break; } }
if (bk == 64) M2D_KS(64) else M2D_KS(128)
#undef M2D_KS
#undef M2D_TM
#undef M2D_NT1
#undef M2D_AB1
#undef M2D_NT
#undef M2D_AB
#undef M2D_L1
#undef M2D_L
}
} // namespace
extern "C" int r4d_gemm_m2xfp4a8_decode_max_m(void) { return R4D_M2D_MTILE * R4D_M2D_MAX_TM; }
// The raw entry, as r4d_gemm_fp8a8_nt_m16: plain C ABI for a caller that sizes the split itself.
// The scratch is the split partial m2d_partial_bytes(M, N, KS) long; `scratch` null runs unsplit
// only when KS is 1.
extern "C" void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws, long wm, long wref,
long c, int M, int K, int N, int KS, int BK, int NT,
int as_group, int as_rs, long scratch,
long scratch_bytes, long stream, int lda, int ldws,
int ldc) {
m2d_launch(a, ascale, wq, ws, wm, wref, c, M, K, N, KS, BK, NT, as_group, as_rs, stream, scratch,
scratch_bytes, lda, ldws, ldc);
}
// ============================================================== the plugin ABI entry point
extern "C" int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
if (g.M > r4d_gemm_m2xfp4a8_decode_max_m() || g.N > R4D_M2D_MAX_N) return R4D_NO(RAD_E_SHAPE);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
if (rc != RAD_OK) return rc;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
const long long kb = (g.K + 127) / 128;
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order: the part
// window opens at n0 of it as of the exponent plane, at n0 * K / 2 of the codes.
const long meta0 = (long)g.N * g.K / 2;
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
R4D_TRY("gemm_m2xfp4a8_decode",
m2d_launch(r4d_addr(g.a) + p * g.K, r4d_addr(g.ascale) + (long)(p * kb * 4),
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
r4d_addr(g.b) + meta0 + n0, r4d_addr(g.bref) + n0,
r4d_addr(g.y) + n0 * 2,
(int)g.M, (int)g.K, (int)np, t.ks, t.bk, t.nt, as_group, as_rs,
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes,
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N));
}
return RAD_OK;
}
/* The op's scratch size. A narrower M can split wider than the band's widest M, so the size is the
* widest split over the band times the widest M, an upper bound for every launch. Parts of a
* partitioned weight split at their own N and run in turn sharing the scratch, so the bound is the
* largest part's. */
extern "C" int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
const long long K = r4d_geti_or(a, "K", 0);
if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_m2xfp4a8_decode_max_m()) return 0;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
long long bound[4];
mx_part_bounds(N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound);
int64_t worst = 0;
for (int i = 0; i < 3; ++i) {
const long long np = bound[i + 1] - bound[i];
if (np < 16) continue;
int ks = 1;
for (int m = 1; m <= (int)M; ++m) {
const int k = m2d_plan(m, (int)K, (int)np, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
}
const int64_t b = (int64_t)m2d_partial_bytes((int)M, (int)np, ks);
if (b > worst) worst = b;
}
const int64_t ctr = (int64_t)m2d_ctr_count() * (int64_t)sizeof(unsigned);
return worst > ctr ? worst : ctr;
}
+373
View File
@@ -0,0 +1,373 @@
// r4d_gemm_m2xfp4a8_tiled.hip - r4d_gemm_m2xfp4a8_tiled: the M2XFP4 x fp8 GEMM for prefill row
// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout, fold and
// tile of r4d_gemm_mxfp4a8_tiled, plus the weight-side Sg-EM (arXiv 2601.19213 §4.4.2) the decode
// row decodes: per group of 32 K a meta byte of four two-bit subgroup multipliers, folded into the
// e4m3 staging bytes through r4d_m2xfp4.h's second table index, so the WMMA chain, the Wref
// epilogue and the activation scale grids are the mxfp4 kernel's unchanged.
//
// The meta byte is staged beside the exponent byte: one byte per (weight row, 32 of K), in the
// scale plane's [K/32][N] order and row pitch, in the tail of the same stored weight (the relayout
// appends it after the fragment-order codes, r4d_layout.cpp). A staged slot's eight elements sit at
// an offset that is a multiple of 8 inside their 32-column group, so one two-bit field per slot
// covers it whole; the shift is fixed per slot across slabs and read with the geometry the scale
// dword already uses.
//
// The fold's bound: Wref[n] is the row's largest exponent byte as for MXFP4, so d >= 0 holds for
// every block, and the largest element any table cell then holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d
// -- an e4m3 normal at every d >= 0 (r4d_m2xfp4.h). The table is four times the mxfp4 one, 512
// bytes, still nothing against sW; the LDS copy widens with it.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_m2xfp4.h"
// bf16 output as uint16 pairs (the emulator-compatible spelling, r4d_common.h): the OCP
// rows read __hip_bfloat16 from hip_bf16.h, whose bytes these are.
#include <cstdint>
#include <stdexcept>
#define R4D_M2T_TM 4 // 16-row fragments per wave
#define R4D_M2T_WM 4 // waves along M
#define R4D_M2T_WN 2 // waves along N
#define R4D_M2T_PAD 8 // LDS row pad: 16 lanes reading rows 64 B apart collide 8 ways
#define R4D_M2T_NTHR (R4D_M2T_WM * R4D_M2T_WN * 32)
#define R4D_M2T_BMF (R4D_M2T_WM * R4D_M2T_TM * 16)
#define R4D_M2T_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
#define R4D_M2T_TN4_MIN_M 2048 // tn=0's crossover, see r4d_gemm_mxfp4a8_tiled.hip
typedef int m2t_v2i __attribute__((ext_vector_type(2)));
typedef unsigned m2t_u2 __attribute__((ext_vector_type(2)));
typedef unsigned m2t_u4 __attribute__((ext_vector_type(4)));
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane; writes are contiguous.
// (r4d_mxfp4a8_tile_a_kernel, shared work; this row runs its own copy so the two units stay
// independent.)
__global__ __launch_bounds__(256) void r4d_m2xfp4a8_tile_a_kernel(
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
long long slots, int lda) {
const long long o = (long long)blockIdx.x * 256 + threadIdx.x;
if (o >= slots) return;
const int ks = K / 16;
const int lane = (int)(o & 31);
const long long f = o >> 5;
const int mt = (int)(f / ks), kst = (int)(f % ks);
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
m2t_u2 v = { 0u, 0u };
if (r < M) v = *(const m2t_u2*)(A + (size_t)r * lda + k);
*(m2t_u2*)(AT + o * 8) = v;
}
template <int TN, int LBK, bool ABLK>
__global__ __launch_bounds__(R4D_M2T_NTHR) void r4d_gemm_m2xfp4a8_tiled_kernel(
const unsigned char* __restrict__ AT, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
uint16_t* __restrict__ C, int M, int K, int N, int as_rs, int ldws, int ldc) {
constexpr int TM = R4D_M2T_TM, WN = R4D_M2T_WN, NTHR = R4D_M2T_NTHR, BMF = R4D_M2T_BMF;
constexpr int NS = LBK / 16, STR = LBK + R4D_M2T_PAD, BNF = WN * TN * 16;
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
// 4 weight slots (one 16 B read) wherever the tile has enough of them, else 2 (8 B), else 1.
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
__shared__ unsigned char sW[BNF * STR];
__shared__ unsigned int sMag[128]; // kM2xfp4Mag: [16][4][2] words
__shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int wm = wave / WN, wn = wave % WN;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
const int ksteps = K / 16, Mt = (M + 15) >> 4;
if (tid < 128) sMag[tid] = (&kM2xfp4Mag[0][0][0])[tid];
// One A base per M fragment, wave-uniform: readfirstlane keeps it in an SGPR so loads take the
// SADDR form with a 32-bit lane offset. A tile past M reads the last real one.
const unsigned char* abase[TM];
#pragma unroll
for (int i = 0; i < TM; ++i) {
int mt = (m0 >> 4) + wm * TM + i;
mt = mt < Mt - 1 ? mt : Mt - 1;
abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256);
}
const unsigned int aoff = (unsigned int)lane * 8;
// The W slots this thread stages, fixed across slabs: WSLOTS adjacent rows of one (n-tile,
// k-step), so the wave reads contiguous bytes; the clamp keeps the vector read aligned. The meta
// shift moves with the slot: its eight elements' offset inside their 32-column group is
// kst*16 + (lane>>4)*8, a multiple of 8 (r4d_m2xfp4.h).
int wrow[NW], wkloc[NW], wrc[NW], wkst[NW], wlanec[NW], wksh[NW];
unsigned int wref[NW];
#pragma unroll
for (int it = 0; it < NW; ++it) {
const int sl = it * NTHR * WSLOTS + tid * WSLOTS;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % NS, ntl = rest / NS;
wrow[it] = ntl * 16 + (lane_ & 15);
wkloc[it] = kst * 16 + (lane_ >> 4) * 8;
wksh[it] = r4d_m2xfp4_kshift(wkloc[it]);
const int gn = n0 + wrow[it];
wrc[it] = gn < N - WSLOTS ? gn : N - WSLOTS;
wlanec[it] = (lane_ & 16) | (wrc[it] & 15);
wkst[it] = kst;
wref[it] = WSLOTS == 4 ? *(const unsigned int*)(Wref + wrc[it])
: WSLOTS == 2 ? *(const unsigned short*)(Wref + wrc[it])
: Wref[wrc[it]];
}
v8f acc[TM][TN];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
// ABLK: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two scales (the
// block starting there and the one before it) a boundary early.
const int trow = m0 + tid < M ? m0 + tid : M - 1;
const float* __restrict__ asrow = As + (size_t)trow * as_rs;
float ns = 0.f, np = 0.f;
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
lds_barrier(); // sMag
for (int k0 = 0; k0 < K; k0 += LBK) {
// ABLK: at a 128 boundary each row's ratio goes to LDS, published by the staging barrier below
// (sR's previous readers finished before the last slab's closing barrier). A zero block keeps
// the carried scale; after a zero block the carried scale is looked up from the grid.
const bool bnd = ABLK && k0 && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd)
sR[tid] = ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(asrow, (k0 >> 7) - 2)) / ns : 1.f;
}
// A fragments for the whole slab, one clause, consumed only at the WMMAs.
m2t_v2i af[TM][NS];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int st = 0; st < NS; ++st)
af[i][st] = *(const m2t_v2i*)(abase[i] +
(aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256)));
// W slab -> LDS, folded to e4m3. The meta bytes ride the same dword reads as the exponents.
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < NW; ++it) {
const unsigned int* src =
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
unsigned int wq[WSLOTS], wsw, wmw;
if constexpr (WSLOTS == 4) {
const m2t_u4 v = *(const m2t_u4*)src;
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
wmw = *(const unsigned int*)(Wm + (size_t)blk * ldws + wrc[it]);
} else if constexpr (WSLOTS == 2) {
const m2t_u2 v = *(const m2t_u2*)src;
wq[0] = v[0]; wq[1] = v[1];
wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
wmw = *(const unsigned short*)(Wm + (size_t)blk * ldws + wrc[it]);
} else {
wq[0] = *src;
wsw = Ws[(size_t)blk * ldws + wrc[it]];
wmw = Wm[(size_t)blk * ldws + wrc[it]];
}
#pragma unroll
for (int q = 0; q < WSLOTS; ++q) {
const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF),
(int)((wsw >> (8 * q)) & 0xFF));
const int k = (int)((wmw >> (8 * q + wksh[it])) & 3);
const int ti = (d * 4 + k) * 2;
unsigned int lo, hi;
r4d_m2xfp4_unpack8_t(wq[q], sMag[ti], sMag[ti + 1], &lo, &hi);
*(m2t_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = m2t_u2{lo, hi};
}
}
lds_barrier();
if constexpr (ABLK) {
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
if (bnd) {
#pragma unroll
for (int i = 0; i < TM; ++i) {
const float r = sR[wm * TM * 16 + i * 16 + col];
#pragma unroll
for (int j = 0; j < TN; ++j)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][j][e] *= r;
}
}
// The next boundary's scales, issued behind this slab's loads and needed a boundary later.
if ((k0 & 127) == 0 && k0 + 128 < K) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < NS; ++step) {
const int kk = step * 16 + kb8;
m2t_v2i wf[TN];
#pragma unroll
for (int j = 0; j < TN; ++j) {
const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk];
wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4);
}
// Keep one step's W fragments live at a time; otherwise the compiler hoists every step's
// loads above the first WMMA.
__builtin_amdgcn_sched_barrier(0);
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j)
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
acc[i][j]);
}
lds_barrier();
}
// Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns
// of N fragment j, one 16-byte store per (i, j). 2^(Wref[n]-127) is the float whose exponent
// field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside or all outside N.
float sc[TM];
if constexpr (ABLK) {
// the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads
sR[tid] = r4d_mxfp4_carried(asrow, (K - 1) >> 7);
lds_barrier();
#pragma unroll
for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col];
} else {
#pragma unroll
for (int i = 0; i < TM; ++i) {
const int m = m0 + wm * TM * 16 + i * 16 + col;
sc[i] = As[(size_t)(m < M ? m : M - 1) * as_rs];
}
}
#pragma unroll
for (int j = 0; j < TN; ++j) {
const int nb = n0 + wn * TN * 16 + j * 16 + kb8;
if (nb >= N) continue;
const m2t_u2 rb = *(const m2t_u2*)(Wref + nb);
#pragma unroll
for (int i = 0; i < TM; ++i) {
const int m = m0 + wm * TM * 16 + i * 16 + col;
if (m >= M) continue;
// rounded as the bf16 store rounds, packed in whole registers (see bf16x2_rne_nan)
float v[8];
#pragma unroll
for (int e = 0; e < 8; ++e) {
const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
v[e] = acc[i][j][e] * rf * sc[i];
}
m2t_u4 o;
o.x = bf16x2_rne_nan(v[0], v[1]);
o.y = bf16x2_rne_nan(v[2], v[3]);
o.z = bf16x2_rne_nan(v[4], v[5]);
o.w = bf16x2_rne_nan(v[6], v[7]);
*(m2t_u4*)(C + (size_t)m * ldc + nb) = o;
}
}
}
extern "C" int r4d_gemm_m2xfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; }
extern "C" long r4d_m2xfp4a8_tile_a_bytes(int M, int K) {
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
}
extern "C" void r4d_m2xfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda) {
if (!lda) lda = K;
if (M < 1) throw std::runtime_error("r4d m2xfp4a8_tile_a: M must be >= 1");
if (K < 16 || K % 16) throw std::runtime_error("r4d m2xfp4a8_tile_a: K must be a multiple of 16");
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
hipLaunchKernelGGL(r4d_m2xfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256),
0, (hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K,
slots, lda);
}
extern "C" void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws, long wm, long wref,
long c, int M, int K, int N, int TN, int as_group,
int as_rs, long stream, int ldws, int ldc) {
if (!ldws) ldws = N;
if (!ldc) ldc = N;
if (M < 1) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: M must be >= 1");
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: N must be a multiple of 16");
if (K < R4D_M2T_KUNIT || K % R4D_M2T_KUNIT)
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: K must be a multiple of 64");
// tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves fewer than 128 blocks
// (narrow N), where TN=2's extra blocks win.
if (TN == 0)
TN = M >= R4D_M2T_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_M2T_BMF - 1) / R4D_M2T_BMF) >= 128
? 4 : 2;
if (TN != 2 && TN != 4) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: TN must be 2 or 4");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: the activation scale is per row or per 128 of K");
const bool ablk = as_group == 128;
if (ablk && as_rs < (K + 127) / 128)
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: activation scale rows shorter than ceil(K/128)");
const bool wide_slab = TN == 2 && K % 128 == 0;
const int bnf = R4D_M2T_WN * TN * 16;
dim3 grid((N + bnf - 1) / bnf, (M + R4D_M2T_BMF - 1) / R4D_M2T_BMF), block(R4D_M2T_NTHR);
auto Ap = (const unsigned char*)at;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Mp = (const unsigned char*)wm;
auto Rp = (const unsigned char*)wref;
auto Cp = (uint16_t*)c;
hipStream_t st = (hipStream_t)stream;
#define M2T_LAUNCH(TNv, LBKv, ABv) \
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
Wp, Zp, Mp, Rp, Cp, M, K, N, as_rs, ldws, ldc)
if (TN == 4) { if (ablk) M2T_LAUNCH(4, 64, true); else M2T_LAUNCH(4, 64, false); }
else if (wide_slab) { if (ablk) M2T_LAUNCH(2, 128, true); else M2T_LAUNCH(2, 128, false); }
else { if (ablk) M2T_LAUNCH(2, 64, true); else M2T_LAUNCH(2, 64, false); }
#undef M2T_LAUNCH
}
// ============================================================== the plugin ABI entry point
// The row-major activation is re-tiled into the op's scratch and the GEMM reads it there. For a
// partitioned weight (mx_parts), each part's activation copy is re-tiled and multiplied in turn.
extern "C" int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
/* The per-row reference exponent is required, as in r4d_rad_gemm_mxfp4a8_m64. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
if (g.K % R4D_M2T_KUNIT) return R4D_NO(RAD_E_SHAPE);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
if (rc != RAD_OK) return rc;
const long long slab = r4d_m2xfp4a8_tile_a_bytes((int)g.M, (int)g.K);
if (!a->scratch || a->scratch_bytes < slab) return R4D_NO(RAD_E_INVAL);
R4dMxTileCfg t;
r4d_cfg_mxfp4_tiled(a, &t);
const long kb = (long)((g.K + 127) / 128);
const long at = (long)(uintptr_t)a->scratch;
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order; a part
// windows it at n0 of the plane, as of the exponents.
const long meta0 = (long)g.N * g.K / 2;
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
R4D_TRY("gemm_m2xfp4a8_tiled",
r4d_m2xfp4a8_tile_a(r4d_addr(g.a) + p * g.K, at, (int)g.M, (int)g.K,
(long)(uintptr_t)s, (int)(mp.lda ? mp.lda : g.K));
r4d_gemm_m2xfp4a8_tiled(at, r4d_addr(g.ascale) + p * kb * 4, r4d_addr(g.b) + n0 * g.K / 2,
r4d_addr(g.bscale) + n0, r4d_addr(g.b) + meta0 + n0,
r4d_addr(g.bref) + n0,
r4d_addr(g.y) + n0 * 2, (int)g.M, (int)g.K, (int)np, t.tn,
as_group, as_rs, (long)(uintptr_t)s, (int)g.N, (int)g.N));
}
return RAD_OK;
}
/* The op's scratch, sized at the band's widest M: the fragment-tiled activation in whole 16-row
* fragments. One copy serves every part: parts run in order on the op's stream, so a re-tile
* cannot overtake the previous part's GEMM. */
extern "C" int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0);
return (int64_t)r4d_m2xfp4a8_tile_a_bytes((int)M, (int)K);
}
+21 -32
View File
@@ -27,7 +27,7 @@
//
// No state is keyed on the stream, since a recorded pass may replay on another stream. The split
// partial is the op's scratch (sized by the scratch hook, read+write, so overlapping ops get
// disjoint slices); the arrival counters are keyed on the output buffer (mxd_out_ctr), zero at
// disjoint slices); the arrival counters ride the scratch's tail, zero at
// entry and reset by the reducer. Launches writing the same output are ordered; overlapping ones
// write different outputs. The row is therefore concurrent (rad_kernel_concurrent), like
// gemm_fp8a8_nt_m16. A scratch shorter than the split needs is refused.
@@ -457,31 +457,8 @@ void r4d_gemm_mxfp4a8_decode1_kernel(
}
namespace {
// The arrival counters, one block per output buffer (see the header). They cannot live in the
// scratch, which other ops overwrite, because they must be zero at entry. One allocation per
// (device, output), kept zero by the reducer and never freed (a recorded pass replays the
// pointer), as gemm_fp8a8_nt_m16's split_ctr.
unsigned* mxd_out_ctr(const void* out) {
static std::mutex mu;
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
std::lock_guard<std::mutex> lk(mu);
const auto key = std::make_pair(dev, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16);
unsigned* p = nullptr;
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
// Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished
// when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it runs on the
// null stream, which a non-blocking stream does not wait for, so wait here.
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, p);
return p;
}
// The arrival counters now ride the op's scratch (mxd_partial_bytes); the per-output library
// allocation this replaced was a pointer a recorded pass could not relocate.
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule; see
// the header). Shared by the launch and the scratch hook so the sized partial is the one written.
@@ -508,8 +485,15 @@ MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
return p;
}
/* The scratch: the split partial when ks > 1, then the arrival counters. The counters live in the
* scratch rather than in a library-owned allocation because the scratch is a declared op buffer:
* a recorded pass relocates it with the other operands, while a pointer the library allocated
* itself is baked into the recorded kernarg and cannot be relocated. */
constexpr size_t mxd_ctr_count() { return R4D_MXD_MAX_N / (R4D_MXD_DWN * 16); }
long mxd_partial_bytes(int M, int N, int ks) {
return ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0;
return (ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0) +
(long)mxd_ctr_count() * (long)sizeof(unsigned);
}
void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N,
@@ -530,12 +514,16 @@ void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M,
throw std::runtime_error("r4d gemm_mxfp4a8_decode: KS must be 1, 2, 4, 8 or 16");
if (bk != 64 && bk != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: BK must be 64 or 128");
if (scratch_bytes < mxd_partial_bytes(M, N, ks) || (ks > 1 && !scratch))
if (!scratch || scratch_bytes < mxd_partial_bytes(M, N, ks))
throw std::runtime_error("r4d gemm_mxfp4a8_decode: the op's scratch is shorter than the split "
"partial; the scratch hook sizes it");
"partial and the arrival counters; the scratch hook sizes it");
float* P = (float*)scratch;
unsigned* cnt = mxd_out_ctr((const void*)c);
if (!cnt) throw std::runtime_error("r4d gemm_mxfp4a8_decode: split counter alloc failed");
unsigned* cnt = (unsigned*)((unsigned char*)P +
(ks > 1 ? (size_t)ks * (size_t)M * (size_t)N * sizeof(float) : 0));
/* Every launch enters with the counters zero: the scratch is shared across ops, and a replayed
* pass writes the same slots. One 1.1 KiB memset beside the launch is not measurable. */
if (hipMemsetAsync(cnt, 0, mxd_ctr_count() * sizeof(unsigned), (hipStream_t)stream) != hipSuccess)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: zeroing the arrival counters failed");
const bool ablk = as_group == 128, nt = pl.nt;
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
@@ -638,5 +626,6 @@ extern "C" int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) {
const int64_t b = (int64_t)mxd_partial_bytes((int)M, (int)np, ks);
if (b > worst) worst = b;
}
return worst;
const int64_t ctr = (int64_t)mxd_ctr_count() * (int64_t)sizeof(unsigned);
return worst > ctr ? worst : ctr;
}
+134
View File
@@ -939,6 +939,140 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand,
return RAD_OK;
}
/* ---- M2XFP4: the M2 analogue of MXFP4 above, the paper's weight-side Sg-EM (arXiv 2601.19213
* §4.4.2). The quantiser's own scheme "m2xfp4", three TILED planes over the same 32-column groups:
*
* codes u4 [1 x 1] e2m1, element 2j in bits 0-3 of byte j -- radiance MXFP4's codes
* scale u8 [1 x 32] e8m0 per group, the adaptive bias already folded into the stored byte
* meta u8 [1 x 32] one byte a group: subgroup s = columns [8s, 8s+8) in bits [2s, 2s+2)
*
* The exact element is e2m1mag[c&7] . sign(c) . 2^(scale-127) . (1 + k_s/4). What the kernels read
* is the mxfp4 arrangement with the meta plane riding the stored weight's tail, in the scale
* plane's [K/32][N] order: codes in fragment order, then K/32 rows of N meta bytes, so both GEMM
* rows read it with the exponents' own geometry (r4d_gemm_m2xfp4a8_*.hip). b_ref stays each row's
* largest exponent byte, the same derivation a reader of the plane could compute -- and it is what
* bounds the fold: d >= 0 for every block, so the largest e4m3 a table cell holds is the x1.75
* magnitude 10.5 scaled by 2^-d, a normal at every d >= 0.
*
* Anything else is refused: this kernel library decodes one scheme, and a weight whose meta plane
* said something else would decode to other numbers.
*
* A rotated weight (ParoQuant's M2XFP4) carries the same three planes in the basis its "givens"
* transform names, with the rotation's tables beside them -- the rotated MXFP4 weight's shape plus
* the metadata plane. The GEMM reads the planes as for an unrotated weight; the rotation is
* applied to the activation (givens_dense_quant), whose tables are separate weight operands. */
namespace {
/* The scheme's three planes, whichever kind of weight carries them. */
bool m2_planes(const RadEncoding* enc) {
if (!enc || !rad_enc_is(enc, "m2xfp4")) return false;
if (enc->plane[0].dtype != RAD_FP4E2M1 || enc->plane[0].block[0] != 1 ||
enc->plane[0].block[1] != 1)
return false;
const int s = rad_enc_find(enc, "scale"), m = rad_enc_find(enc, "meta");
if (s < 0 || m < 0) return false;
if (enc->plane[s].dtype != RAD_E8M0 || enc->plane[s].kind != RAD_PLANE_TILED ||
enc->plane[s].block[0] != 1 || enc->plane[s].block[1] != R4D_MXFP4_GROUP)
return false;
if (enc->plane[m].dtype != RAD_U8 || enc->plane[m].kind != RAD_PLANE_TILED ||
enc->plane[m].block[0] != 1 || enc->plane[m].block[1] != R4D_MXFP4_GROUP)
return false;
return true;
}
/* A rotated one: the three planes in the basis of a "givens" transform, whose tables are views of
* the weight's planes. Only the presence and the dtype of the tables is checked here (the arch
* declares them as operands the rotation op reads); any other transform would decode to other
* numbers, so it is refused. */
bool m2_paro_enc(const RadEncoding* enc, long long K) {
if (!enc || std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
if (enc->n_planes < 6 || !rad_enc_valid(enc) || !m2_planes(enc)) return false;
const int p = rad_enc_find(enc, "t.pairs"), an = rad_enc_find(enc, "t.angle"),
sc = rad_enc_find(enc, "t.scale");
if (p < 0 || an < 0 || sc < 0) return false;
if (enc->plane[p].dtype != RAD_I32 || enc->plane[an].dtype != RAD_F32 ||
enc->plane[sc].dtype != RAD_F32)
return false;
/* The quantiser rotates whole groups of 128 columns, one scale per group. */
return K % 128 == 0 && enc->plane[p].extent[1] == K;
}
int m2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out, WGeom* gout) {
if (!out || !pl) return RAD_E_INVAL;
WGeom g;
int rc = wgeom(p, n_p, R4D_MXFP4_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_MXFP4_GROUP || g.K % 16) return RAD_E_SHAPE;
if (!m2_planes(enc)) return RAD_E_DTYPE;
const bool plain = !enc->transform[0] && enc->n_planes == 3;
if (!plain && !m2_paro_enc(enc, g.K)) return RAD_E_DTYPE;
if (gout) *gout = g;
const long long nblk = g.K / R4D_MXFP4_GROUP;
if (operand == Q_BSCALE || operand == Q_BREF) {
if (!selects(enc, sel, n, "scale") || !dims(pl[0], g.N, nblk)) return RAD_E_SHAPE;
if (operand == Q_BSCALE) fill(out, "r4d.mxfp4.e8m0", R4D_DT_E8M0, nblk, g.N, nblk * g.N);
else fill(out, "r4d.mxfp4.wref", R4D_DT_E8M0, g.N, 1, g.N);
return RAD_OK;
}
if (operand != Q_B) return RAD_E_UNSUPPORTED;
/* The weight operand takes codes and meta: the codes go to fragment order, the meta to the
* stored blob's tail (rad_arch's decl_view names both planes). */
if (!selects(enc, sel, n, "codes", "meta") || !dims(pl[0], g.N, g.K) ||
!dims(pl[1], g.N, nblk))
return RAD_E_SHAPE;
fill(out, "r4d.m2xfp4.frag.g32.meta", R4D_DT_M2XFP4_FRAG, g.N, g.K,
g.N * g.K / 2 + nblk * g.N);
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_m2xfp4(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
return m2_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr);
}
extern "C" int r4d_rad_relayout_m2xfp4(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const RadTensor* pl,
int n, void* dst, int64_t dst_bytes) {
RadLayout L;
WGeom g;
const int rc = m2_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
std::memset(dst, 0, (size_t)dst_bytes);
const long long nblk = g.K / R4D_MXFP4_GROUP;
uint8_t* d = (uint8_t*)dst;
if (operand == Q_BSCALE || operand == Q_BREF) {
const uint8_t* e = pdata(pl[0]);
for (long long nn = 0; nn < g.N; ++nn) {
uint8_t mx = 0;
for (long long b = 0; b < nblk; ++b) {
const uint8_t v = e[nn * nblk + b];
if (operand == Q_BSCALE) d[b * g.N + nn] = v;
if (v > mx) mx = v;
}
if (operand == Q_BREF) d[nn] = mx;
}
return RAD_OK;
}
/* Codes to fragment order (mx_slot, as r4d_rad_relayout_mxfp4), then the meta plane appended:
* canonical [N][K/32] read into stored [K/32][N]. */
const uint8_t* meta = pdata(pl[1]);
uint8_t* md = d + g.N * g.K / 2;
for (long long nn = 0; nn < g.N; ++nn) {
const uint8_t* row = pdata(pl[0]) + nn * (g.K / 2);
for (long long k = 0; k < g.K; ++k) {
const uint8_t code = (uint8_t)((row[k >> 1] >> (4 * (k & 1))) & 0xF);
const long long idx = mx_slot(g, nn, k);
if (k & 1) d[idx] = (uint8_t)((d[idx] & 0x0Fu) | (uint32_t)(code << 4));
else d[idx] = (uint8_t)((d[idx] & 0xF0u) | code);
}
for (long long b = 0; b < nblk; ++b) md[b * g.N + nn] = meta[nn * nblk + b];
}
return RAD_OK;
}
/* ---- the MoE experts. The weight is staged through LDS, so it is not permuted: the int4 plane is
* the canonical one with each dword's nibbles reordered for the expansion (byte b holds element b
* low and element b+4 high), and the fp8 plane is the canonical one unchanged. `w4a8h` is the same
+104
View File
@@ -0,0 +1,104 @@
// Shared device code for the M2XFP4 GEMMs (r4d_gemm_m2xfp4a8_decode, r4d_gemm_m2xfp4a8_tiled):
// the folded-magnitude table and the eight-element unpack that reads it. The M2 analogue of
// r4d_mxfp4.h: the same e2m1 codes and E8M0 exponents, plus one more per-group byte of weight-side
// Sg-EM metadata (arXiv 2601.19213 §4.4.2), which folds the same way -- through a table, with a
// v_perm_b32 per half-word.
//
// The container ("m2xfp4", the quantiser's scheme) stores, per group of 32 K, an E8M0 exponent byte
// whose adaptive bias b in {-1,0,1} is already folded in, and a meta byte holding one two-bit
// subgroup multiplier k_s per eight columns, s = columns [8s, 8s+8) of the group: the stored byte's
// bits [2s, 2s+2). The exact weight is
//
// w = e2m1mag[c & 7] * sign(c) * 2^(scale - 127) * (1 + k_s / 4)
//
// with e2m1mag = {0, .5, 1, 1.5, 2, 3, 4, 6} and k -> {1.0, 1.25, 1.5, 1.75}. The fold of
// r4d_gemm_mxfp4a8_nt_m64.hip applies to it unchanged: d = Wref[n] - E8M0[n][blk] goes through the
// table, 2^(Wref[n]-127) once in the epilogue. Wref[n] is still the row's largest exponent byte,
// so d >= 0 holds for every block; what the meta adds is bounded the same way -- the largest
// element a table cell holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d, an E4M3 normal for every d >= 0, so
// no cell saturates and the fold is exact in its exponent at every block.
#pragma once
#include "r4d_mxfp4.h" // the fold clamp r4d_mxfp4_fold_d, the carried-scale reader, GROUP
#define R4D_M2XFP4_SUBGROUP 8 // K per two-bit meta multiplier: four of them per 32-column group
// kM2xfp4Mag[d][k] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by
// (1 + k/4) * 2^-d, as packed e4m3 bytes (low word, high word), indexed by the 3-bit magnitude
// through v_perm_b32 -- kMxfp4Mag's table with a second index. Entries are the round-to-nearest-even
// e4m3 of the product, matching the hardware conversion.
//
// Exactness, per magnitude and k, in the normal range of e4m3 (every entry here down to its
// subnormal floor behaves exactly like r4d_mxfp4.h's table one binade earlier, where the 2^-9 step
// is coarse; the entries flush the same way and the sums they miss are invisible next to the
// accumulator):
// - k = 0 is r4d_mxfp4.h's kMxfp4Mag row, byte for byte.
// - k = 1, 2: exact. The products' mantissas (1.25, 1.5 and 1.75 times a magnitude whose own
// mantissa is 1.0 or 1.1) take at most the three e4m3 mantissa bits, at every d while the
// value is normal.
// - k = 3 (x1.75): the even-mantissa magnitudes {0, .5, 1, 2, 4} stay exact (1.11 x 1.0); the odd
// ones {1.5, 3, 6} land on 1.0101, four mantissa bits, and round to the tie's even side -- 2.5,
// 5 and 10 scaled by 2^-d. That is 2^-4.4 relative error on those elements and nothing on the
// rest, accepted here: the CPU decode (and the reference) stay exact, and 6 * 1.75 = 10.5 at
// d = 0 is what the row-maximum bound above has to fit, which it does.
//
// Static: each kernel's code object carries its own copy.
static __device__ __constant__ unsigned int kM2xfp4Mag[16][4][2] = {
{{0x3c383000u, 0x4c484440u}, {0x3f3a3200u, 0x4f4a4742u}, {0x413c3400u, 0x514c4944u},
{0x423e3600u, 0x524e4a46u}},
{{0x34302800u, 0x44403c38u}, {0x37322a00u, 0x47423f3au}, {0x39342c00u, 0x4944413cu},
{0x3a362e00u, 0x4a46423eu}},
{{0x2c282000u, 0x3c383430u}, {0x2f2a2200u, 0x3f3a3732u}, {0x312c2400u, 0x413c3934u},
{0x322e2600u, 0x423e3a36u}},
{{0x24201800u, 0x34302c28u}, {0x27221a00u, 0x37322f2au}, {0x29241c00u, 0x3934312cu},
{0x2a261e00u, 0x3a36322eu}},
{{0x1c181000u, 0x2c282420u}, {0x1f1a1200u, 0x2f2a2722u}, {0x211c1400u, 0x312c2924u},
{0x221e1600u, 0x322e2a26u}},
{{0x14100800u, 0x24201c18u}, {0x17120a00u, 0x27221f1au}, {0x19140c00u, 0x2924211cu},
{0x1a160e00u, 0x2a26221eu}},
{{0x0c080400u, 0x1c181410u}, {0x0f0a0500u, 0x1f1a1712u}, {0x110c0600u, 0x211c1914u},
{0x120e0700u, 0x221e1a16u}},
{{0x06040200u, 0x14100c08u}, {0x08050200u, 0x17120f0au}, {0x09060300u, 0x1914110cu},
{0x0a070400u, 0x1a16120eu}},
{{0x03020100u, 0x0c080604u}, {0x04020100u, 0x0f0a0805u}, {0x04030200u, 0x110c0906u},
{0x05040200u, 0x120e0a07u}},
{{0x02010000u, 0x06040302u}, {0x02010100u, 0x08050402u}, {0x02020100u, 0x09060403u},
{0x03020100u, 0x0a070504u}},
{{0x01000000u, 0x03020201u}, {0x01010000u, 0x04020201u}, {0x01010000u, 0x04030202u},
{0x01010000u, 0x05040302u}},
{{0x00000000u, 0x02010100u}, {0x00000000u, 0x02010101u}, {0x01000000u, 0x02020101u},
{0x01000000u, 0x03020101u}},
{{0x00000000u, 0x01000000u}, {0x00000000u, 0x01010000u}, {0x00000000u, 0x01010100u},
{0x00000000u, 0x01010100u}},
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x01000000u},
{0x00000000u, 0x01000000u}},
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u}},
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u}},
};
// The two-bit field of a meta byte that covers `koff`, an element offset inside a 32-column group
// that is a multiple of R4D_M2XFP4_SUBGROUP (which the kernels' staging offsets all are): the
// subgroup s = koff / 8, bits [2s, 2s+2). A thread whose eight elements start at koff takes this
// shift once and one meta byte per (row, block) alongside the exponent byte.
static __device__ __forceinline__ int r4d_m2xfp4_kshift(int koff) {
return 2 * ((koff >> 3) & 3);
}
// Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) -> eight e4m3 bytes
// in k order (word 0 = elements 0..3, word 1 = 4..7), with the exponent difference `d` and the
// subgroup multiplier `k` folded in. r4d_mxfp4_unpack8_t with the [d][k] table row; see there.
//
// `_t` takes a table row (t0, t1) the caller already holds, e.g. from an LDS copy (the tiled
// kernel's sMag), which keeps the lookup off the global load counter the weight and activation
// loads wait on.
static __device__ __forceinline__ void r4d_m2xfp4_unpack8_t(unsigned int wv, unsigned int t0,
unsigned int t1, unsigned int* lo,
unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, t0, t1, lo, hi);
}
static __device__ __forceinline__ void r4d_m2xfp4_unpack8(unsigned int wv, int d, int k,
unsigned int* lo, unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, kM2xfp4Mag[d][k][0], kM2xfp4Mag[d][k][1], lo, hi);
}
+10
View File
@@ -450,6 +450,12 @@ int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*);
/* M2XFP4 (the paper's weight-side Sg-EM): the same GEMM bands at the m2xfp4 encoding, one meta
* plane more (r4d_layout.cpp, m2xfp4). */
int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs*);
int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs*);
int r4d_rad_dequant_w4 (const RadArgs*, RadStream);
int r4d_rad_rowtopk (const RadArgs*, RadStream);
int64_t r4d_rad_rowtopk_scratch(const RadArgs*);
@@ -652,6 +658,10 @@ int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const in
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_layout_m2xfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_m2xfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
+56 -30
View File
@@ -4808,6 +4808,16 @@ static const RadConstraint cGemmMxfp4A8Decode[] = {
static const RadConstraint cGemmMxfp4A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* The M2XFP4 rows (r4d_gemm_m2xfp4a8_*.hip): the same bands at the m2xfp4 encoding, whose dtype
* string alone separates them -- no skinny M2 row exists, so the decode row owns M <= 128 outright
* and the tiled row everything above, with no priority question between them (MXDEC outranks TILED
* wherever both match, as for mxfp4a8). */
static const RadConstraint cGemmM2xfp4A8Decode[] = {
C_LE("M", 128), C_LE("N", 36864), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "m2xfp4"),
};
static const RadConstraint cGemmM2xfp4A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "m2xfp4"),
};
/* r4d_gemm_w8a8_tiled: the same kernel at radix 8. Its asym arm is not declared in r4d.h, so
* `w8a8_asym` is absent from the dtype set. */
static const RadConstraint cGemmW8A8Tiled[] = {
@@ -4903,24 +4913,9 @@ static const RadTunable tGemmPrefill[] = {
"compiled tile arm; 0 is BM 128 x BN 256, libr4d's own default" },
};
/* The MXFP4 tiled GEMM's one axis: compiled arms of one template. 0 is the M crossover (TN=4 from
* M >= 2048), which needs M. */
static const int64_t kMxTn[] = { 0, 2, 4 };
static const RadTunable tGemmMxfp4Tiled[] = {
{ "tn", kMxTn, NELEM(kMxTn), 0,
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 2048" },
};
/* The MXFP4 decode GEMM's axes. 0 on each is the kernel's own rule (r4d_gemm_mxfp4a8_decode.hip);
* `nt` 1 streams the weight past the caches, 2 loads it plainly. */
static const int64_t kMxDecKs[] = { 0, 1, 2, 4, 8, 16 };
static const int64_t kMxDecBk[] = { 0, 64, 128 };
static const int64_t kMxDecNt[] = { 0, 1, 2 };
static const RadTunable tGemmMxfp4Decode[] = {
{ "ks", kMxDecKs, NELEM(kMxDecKs), 0, "split-K workgroups a column block. 0 = the fill rule" },
{ "bk", kMxDecBk, NELEM(kMxDecBk), 0, "K slab in bytes. 0 = 128, or 64 for a wide unsplit DTM 4" },
{ "nt", kMxDecNt, NELEM(kMxDecNt), 0, "weight loads: 1 non-temporal, 2 plain. 0 = by weight size" },
};
/* The MXFP4 tiled GEMM's one axis and the MXFP4 decode GEMM's axes (with the M2XFP4 rows
* declaring the decode set) live in r4d_args.h now, beside the cfg readers that resolve them, so
* a kernel unit links without this declaration side. */
/* ------------------------------------------------------------------------ split-KV attention
* 0 is libr4d's split law (table in r4d_attn_paged_h256_gqa6.hip), which reads num_seqs and
@@ -7530,6 +7525,42 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
/* M2XFP4: the mxfp4a8 rows at the paper's weight-side Sg-EM (arXiv 2601.19213 §4.4.2) -- per 32 K
* one more byte of weight, four two-bit subgroup multipliers, folded into the same e4m3 staging
* bytes through r4d_m2xfp4.h's table. The bands, tunables (ks/bk/nt and tn resolve through the
* same cfg readers) and relayout contract are the OCP rows', with the meta plane in the stored
* weight's tail (r4d_layout.cpp, m2xfp4) and no skinny row: at these row counts the decode kernel
* covers the whole M <= 128 band, the tiled one prefill. */
{ "gemm_m2xfp4a8_decode", "gemm_nt_q", "gemm",
"the M2XFP4 GEMM for the DECODE band: the mxfp4a8 decode kernel's split-K across workgroups with "
"a fused last-arriver reduction, the weight unpacked through LDS with its per-subgroup meta "
"multiplier, streaming weight loads",
"M <= 128; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
"[K/32][N] E8M0 exponents and per-row reference exponent, and the [K/32][N] meta plane in the "
"stored weight's tail; the split partial in the op's scratch",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K (bias "
"folded) and a two-bit multiplier per 8 K folded into the element against a per-row reference, "
"bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXDEC,
ROW(cGemmM2xfp4A8Decode), ROW(tGemmMxfp4Decode), nullptr,
nullptr, nullptr, r4d_rad_gemm_m2xfp4a8_decode, r4d_rad_gemm_m2xfp4a8_decode_scratch,
r4d_rad_layout_m2xfp4, r4d_rad_relayout_m2xfp4 },
{ "gemm_m2xfp4a8_tiled", "gemm_nt_q", "gemm",
"the M2XFP4 GEMM tiled for PREFILL row counts: the mxfp4a8 tiled kernel's 256-row block, the "
"activation re-tiled into the op's scratch, the weight with its meta multipliers unpacked once "
"per K slab into LDS",
"any M; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
"[K/32][N] E8M0 exponents and per-row reference exponent, and the [K/32][N] meta plane in the "
"stored weight's tail; the re-tiled activation in the op's scratch",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K (bias "
"folded) and a two-bit multiplier per 8 K folded into the element against a per-row reference, "
"bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_TILED,
ROW(cGemmM2xfp4A8Tiled), ROW(tGemmMxfp4Tiled), nullptr,
nullptr, nullptr, r4d_rad_gemm_m2xfp4a8_tiled, r4d_rad_gemm_m2xfp4a8_tiled_scratch,
r4d_rad_layout_m2xfp4, r4d_rad_relayout_m2xfp4 },
/* Band read off the entry point's own rejection tests. */
{ "gemm_w4a8_prefill", "gemm_nt_q", "gemm",
"the 4-bit GEMM for PREFILL row counts, where the matrix pipe rather than the weight stream is "
@@ -9389,10 +9420,11 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
* every collective the peer flags and exchange buffers the all-reduces own
*
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream and the output;
* gemm_mxfp4a8_decode's split partial is the op's scratch and its arrival counters are keyed on the
* output alone; router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken
* at init, one per declared op and band). Concurrent launches never share these, so those three
* rows are concurrent. A new row with stream-ordered state belongs in the list above.
* gemm_mxfp4a8_decode's and gemm_m2xfp4a8_decode's split partial is the op's scratch and their
* arrival counters are keyed on the output alone (the M2 row keeps its own counter blocks,
* m2d_out_ctr); router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken
* at init, one per declared op and band). Concurrent launches never share these, so those rows are
* concurrent. A new row with stream-ordered state belongs in the list above.
*
* lora_* ordered on purpose: the core appends them behind the GEMM whose `y` they
* update and refills the pools they read between steps with its own copies,
@@ -9545,14 +9577,8 @@ extern "C" void r4d_cfg_tiled(const RadArgs* a, R4dTileCfg* out) {
extern "C" void r4d_cfg_prefill(const RadArgs* a, R4dTileCfg* out) {
tile_bmbn(TUNE(a, tGemmPrefill, "tile"), 1, out);
}
extern "C" void r4d_cfg_mxfp4_decode(const RadArgs* a, R4dMxDecCfg* out) {
out->ks = TUNE(a, tGemmMxfp4Decode, "ks");
out->bk = TUNE(a, tGemmMxfp4Decode, "bk");
out->nt = TUNE(a, tGemmMxfp4Decode, "nt");
}
extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) {
out->tn = TUNE(a, tGemmMxfp4Tiled, "tn");
}
/* r4d_cfg_mxfp4_decode and r4d_cfg_mxfp4_tiled are inline in r4d_args.h, beside their tables and
* the tune reader, so the kernel units carry them without this declaration side. */
extern "C" void r4d_cfg_split(const RadArgs* a, R4dSplitCfg* out) {
out->splits = TUNE(a, tAttnSplit, "splits");
}
+158
View File
@@ -4386,6 +4386,147 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
}
/* The M2XFP4 rows (r4d_gemm_m2xfp4a8_*.hip): mxfp4a8_numeric's shape checks at the m2xfp4
* encoding -- a third plane of per-subgroup multipliers, whose every byte value is valid, drawn
* full range so k = 3 is in regular rotation, beside the bias-folded exponents. The bound is the
* mxfp4 row's plus the table's accepted k = 3 rounding: a quarter of the weights at up to 2^-4.4
* each is about 1.2% of a whole dot, so 4e-2 holds the same margin the 1e-2 does there. The
* relayout is exercised for real: the weight operand takes codes and meta, and the stored blob the
* launch reads is this hook's output. */
static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K,
int tn, bool ablk = false, std::vector<RadParam> extra = {},
int64_t pb1 = 0, int64_t pb2 = 0) {
if (!sel(row)) return;
const PartCut cut(N, pb1, pb2);
const int parts = cut.parts;
char nm[160];
std::string ex;
for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival);
if (parts > 1) ex += " parts=" + std::to_string(parts);
std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld tn=%d%s%s", row, (long long)M,
(long long)N, (long long)K, tn, ablk ? " ascale=row x 128" : "", ex.c_str());
const RadKernelInfo* r = find(pl, row);
if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; }
const int64_t nblk = K / 32;
Planes p;
rad_enc_clear(&p.enc);
rad_enc_copy_str(p.enc.scheme, "m2xfp4");
rad_enc_add_plane(&p.enc, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&p.enc, "scale", RAD_E8M0, 1, 32);
rad_enc_add_plane(&p.enc, "meta", RAD_U8, 1, 32);
p.size(N, K);
const int ic = p.find("codes"), is = p.find("scale"), im = p.find("meta");
if (ic < 0 || is < 0 || im < 0) { ok(nm, false, "encoding has no m2xfp4 planes"); return; }
/* codes and exponents as mxfp4_fill draws them (deep: exponents the fold's subnormal floor
* reaches), the meta full range so every multiplier and every subgroup phase appears */
mxfp4_fill(p, ic, is, N, K, 0x71u, true);
for (int64_t i = 0; i < (int64_t)p.data[(size_t)im].size(); ++i)
p.data[(size_t)im][(size_t)i] = (uint8_t)st_mix32((uint32_t)i ^ 0x4d2eu);
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 32) };
std::vector<uint8_t> wq, ws, wr;
const int rw = stored(r, lp, 2, p, { "codes", "meta" }, &wq);
const int rs = stored(r, lp, 3, p, { "scale" }, &ws);
const int rr = stored(r, lp, 6, p, { "scale" }, &wr);
if (rw != RAD_OK || rs != RAD_OK || rr != RAD_OK) {
ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs) + "/" +
std::to_string(rr));
return;
}
const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1;
const int64_t PK = parts * K, PA = parts * asc; /* a row of `a`, and of its scale */
std::vector<uint8_t> ha((size_t)(M * PK));
std::vector<float> av((size_t)(M * PK)), as((size_t)(M * PA));
for (int64_t i = 0; i < M; ++i) {
for (int64_t c = 0; c < PA; ++c) {
const uint32_t h = st_mix32((uint32_t)(i * PA + c) ^ 0xa5u);
as[(size_t)(i * PA + c)] =
ablk ? ((i + c) % 11 == 5 ? 0.0f : 0.002f * (float)(1 + h % 97))
: 0.0125f * (float)(1 + h % 5);
}
for (int64_t k = 0; k < PK; ++k) {
const bool zero = ablk && as[(size_t)(i * PA + (k / K) * asc + (k % K) / 128)] == 0.0f;
const float v = zero ? 0.0f : mxfp4_act(i, k, 0x3cu);
rad_store_f32(ha.data(), RAD_F8E4M3, i * PK + k, v);
av[(size_t)(i * PK + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * PK + k);
}
}
std::vector<uint16_t> hy((size_t)(M * N), 0);
void* d_a = dalloc(ha.size());
void* d_s = dalloc(as.size() * 4);
void* d_w = dalloc(wq.size());
void* d_e = dalloc(ws.size());
void* d_r = dalloc(wr.size());
void* d_y = dalloc(hy.size() * 2);
if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y) { ok(nm, false, "hipMalloc failed"); return; }
st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice);
st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice);
st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_a, RAD_F8E4M3, { M, PK }),
ablk ? T(d_s, RAD_F32, { M, PA }) : T(d_s, RAD_F32, { M }),
T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }),
T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(d_r, RAD_U8, { (int64_t)wr.size() }),
};
absent(ts[5]);
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "m2xfp4") };
if (tn) ps.push_back(PI("tn", tn));
if (pb1) ps.push_back(PI("pb1", pb1));
if (pb2) ps.push_back(PI("pb2", pb2));
for (const RadParam& p : extra) ps.push_back(p);
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
if (r->scratch) {
const int64_t sb = r->scratch(&a);
if (sb > 0) {
a.scratch = dalloc((size_t)sb);
a.scratch_bytes = sb;
if (!a.scratch) { ok(nm, false, "hipMalloc failed"); return; }
}
}
const int rc = r->launch(&a, (RadStream) nullptr);
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) {
ok(nm, false, "rc=" + std::to_string(rc));
return;
}
st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost);
/* Every column for small N, a stride otherwise, always including the last column. The exact
* decode: the e2m1 code, the subgroup's stored multiplier, and the folded exponent. */
const int64_t nstep = N > 96 ? N / 96 : 1;
double num = 0, den = 0;
for (int64_t i = 0; i < M; ++i)
for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) {
double acc = 0;
const int pt = cut.part_of(n);
for (int64_t k = 0; k < K; ++k) {
const uint8_t meta = p.data[(size_t)im][(size_t)(n * nblk + k / 32)];
const int kk = (int)(((meta >> (2 * ((k % 32) / 8))) & 3));
const double w =
(double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) *
(1.0 + kk / 4.0) *
(double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32);
acc += (double)av[(size_t)(i * PK + pt * K + k)] * w *
(ablk ? (double)as[(size_t)(i * PA + pt * asc + k / 128)] : 1.0);
}
if (!ablk) acc *= (double)as[(size_t)i];
const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc;
num += d * d;
den += acc * acc;
}
const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num);
char d[96];
std::snprintf(d, sizeof d, "rel_l2 %.3e", rel);
ok(nm, rel < 4e-2, d);
}
/* What givens_numeric runs: the sequential rotation to f16, or the dense rotation with either
* quantiser. */
enum class GvCase { Rotate, DenseFp8, DenseI8 };
@@ -26820,6 +26961,23 @@ static void device_phase(const Plugin& pl) {
for (int bk : { 64, 128 })
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 96, 400, 2560, 0, true,
{ PI("ks", ks), PI("bk", bk), PI("nt", 1) });
/* The M2XFP4 rows: the decode band's rule and band edges, the tiled row at both widths and
* past the tn crossover, both activation grids, and parts -- the same spread the OCP rows
* get, at the three-plane encoding. */
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 272, 640, 0, false);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 272, 640, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 40, 400, 2560, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 128, 512, 2560, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 5, 1040, 576, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 96, 14336, 640, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 400, 2560, 0, true, {}, 128);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 40, 512, 2560, 0, true, {}, 128, 384);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 40, 272, 640, 2, false);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 400, 640, 4, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 2100, 512, 2560, 0, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 272, 576, 2, true);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 400, 640, 2, true, {}, 192);
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 34816, 5120, 0, true, {}, 17408);
for (int ks : { 1, 2, 4, 8, 16 })
for (int bk : { 64, 128 })
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 24, 400, 2560, 0, true,
+66
View File
@@ -376,6 +376,64 @@ static int gemm_zp(const ZpGrid& zg, const RadTensor* A, const RadTensor* as_,
return RAD_OK;
}
/* ------------------------------------------------------------------ M2XFP4 */
/* gemm_nt_q at dtype m2xfp4, the m2xfp4 quantiser's own scheme (libquant): `b` is the weight's
* codes and meta planes concatenated as stored (the shape hook's m2xfp4 arm -- the codes rows,
* then the meta rows), `b_scale` the E8M0 exponent plane [N, K/32] and `b_ref` the same plane,
* as the mxfp4 grid's. The exact element is e2m1 code . 2^(e-127) . (1 + k_s/4), the subgroup
* multiplier k_s the meta byte's two-bit field [2s, 2s+2) over subgroups s of eight columns
* (libr4d's r4d_m2xfp4.h folds the same law into its staging table); each product is one f32
* multiply, each row one f32 accumulation in k order -- the exact decode's own arithmetic, since
* the multipliers take the codes off the integer grid an mxfp4 group sub-sum would use. */
static const float kM2E2M1[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
static int gemm_m2(const RadArgs* a) {
if (a->n_t < 5) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
const RadTensor *as_ = t_in(a, 1), *bs_ = t_in(a, 3);
if (!A->data || !B->data || !Y->data) return RAD_E_INVAL;
if (t_in(a, 5)) return RAD_E_UNSUPPORTED; /* a_sum belongs to the asym grids */
if (A->dtype != RAD_F8E4M3 || B->dtype != RAD_U8 || B->rank != 1) return RAD_E_DTYPE;
if (!as_ || !bs_ || bs_->dtype != RAD_E8M0 || bs_->rank < 2) return RAD_E_DTYPE;
const int64_t K = p_int(a, "K", 0), N = p_int(a, "N", 0);
if (K <= 0 || K % 32 || N <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
const int64_t kb = K / 32, akb = (K + 127) / 128;
if (numel(A) < M * K || numel(B) != N * (K / 2 + kb) || numel(bs_) < N * kb ||
numel(as_) < M * akb)
return RAD_E_SHAPE;
const int64_t ars = row_stride(A, K), acs = laststride(A);
const int64_t srs = row_stride(as_, akb), scs = laststride(as_);
const int64_t brs = row_stride(bs_, kb);
const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y);
const uint8_t* meta0 = (const uint8_t*)B->data + N * (K / 2);
REF_PAR_FOR(N)
for (int64_t n = 0; n < N; ++n) {
const uint8_t* codes = (const uint8_t*)B->data + n * (K / 2);
const uint8_t* meta = meta0 + n * kb;
const uint8_t* expe = (const uint8_t*)bs_->data + n * brs;
/* The weight row decoded once, so the meta and exponent reads are not repeated per
* activation row. */
std::vector<float> w((size_t)K);
for (int64_t k = 0; k < K; ++k) {
const uint8_t c = (uint8_t)((codes[k >> 1] >> (4 * (k & 1))) & 0xF);
const float cv = (c & 8 ? -kM2E2M1[c & 7] : kM2E2M1[c & 7]);
const float ev = std::ldexpf(1.0f, (int)expe[k >> 5] - 127);
const float km = 1.0f + 0.25f * (float)((meta[k >> 5] >> (2 * ((k & 31) >> 3))) & 3);
w[(size_t)k] = cv * ev * km;
}
for (int64_t m = 0; m < M; ++m) {
const int64_t ab = m * ars;
float acc = 0.0f;
for (int64_t k = 0; k < K; ++k)
acc += ldt(A, ab + k * acs) * ldt(as_, m * srs + (k >> 7) * scs) * w[(size_t)k];
stt(Y, m * ys_r + n * ys_c, acc);
}
}
return RAD_OK;
}
static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
const int nt = bias_operand ? 6 : 5;
if (a->n_t < nt || !a->t[0].data || !a->t[2].data || !a->t[nt - 1].data) return RAD_E_INVAL;
@@ -391,6 +449,14 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
* only. */
const ZpGrid* zg = zp_grid(p_str(a, "dtype", nullptr));
if (zg && bias_operand) return RAD_E_UNSUPPORTED;
/* M2XFP4: the quantiser's own scheme, decoded by gemm_m2 from its concatenated planes.
* Parts (pb1/pb2) are the rotated grids'; the m2 declare makes none, and a case carrying
* them is declined rather than answered unsplit. */
if (!bias_operand && p_str(a, "dtype", nullptr) &&
std::strcmp(p_str(a, "dtype", nullptr), "m2xfp4") == 0) {
if (p_int(a, "pb1", 0) > 0 || p_int(a, "pb2", 0) > 0) return RAD_E_UNSUPPORTED;
return gemm_m2(a);
}
if (!bias_operand) {
if (t_in(a, 5) && (!zg || zg->act != ZP_I8_ROW)) return RAD_E_UNSUPPORTED;
if (t_in(a, 6) && B->dtype != RAD_FP4E2M1) return RAD_E_UNSUPPORTED;
+13
View File
@@ -69,9 +69,22 @@ struct Scales {
int64_t group; /* K elements per scale */
int64_t rblk; /* operand rows per scale row; 1 unless the grid is block-scaled */
bool e8m0; /* the scale stream is OCP e8m0 exponent bytes, not floats */
/* M2XFP4 (libquant's `m2xfp4`, lq_m2xfp.cpp): `group` is 8, so `g` names a subgroup. The
* E8M0 byte is one per four subgroups and the meta plane's two-bit field refines it, the
* scale of subgroup g being e8m0(scale[g >> 2]) . (1 + k/4) with k the field's value -- the
* quantiser's own decode, which this states where it folds the product. */
const uint8_t* m2_meta = nullptr; /* [rows][K/32] meta bytes, canonical rows */
int64_t m2_mrs = 0; /* bytes between meta rows */
bool m2 = false;
/* The scale of group `g` of `row`. */
inline float grp(int64_t row, int64_t g) const {
if (m2) {
const int64_t gi = g >> 2;
const int64_t i = (rblk > 1 ? row / rblk : row) * rs + gi * cs;
const int k = (m2_meta[row * m2_mrs + gi] >> (2 * (g & 3))) & 3;
return e8m0_to_f32(((const uint8_t*)p)[i]) * (1.0f + 0.25f * (float)k);
}
int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs;
return e8m0 ? e8m0_to_f32(((const uint8_t*)p)[i]) : ld_dt(dt, p, i);
}
+101 -2
View File
@@ -182,15 +182,70 @@ static inline int ref_layout_mtp(const RadParam*, int, int operand, const RadEnc
return layout_scaled(operand, 4, 5, enc, sel, planes, n, out);
}
/* M2XFP4, the `m2xfp4` quantiser's own scheme (libquant): three TILED planes over 32-column
* groups, and gemm_nt_q's weight operand takes the codes and the meta. Their stored form is the
* two planes' canonical bytes concatenated -- the codes' rows, then the meta's -- the form the
* core's selection reader hands a kernel that decodes the scheme itself beside the scale stream
* another operand carries (core/format/encoding.cpp), and the one both libraries' m2 arms read.
* libavx/avx_planes.h states the same rules. */
static inline bool m2_enc_planes(const RadEncoding* enc) {
if (!rad_enc_is(enc, "m2xfp4")) return false;
/* A rotated weight (ParoQuant) carries the same three planes in the basis its "givens"
* transform names, with the rotation's tables beside them; the rotation is the activation's,
* so the planes are read as they are. */
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
const RadEncPlane* mt = rad_enc_plane(enc, "meta");
const bool planes = enc->plane[0].kind == RAD_PLANE_TILED &&
enc->plane[0].dtype == RAD_FP4E2M1 && enc->plane[0].block[0] == 1 &&
enc->plane[0].block[1] == 1 && sc && mt && sc->kind == RAD_PLANE_TILED &&
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == 32 &&
mt->kind == RAD_PLANE_TILED && mt->dtype == RAD_U8 && mt->block[0] == 1 &&
mt->block[1] == 32;
if (!planes) return false;
if (!enc->transform[0]) return enc->n_planes == 3;
return enc->n_planes >= 6 && rad_enc_plane(enc, "t.pairs") &&
rad_enc_plane(enc, "t.angle") && rad_enc_plane(enc, "t.scale");
}
/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the zero-point grid `dtype` names,
* one each per (row, `group` of K), over codes of that grid's width. The codes (operand 2) are one
* plane and stored as they are. A "givens" transform is the activation's (givens_rotate,
* givens_dense_quant), so the planes are read the same way under it. */
* givens_dense_quant), so the planes are read the same way under it. At `m2xfp4` the weight
* operand takes codes and meta concatenated (above); the scale and reference operands are single
* planes, stored as they are. */
static inline int ref_layout_gemm_q(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
const char* dt = rad_param_gets(p, n_p, "dtype", nullptr);
if (dt && std::strcmp(dt, "m2xfp4") == 0) {
const long long group = rad_param_geti(p, n_p, "group", 0);
const long long N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
if (!m2_enc_planes(enc) || group != 32 || N <= 0 || K <= 0 || K % 32)
return RAD_E_DTYPE;
if (operand == 2) {
if (!sel_roles(enc, sel, n, "codes", "meta")) return RAD_E_DTYPE;
if (planes[0].shape[0] != N || planes[0].shape[1] != K ||
planes[1].shape[0] != N || planes[1].shape[1] != K / 32)
return RAD_E_SHAPE;
out->tag = "m2.codes.meta";
out->dtype = RAD_U8;
out->rank = 1;
out->shape[0] = N * (K / 2 + K / 32);
out->align = 0;
out->bytes = out->shape[0];
return RAD_OK;
}
if (operand == 3 || operand == 6) {
if (n != 1 || sel[0] < 0 || sel[0] >= enc->n_planes ||
std::strncmp(enc->plane[sel[0]].role, "scale", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
return RAD_E_UNSUPPORTED; /* one plane, stored as it is */
}
return RAD_E_UNSUPPORTED;
}
if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr));
const ZpGrid* zg = zp_grid(dt);
const long long group = rad_param_geti(p, n_p, "group", 0);
if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
@@ -208,6 +263,50 @@ static inline int ref_layout_gemm_q(const RadParam* p, int n_p, int operand,
return rad_planes_layout(enc, sel, planes, n, out);
}
/* gemm_nt_q's own relayout: the m2 arm's concatenated form beside the zero-point grids' joined
* one, each as its layout hook laid it out. */
template <RadLayoutFn L>
static int ref_relayout_gemm_q(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst,
int64_t dst_bytes) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (lay.tag && std::strcmp(lay.tag, "m2.codes.meta") == 0) {
if (dst_bytes != lay.bytes) return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
for (int i = 0; i < n; ++i) {
const int64_t rb = rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
const int64_t b = planes[i].shape[0] * rb;
std::memcpy(d, planes[i].data, (size_t)b);
d += b;
}
return RAD_OK;
}
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
}
template <RadLayoutFn L>
static int ref_unrelayout_gemm_q(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (lay.tag && std::strcmp(lay.tag, "m2.codes.meta") == 0) {
if (src_bytes != lay.bytes) return RAD_E_SHAPE;
const uint8_t* s = (const uint8_t*)src;
for (int i = 0; i < n; ++i) {
const int64_t rb = rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
const int64_t b = planes[i].shape[0] * rb;
std::memcpy(planes[i].data, s, (size_t)b);
s += b;
}
return RAD_OK;
}
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
}
/* RadRelayoutFn and RadUnrelayoutFn for any of the layout hooks above: the hook decides whether
* the planes are joined, and the copies are rad_planes.h's. */
template <RadLayoutFn L>
+14 -3
View File
@@ -2003,6 +2003,17 @@ static int ref_check_gemm_q(const char* op, const RadArgs* a) {
}, \
nullptr, lay, ref::ref_relayout_planes<lay>, fn##_shape, ref::ref_unrelayout_planes<lay> }
/* gemm_nt_q: its zero-point grids join scale and zero (ref_planes.h) while its m2xfp4 arm
* concatenates codes and meta, so the row carries the hook's own relayout pair. */
#define ROWL_GQ(nm, opname, fam, what, dts, check, fn, lay) \
{ nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \
nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, \
[](const RadArgs* a, RadStream s) -> int { \
const int rc = check(opname, a); \
return rc < 0 ? rc : fn(a, s); \
}, \
nullptr, lay, ref::ref_relayout_gemm_q<lay>, fn##_shape, ref::ref_unrelayout_gemm_q<lay> }
#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*)"
@@ -2178,9 +2189,9 @@ SIMPLE("ref_dequant", "dequant", "quant", "group-scaled dequantisation", DT_ANY,
SIMPLE("ref_gemm_nt", "gemm_nt", "gemm", "C = A B^T, f32 accumulate", DT_FLOAT, ref_gemm_nt),
SIMPLE("ref_gemm_nt_bias", "gemm_nt_bias", "gemm", "C = A B^T + bias", DT_FLOAT,
ref_gemm_nt_bias),
ROWL("ref_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; u2 / u4 / u5 codes with an f16 scale "
"and integer zero per group, joined; f32 accumulate",
ROWL_GQ("ref_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands",
"i8 / fp8 / float A; w4, w2, mxfp4, m2xfp4, i8 or float B; u2 / u4 / u5 codes with an f16 "
"scale and integer zero per group, joined; f32 accumulate",
ref_check_gemm_q, ref_gemm_nt_q, ref::ref_layout_gemm_q),
SIMPLE("ref_gemm_nt_q_bias", "gemm_nt_q_bias", "gemm", "quantised C = A B^T + bias",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", ref_gemm_nt_q_bias),
+24 -17
View File
@@ -1154,10 +1154,10 @@ int ref_gemm_nt_bias_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
* The fp8 grid is stated by the checkpoint: E4M3 [N][K] against a bf16 [ceil(N/128)][ceil(K/128)]
* plane, `group` carrying the 128. w4a8 and w8a8 are the affine encoding's two planes, codes and
* an f16 scale per (row, `group` of K), against int8 codes in the step order with one f32 scale a
* row. `a_sum` (asymmetric grids) is absent, and so is `b_ref` except at mxfp4a8. Activation
* scales are drawn in (0, 1): a quantiser's are never negative, and an MXFP4 kernel treats a
* block whose scale is not positive as empty (docs/OPS.md). */
static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadOpdDesc* out) {
* row. `a_sum` (asymmetric grids) is absent, and so is `b_ref` except at mxfp4a8 and m2xfp4.
* Activation scales are drawn in (0, 1): a quantiser's are never negative, and an MXFP4 kernel
* treats a block whose scale is not positive as empty (docs/OPS.md). */
int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
const int64_t group = gi(p, n_p, "group", 0);
const char* q = gs(p, n_p, "dtype");
@@ -1165,11 +1165,11 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO
const bool f32s = is("fp8a8f32");
const bool a8 = is("fp8a8") || f32s, a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8");
/* i8a8h is i8a8's operands; its rotation is in the values. */
const bool i8 = is("i8a8") || is("i8a8h"), mx = is("mxfp4a8");
if ((!a8 && !a16 && !w4 && !w8 && !i8 && !mx) || N <= 0 || K <= 0 || group <= 0)
const bool i8 = is("i8a8") || is("i8a8h"), mx = is("mxfp4a8"), m2 = is("m2xfp4");
if ((!a8 && !a16 && !w4 && !w8 && !i8 && !mx && !m2) || N <= 0 || K <= 0 || group <= 0)
return RAD_E_UNSUPPORTED;
/* Neither has a bias form in any architecture. */
if (bias && (i8 || mx)) return RAD_E_UNSUPPORTED;
if (bias && (i8 || mx || m2)) return RAD_E_UNSUPPORTED;
/* The bias form requires `a_scale`, so the fp8a16 reading (bf16 activation, no scale) cannot
* be expressed there. */
if (bias && a16) return RAD_E_UNSUPPORTED;
@@ -1177,20 +1177,27 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO
const int64_t kb = (K + group - 1) / group;
const int64_t nb = (N + group - 1) / group;
Opd o;
if (i8 || mx) {
if (i8 || mx || m2) {
/* i8a8: quant_act_i8g's row-major codes and f32 scale per (row, `group` of K) against int8
* codes with a bf16 scale per (row, `group` of K). mxfp4a8: quant_act_fp8's pair at 128
* against e2m1 codes with an E8M0 exponent per (row, `group` = 32 of K); `b_ref` is the same
* exponent plane, which an mxfp4 kernel reduces to a per-row reference at load. */
const int64_t akb = mx ? (K + 127) / 128 : kb;
o.t((uint32_t)(mx ? RAD_F8E4M3 : RAD_I8), { M, K }); /* a */
o.t_fill((uint32_t)RAD_F32, { M, akb }, (uint32_t)RAD_FILL_SIGMOID, 0); /* a_scale */
o.t((uint32_t)(mx ? RAD_FP4E2M1 : RAD_I8), { N, K }); /* b */
o.t((uint32_t)(mx ? RAD_E8M0 : RAD_BF16), { N, kb }); /* b_scale */
o.t((uint32_t)RAD_BF16, { M, N }); /* y */
o.skip(); /* a_sum */
if (mx) o.t((uint32_t)RAD_E8M0, { N, kb }); /* b_ref */
* exponent plane, which an mxfp4 kernel reduces to a per-row reference at load. m2xfp4:
* the mxfp4a8 operands with the metadata plane riding `b`, whose (codes,meta) selection
* reads back as the two planes' bytes concatenated (encoding.cpp) -- the codes rows, then
* the meta rows -- which ref_gemm.cpp's own arm decodes against `b_scale`. */
const int64_t akb = (mx || m2) ? (K + 127) / 128 : kb;
o.t((uint32_t)((mx || m2) ? RAD_F8E4M3 : RAD_I8), { M, K }); /* a */
o.t_fill((uint32_t)RAD_F32, { M, akb }, (uint32_t)RAD_FILL_SIGMOID, 0); /* a_scale */
if (m2)
o.t((uint32_t)RAD_U8, { N * (K / 2 + K / 32) }); /* b -- codes then meta bytes */
else
o.t((uint32_t)(mx ? RAD_FP4E2M1 : RAD_I8), { N, K }); /* b */
o.t((uint32_t)((mx || m2) ? RAD_E8M0 : RAD_BF16), { N, kb }); /* b_scale */
o.t((uint32_t)RAD_BF16, { M, N }); /* y */
o.skip(); /* a_sum */
if (mx || m2) o.t((uint32_t)RAD_E8M0, { N, kb }); /* b_ref */
else o.skip();
if (m2 && (group != 32 || K % 32)) return RAD_E_UNSUPPORTED;
return o.finish("gemm_nt_q", operand, out);
}
if (w4 || w8) {
+17
View File
@@ -0,0 +1,17 @@
#!/bin/bash
NAME=$1; HIP=$2; SKIP_CONV=$3
IFS=$'\t' read -r _n _h DIR OUT EXTRA <<< "$(grep -P "^$NAME\t" /tmp/night/lanes.tsv)"
LOG=/tmp/night/cpk-$NAME.log
R=/home/zee/orca/workspaces/radiance/m2xfp
if [ "$SKIP_CONV" != "skip" ]; then
echo "$(date -Is) $NAME convert start (hip$HIP)" >> $LOG
cd /home/zee/code/vllm/ggz14/paroquant || exit 1
env FORCE=1 PARO_HIP_VISIBLE=$HIP PARO_NAME=paro_cnv_$NAME FT_RESULTS=$DIR OUT=$OUT $EXTRA ./stage2-m2xfp4.sh convert >> $LOG 2>&1 || { echo "$(date -Is) $NAME CONVERT FAILED" >> $LOG; exit 1; }
fi
echo "$(date -Is) $NAME pack start" >> $LOG
cd $R || exit 1
PATH=$R/build-r4d/bin:$PATH python3 tools/rad_pack_m2xfp4.py /home/zee/models/$OUT --home $R/build-r4d/radiance_home --recipe data/recipes/q38-27b-paro-m2xfp4-df2.recipe --draft /home/zee/models/hf/Qwen3.8-27B-DFlash2 -o /media/zee/ai/radiance/containers/q38-27b-m2xfp4-ft-$NAME.rad >> $LOG 2>&1 || { echo "$(date -Is) $NAME PACK FAILED" >> $LOG; exit 1; }
echo "$(date -Is) $NAME kld start" >> $LOG
cd $R/build-r4d || exit 1
HIP_VISIBLE_DEVICES=$HIP GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 ./bin/radiance --model /media/zee/ai/radiance/containers/q38-27b-m2xfp4-ft-$NAME.rad --radiance-home radiance_home --kld-ref /home/zee/models/rad/kld-bf16 --kld-out /home/zee/models/rad/kld-$NAME-vs-bf16.json >> $LOG 2>&1
echo "$(date -Is) $NAME CHAIN DONE rc=$?" >> $LOG
+13
View File
@@ -0,0 +1,13 @@
import json, sys, time, urllib.request, threading
PORT=int(sys.argv[1])
def one(out):
body=json.dumps({"model":"qwen35","messages":[{"role":"user","content":"Write a detailed essay about the history of computing, covering many decades."}],"max_tokens":256,"temperature":0.7,"stream":False}).encode()
t0=time.time()
r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=600).read()
out.append(json.loads(r)["usage"]["completion_tokens"]/(time.time()-t0))
for c in (1,4,8,16):
out=[]; th=[threading.Thread(target=one,args=(out,)) for _ in range(c)]
t0=time.time()
for t in th: t.start()
for t in th: t.join()
print(f"conc={c}: {sum(out):.1f} tok/s aggregate ({time.time()-t0:.0f}s)")
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
LOG=/tmp/night/eval.log
cd /home/zee/orca/workspaces/radiance/m2xfp/build-r4d
pkill -f 'bin/radianc[e].*39476' 2>/dev/null; sleep 2
HIP_VISIBLE_DEVICES=2 GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 nohup ./bin/radiance \
--model /media/zee/ai/radiance/containers/q38-27b-m2xfp4.rad \
--radiance-home radiance_home --host 127.0.0.1 --port 39476 \
--max-num-seqs 16 --max-model-len 16384 > /tmp/night/eval-serve.log 2>&1 &
SPID=$!
for i in $(seq 1 180); do curl -sf :39476/health >/dev/null 2>&1 && break; sleep 5; done
curl -sf :39476/health >/dev/null 2>&1 || { echo "$(date -Is) SERVE FAILED (host)" >> $LOG; exit 1; }
echo "$(date -Is) healthy (host, hip2)" >> $LOG
python3 /tmp/night/gsm8k1.py 200 39476 /home/zee/models/rad/gsm8k-m2xfp4-rtn.json >> $LOG 2>&1
python3 /tmp/night/conc.py 39476 >> $LOG 2>&1
kill $SPID 2>/dev/null
echo "$(date -Is) EVAL DONE (hip2 free)" >> $LOG
+30
View File
@@ -0,0 +1,30 @@
import json, re, sys, urllib.request
from concurrent.futures import ThreadPoolExecutor
N=int(sys.argv[1]); PORT=int(sys.argv[2]); OUT=sys.argv[3]
items=json.load(open("/home/zee/models/calib/gsm8k/test.json"))[:N]
PROMPT=("Solve this maths problem step by step. End with exactly: The answer is <number>\n\nProblem: %s")
def norm(a):
a=a.replace(",","").replace("$","").strip()
try: return float(a)
except: return None
def ask(q):
body=json.dumps({"model":"qwen35","messages":[{"role":"user","content":PROMPT%q}],
"max_tokens":700,"temperature":0,"reasoning_effort":"none"}).encode()
r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,
headers={"Content-Type":"application/json"}),timeout=600).read()
return json.loads(r)["choices"][0]["message"].get("content") or ""
def extract(t):
m=re.findall(r"answer is\s*\$?([-\d][\d,\.]*)", t, re.I)
if m: return norm(m[-1])
m=re.findall(r"([-\d][\d,\.]*)\s*$", t.strip())
return norm(m[-1]) if m else None
res={}
def one(i):
q=items[i]["q"]; g=norm(items[i]["a"])
try: t=ask(q)
except Exception: res[i]=(False,g,None,"ERR"); return
p=extract(t); res[i]=(p is not None and g is not None and abs(p-g)<1e-6, g, p, t)
with ThreadPoolExecutor(max_workers=8) as ex: list(ex.map(one, range(len(items))))
c=sum(1 for v in res.values() if v[0])
print(f"GSM8K {N}: {c}/{len(res)} = {100*c/len(res):.1f}%")
json.dump({str(k):v[:3] for k,v in res.items()},open(OUT,"w"))
+3
View File
@@ -0,0 +1,3 @@
MAIN 4 /media/zee/ai/paro-out-ft-m2xfp4 Qwen3.8-27B-PARO-M2XFP4-FT
EXACT 1 /media/zee/ai/paro-out-ft-m2xfp4-exact Qwen3.8-27B-PARO-M2XFP4-FT-EXACT M2XFP4_FOLD=exact
SEED1 0 /media/zee/ai/paro-out-ft-m2xfp4-seed1 Qwen3.8-27B-PARO-M2XFP4-FT-SEED1 PARO_SEED=1
1 MAIN 4 /media/zee/ai/paro-out-ft-m2xfp4 Qwen3.8-27B-PARO-M2XFP4-FT
2 EXACT 1 /media/zee/ai/paro-out-ft-m2xfp4-exact Qwen3.8-27B-PARO-M2XFP4-FT-EXACT M2XFP4_FOLD=exact
3 SEED1 0 /media/zee/ai/paro-out-ft-m2xfp4-seed1 Qwen3.8-27B-PARO-M2XFP4-FT-SEED1 PARO_SEED=1
+18
View File
@@ -0,0 +1,18 @@
import json, random, threading, time, urllib.request
PORT=39476; T0=time.time(); rounds=0; faults=0
def fire(i, kill):
try:
body=json.dumps({"model":"qwen35","messages":[{"role":"user","content":f"Explain in detail topic {i}: write a long essay."}],"max_tokens":512,"temperature":0.8}).encode()
req=urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"})
r=urllib.request.urlopen(req, timeout=2 if kill else 300)
if not kill: r.read()
except Exception:
pass
while time.time()-T0 < 1800:
ths=[threading.Thread(target=fire,args=(i,random.random()<0.5),daemon=True) for i in range(8)]
for t in ths: t.start()
time.sleep(random.uniform(0.5,3)); rounds+=1
try: urllib.request.urlopen(f"http://127.0.0.1:{PORT}/health",timeout=10).read(); ok="ok"
except Exception as e: ok=f"FAULT {e}"; faults+=1
if rounds%20==0: print(f"{time.strftime('%T')} rounds={rounds} health={ok} faults={faults}",flush=True)
print(f"SOAK DONE: {rounds} abort-heavy rounds, {faults} health faults in {(time.time()-T0)/60:.0f} min",flush=True)
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
NAME=$1; CTR=paro_s2_$NAME
IFS=$'\t' read -r _name HIP DIR OUT EXTRA <<< "$(grep -P "^$NAME\t" /tmp/night/lanes.tsv)"
LOG=/tmp/night/watch-$NAME.log; : >> $LOG
last=""; since=$(date +%s); up=0
while :; do
n=$(ls $DIR/Qwen3.8-27B-fp16/*.pt 2>/dev/null | wc -l)
lb=$(docker logs $CTR 2>&1 | wc -c)
io=$(docker exec $CTR sh -c 'awk "/^rchar/{print \$2}" /proc/1/io' 2>/dev/null)
fp="$n:$lb:${io:-0}"; now=$(date +%s)
[ "$fp" != "$last" ] && { last=$fp; since=$now; }
cap=$(docker logs $CTR 2>&1 | grep -ac "Capturing original"); opt=$(docker logs $CTR 2>&1 | grep -ac "Optimizing layer")
echo "$(date -Is) $NAME files=$n idle=$(( (now-since)/60 ))m" >> $LOG
[ "$n" -ge 400 ] && { echo "$(date -Is) $NAME COMPLETE" >> $LOG; break; }
docker ps --filter name=$CTR --format '{{.ID}}' | grep -q . && up=1
if [ "$up" = 0 ] && [ $(( now - since )) -lt 420 ]; then sleep 60; continue; fi
if ! docker ps --filter name=$CTR --format '{{.ID}}' | grep -q .; then
echo "$(date -Is) $NAME gone -> relaunch" >> $LOG
else
thresh=15; [ "$cap" = "0" ] && [ "$opt" = "0" ] && thresh=45
if [ $(( (now-since)/60 )) -lt $thresh ]; then sleep 90; continue; fi
docker exec $CTR /src/.pyspy/bin/py-spy dump --pid 1 > /tmp/ft-hang-$NAME-$(date +%H%M%S).txt 2>&1
echo "$(date -Is) $NAME FROZEN -> dump+relaunch" >> $LOG
docker rm -f $CTR >/dev/null 2>&1; sleep 8
fi
cd /home/zee/code/vllm/ggz14/paroquant && env FORCE=1 PARO_HIP_VISIBLE=$HIP FT_EPOCHS=1 PARO_ROT_KERNEL=1 $EXTRA \
PARO_NAME=$CTR FT_RESULTS=$DIR OUT=$OUT setsid nohup ./stage2-m2xfp4.sh finetune >> /tmp/ft-$NAME.log 2>&1 < /dev/null &
sleep 300
done
+23 -1
View File
@@ -552,6 +552,7 @@ which people, logs and `rad-info` read; kernels read the struct:
| `u2*f16[1x128]-u8[1x128]` | a 2-bit draft head, asymmetric |
| `fp4_e2m1*e8m0[1x32]` | MXFP4 |
| `fp4_e2m1*fp8_e4m3[1x16]*f32[*x*]` | NVFP4: two scale levels |
| `m2xfp4:codes=fp4_e2m1[1x1],scale=e8m0[1x32],meta=u8[1x32]` | M2XFP: MXFP4 with a metadata byte a group |
| codes `u4`, `scale u6[1x32] . f16[1x256]`, `min u6[1x32] . f16[1x256]` | llama.cpp's Q4_K |
| codes `u4`, `table i8{1x16}`, two scale levels | IQ4_XS |
| codes `u8[1x8]` into `grid u8{256x8}`, `signs`, two scale levels | IQ2_XXS |
@@ -562,9 +563,29 @@ which people, logs and `rad-info` read; kernels read the struct:
A GGUF file's K- and I-quants are therefore a lossless rearrangement into planes; serving one needs
only a kernel that reads it.
A scheme the core does not decode is `m2xfp4`: M2XFP (adapted from "M2XFP:
A Metadata-Augmented Microscaling Data Format for Efficient Low-bit Quantization", arXiv
2601.19213, the paper's weight-side Sg-EM only -- its element-side activation scheme is not
encoded here). An OCP MXFP4 group of 32 columns carries, beside its E8M0 exponent, one metadata
byte: four 2-bit extra mantissas, one a subgroup of 8 columns. Subgroup s (columns [8s, 8s+8))
refines the group's shared scale to (1 + k/4) . 2^E with k its two bits, little-endian in bits
[2s, 2s+2), so a group decodes as
```
w[j] = e2m1(codes[j]) . 2^(scale[g] - 127) . (1 + k_s/4), g = j/32, s = (j%32)/8
```
4.5 bits an element. The three planes sit apart -- codes fp4_e2m1 [1 x 1] as a bit stream along
the row (the MXFP4 codes' bytes), the scale e8m0 [1 x 32] and the metadata u8 [1 x 32] one byte a
group -- as the paper's memory organisation keeps them (its §5.2). The exponent byte follows the
MXFP4 grid's OCP rule and its conventions, zeros and short final groups included
(`libquant/lq_m2xfp.cpp`); the quantiser's search chooses the bias of the shared exponent and each
subgroup's k by least squared error (§4.5). The core cannot follow the equation, so the quantiser
supplies the decoder, as below.
The core decodes every `plain` and `affine` encoding to f32 (for the oracle, `rad-convert`'s error
report, and requantising). A quantiser whose scheme the core cannot decode supplies the decoder
(§4.5).
(§4.5); `m2xfp4` is the built-in example.
### 4.2 `.rad`
@@ -731,6 +752,7 @@ Each algorithm pairs with any grid it makes sense for, and a recipe names all th
| `autoround` | sign-gradient descent on rounding offsets and block ranges against H | integer codes, row blocks, one level | the grid |
| `paroquant` | Givens pair rotations and channel scales fitted against H, then AutoRound | every untransformed one | the grid and a `givens` transform |
| `ggml` | llama.cpp's own searches, imatrix-weighted | its legacy, K- and I-quant types | each type's affine form |
| `m2xfp4` | M2XFP's weight-side Sg-EM: per group of 32, each subgroup of 8's extra mantissa k in {0..3} and the shared exponent's bias in {-1, 0, 1} (`adaptive=0` pins the bias) chosen by least squared error, the OCP exponent and its rounding otherwise the MXFP4 grid's | none of the grid options | its own scheme `m2xfp4`, which it decodes: MXFP4's codes and E8M0 exponent plus a u8 metadata byte a group (arXiv 2601.19213) |
| `cast` | a float in another float dtype | none | `plain` |
The grid is `codes` (integers to 32 bits, fp8/6/4) or `table` (a codebook: NF4, IQ4_NL's values,
+27 -4
View File
@@ -429,8 +429,11 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_
${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip
${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip
${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip
${R4D_DIR}/r4d_dsa.hip)
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa)
${R4D_DIR}/r4d_dsa.hip
# The M2XFP4 GEMMs: their cfg readers are inline in r4d_args.h, so the units link
# without the declaration side and the test runs what an untuned install runs.
${R4D_DIR}/r4d_gemm_m2xfp4a8_decode.hip ${R4D_DIR}/r4d_gemm_m2xfp4a8_tiled.hip)
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa m2xfp4)
set(R4D_EMU_BUILT OFF)
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
# No fiber switch for this ISA.
@@ -469,7 +472,7 @@ else()
${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp
${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp
${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp)
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp)
get_filename_component(stem ${src} NAME_WE)
set(lang "")
if(src MATCHES "\\.hip$")
@@ -506,7 +509,7 @@ else()
endif()
endif()
if(R4D_EMU_BUILT)
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa)
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa m2xfp4)
add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t})
endforeach()
# The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel,
@@ -518,6 +521,7 @@ if(R4D_EMU_BUILT)
set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick
r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse
r4d_emu_dsa
r4d_emu_m2xfp4
PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT})
# The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can
# load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within
@@ -640,6 +644,25 @@ if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_moe.rkb)
ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};OMP_WAIT_POLICY=passive")
endif()
# The M2XFP4 rows over the 27B-trunk fixture set (see the root CMakeLists): the four max-tok
# passes replayed together, covering the m2xfp4a8 decode row's whole M ladder. Scoped to
# libref:libr4d: the m2 arm of the other host library is that library's own to bring up.
if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_m2xfp4_m128.rkb)
add_test(NAME kbench_m2xfp4
COMMAND rad-kbench --home ${RAD_PLUGIN_OUT} --kernels libref:libr4d --max-cases 1
--no-ref --strict --coverage ${RAD_KBENCH_ROWS}
--fixture ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m1.rkb
--fixture ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m8.rkb
--fixture ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m16.rkb
--fixture ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m128.rkb)
set_tests_properties(kbench_m2xfp4 PROPERTIES
LABELS "${RAD_KBENCH_LABELS}"
TIMEOUT 1800
RESOURCE_LOCK kbench_memory
PROCESSORS 4
ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};OMP_WAIT_POLICY=passive")
endif()
# libref against its own recordings, both fixtures, at tolerance zero: it is deterministic and
# machine-independent by construction, so any difference is a change in libref (or in the draw)
# that would otherwise become the next recording's target. This is the oracle's regression test.
+336
View File
@@ -0,0 +1,336 @@
/* quant_m2xfp_test.cpp -- the `m2xfp4` quantiser: the metadata plane's pack, the scheme's own
* decode, and the search's quality against plain OCP MXFP4.
*
* Every case quantises through the quantiser's hooks as rad-convert does and reads the weight
* back through enc_decode_rows, which asks libquant's decode hook for the scheme -- so the
* round-trip checks the planes a reader that never saw the quantiser would unpack, against a
* scalar decode of the spec's equation written out here by hand: the nibble stream, the E8M0
* bytes and the metadata's low-bits-first subgroups are each unpacked independently. The quality
* cases compare weight MSE against `rtn codes=fp4_e2m1 group=32 scale=e8m0`, the OCP MXFP4 the
* scheme refines: the search's candidate set contains that quantiser's choice for every group,
* so it can only tie or win, and the wins are where the format earns its half bit. The wide case
* holds the same property one bias wider: wide=1 sweeps b in {-2, ..., 2} and can only tie or
* beat adaptive, its planes decoding bit for bit as the equation does.
*/
#include "quant_fixture.h"
#include <dlfcn.h>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
using namespace rad;
using namespace qfix;
namespace {
constexpr const char* kName = "blk.2.attn_q.weight";
/* The thread count of the OpenMP runtime the plugin loaded, so a run can be repeated at another. */
void threads(int n) {
using Fn = void (*)(int);
if (Fn f = (Fn)dlsym(RTLD_DEFAULT, "omp_set_num_threads")) f(n);
}
bool same_planes(const Quantised& a, const Quantised& b) {
if (a.enc.n_planes != b.enc.n_planes) return false;
for (int i = 0; i < a.enc.n_planes; ++i)
if (a.planes[(size_t)i] != b.planes[(size_t)i]) return false;
return true;
}
/* The spec's decode, by hand: element j's nibble (element 2j in the low bits of byte j/2), its
* group's E8M0 byte and metadata byte, subgroup s = (j%32)/8 in bits [2s, 2s+2). */
std::vector<float> ref_decode(const Quantised& q, int64_t rows, int64_t cols) {
const int64_t ng = (cols + 31) / 32;
const int64_t crow = (4 * cols + 7) / 8;
const uint8_t* codes = q.planes[0].data();
const uint8_t* scale = q.planes[1].data();
const uint8_t* meta = q.planes[2].data();
static const float mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
std::vector<float> out((size_t)(rows * cols));
for (int64_t r = 0; r < rows; ++r)
for (int64_t j = 0; j < cols; ++j) {
const uint8_t nib = (codes[(size_t)(r * crow + (j >> 1))] >> ((j & 1) * 4)) & 15;
const uint8_t sb = scale[(size_t)(r * ng + (j >> 5))];
const uint8_t mb = meta[(size_t)(r * ng + (j >> 5))];
const int k = (mb >> (2 * ((j & 31) >> 3))) & 3;
const float s = std::ldexp(1.0f, (int)sb - 127);
out[(size_t)(r * cols + j)] =
(nib & 8 ? -mag[nib & 7] : mag[nib & 7]) * s * (1.0f + 0.25f * (float)k);
}
return out;
}
double mse(const std::vector<float>& w, const std::vector<float>& d) {
double e = 0.0;
for (size_t i = 0; i < w.size(); ++i) {
const double x = (double)w[i] - d[i];
e += x * x;
}
return e / (double)w.size();
}
/* Lognormal magnitudes, exp(sigma z) with z standard normal from a splitmix draw: the heavy tail
* that makes one shared exponent a group a poor fit. */
std::vector<float> lognormal(int64_t n, uint64_t seed, double sigma) {
uint64_t z = seed;
auto next = [&]() {
z += 0x9E3779B97F4A7C15ull;
uint64_t x = z;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
return (double)((x ^ (x >> 31)) >> 11) / 9007199254740992.0;
};
std::vector<float> w((size_t)n);
for (int64_t i = 0; i < n; i += 2) {
const double u1 = next(), u2 = next();
const double r = std::sqrt(-2.0 * std::log(u1 + 1e-12));
const double a = sigma * r * std::cos(6.283185307179586 * u2);
const double b = sigma * r * std::sin(6.283185307179586 * u2);
w[(size_t)i] = (float)std::exp(a);
if (i + 1 < n) w[(size_t)i + 1] = (float)std::exp(b);
}
return w;
}
/* Every group's amax on a different fraction of an octave, 2^u with u uniform in [0, 1): the
* amax / 2^E0 quotient swept over [4, 8), where the OCP floor's choice of exponent is worst and
* the bias search has most to say. */
std::vector<float> octave_groups(int64_t rows, int64_t cols, uint64_t seed) {
const std::vector<float> z = draw(rows * cols, seed, 4.0f);
std::vector<float> w(z);
const int64_t ng = (cols + 31) / 32;
for (int64_t r = 0; r < rows; ++r)
for (int64_t g = 0; g < ng; ++g) {
uint64_t h = seed ^ ((uint64_t)r * 0x9E3779B97F4A7C15ull) ^ (uint64_t)g;
h = (h ^ (h >> 30)) * 0xBF58476D1CE4E5B9ull;
h = (h ^ (h >> 27)) * 0x94D049BB133111EBull;
const double u = (double)(h >> 11) / 9007199254740992.0;
const float lift = (float)std::exp2(u); /* an octave, [1, 2) */
for (int64_t c = g * 32; c < (g + 1) * 32 && c < cols; ++c)
w[(size_t)(r * cols + c)] = z[(size_t)(r * cols + c)] * lift;
}
return w;
}
/* The fixture's quantise takes its options by reference, so each case builds its own. */
void m2xfp_opts(Opts& o, int adaptive, int wide = 0) {
o.i("adaptive", adaptive);
if (wide) o.i("wide", wide);
}
void mxfp4_opts(Opts& o) { o.s("codes", "fp4_e2m1").i("group", 32).s("scale", "e8m0"); }
} // namespace
TEST(m2xfp4_is_three_planes_and_round_trips_through_its_own_decode) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
const RadQuantWeight w0 = weight_of("x", 8, 64);
RadEncoding e{};
REQUIRE_EQ(q->encoding(nullptr, 0, &w0, &e), RAD_OK);
CHECK_EQ(std::string(e.scheme), std::string("m2xfp4"));
CHECK_EQ(e.transform[0], 0);
REQUIRE_EQ(e.n_planes, 3);
CHECK_EQ(std::string(e.plane[0].role), std::string("codes"));
CHECK_EQ((int)e.plane[0].dtype, (int)RAD_FP4E2M1);
CHECK_EQ(e.plane[0].block[0], 1);
CHECK_EQ(e.plane[0].block[1], 1);
CHECK_EQ(std::string(e.plane[1].role), std::string("scale"));
CHECK_EQ((int)e.plane[1].dtype, (int)RAD_E8M0);
CHECK_EQ(e.plane[1].block[1], 32);
CHECK_EQ(std::string(e.plane[2].role), std::string("meta"));
CHECK_EQ((int)e.plane[2].dtype, (int)RAD_U8);
CHECK_EQ(e.plane[2].block[1], 32);
CHECK_EQ(q->row_block(nullptr, 0, &w0), (int64_t)1);
/* a rank-1 norm is declined, like every quantiser's, not an error */
RadQuantWeight v{};
v.name = "x";
v.rank = 1;
v.shape[0] = 64;
v.rows = 1;
v.cols = 64;
CHECK_EQ(q->encoding(nullptr, 0, &v, &e), RAD_E_UNSUPPORTED);
/* whole groups, a short final group, and an odd column count's nibble tail: the decode the
* core reaches through the hook must equal the equation by hand, bit for bit. */
for (int64_t C : { 256, 112, 101 }) {
const int64_t R = 8;
const std::vector<float> w = draw(R * C, 41, 8.0f);
Opts o_adapt;
m2xfp_opts(o_adapt, 1);
Quantised a = quantise(q, o_adapt, kName, R, C, w);
REQUIRE_EQ(a.status, RAD_OK);
const std::vector<float> d = decode(a, R, C);
REQUIRE_EQ(d.size(), w.size());
const std::vector<float> r = ref_decode(a, R, C);
for (size_t i = 0; i < d.size(); ++i) CHECK_EQ(d[(size_t)i], r[(size_t)i]);
/* rows from the middle, as the oracle and rad-convert ask for them */
std::vector<const void*> pd;
for (auto& p : a.planes) pd.push_back(p.data());
EncodedView v;
std::string why;
enc_view(a.enc, R, C, pd.data(), &v);
std::vector<float> part((size_t)(3 * C));
REQUIRE_EQ(enc_decode_rows(v, 3, 3, part.data(), &why), RAD_OK);
for (int64_t i = 0; i < 3 * C; ++i) CHECK_EQ(part[(size_t)i], d[(size_t)(3 * C + i)]);
}
}
TEST(m2xfp4_packs_the_metadata_low_bits_first_and_zero_groups_like_mxfp4) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
/* One row, one group, its subgroups built to choose k = 0, 0, 1, 3 (the zeros keep k 0, the
* 1.9s want 5/4 of the scale, the 5.5s want 7/4 of it). The group is built so the bias tie
* is exact: every subgroup's best dequantised value is the same under b = -1 and b = 0
* (0, 1.0, 1.875 and 5.25 -- the e2m1 grid is scale-invariant until a candidate saturates),
* so the biases tie at 0.5082 and the search keeps the first of {-1, 0, 1}, the paper's
* argmin. The exponent byte is 126, and the same codes under it decode to what b = 0's 127
* would: the tie moves the byte, never the weight. */
std::vector<float> w(32);
for (int j = 0; j < 8; ++j) w[(size_t)j] = 0.02f;
for (int j = 8; j < 16; ++j) w[(size_t)j] = 1.0f;
for (int j = 16; j < 24; ++j) w[(size_t)j] = 1.9f;
for (int j = 24; j < 32; ++j) w[(size_t)j] = 5.5f;
Opts o_adapt;
m2xfp_opts(o_adapt, 1);
Quantised a = quantise(q, o_adapt, kName, 1, 32, w);
REQUIRE_EQ(a.status, RAD_OK);
REQUIRE_EQ(a.planes[1].size(), (size_t)1);
REQUIRE_EQ(a.planes[2].size(), (size_t)1);
CHECK_EQ((int)a.planes[1][0], 126);
CHECK_EQ((int)a.planes[2][0], (0 << 0) | (0 << 2) | (1 << 4) | (3 << 6));
const std::vector<float> d = decode(a, 1, 32);
REQUIRE_EQ(d.size(), w.size());
const std::vector<float> r = ref_decode(a, 1, 32);
for (int j = 0; j < 32; ++j) CHECK_EQ(d[(size_t)j], r[(size_t)j]);
/* A zero group: byte 0 and zero codes, the MXFP4 grid's exponent-floor clamp, not the
* reference's clamped-amax exponent -- the same decode either way, radiance's bytes win. */
const std::vector<float> z(2 * 64, 0.0f);
Opts o_zero, o_mx;
m2xfp_opts(o_zero, 1);
mxfp4_opts(o_mx);
Quantised m = quantise(q, o_zero, kName, 2, 64, z);
Quantised g = quantise(quantizer("rtn"), o_mx, kName, 2, 64, z);
REQUIRE_EQ(m.status, RAD_OK);
REQUIRE_EQ(g.status, RAD_OK);
CHECK(m.planes[1] == g.planes[1]);
int bad = 0;
for (uint8_t c : m.planes[0]) bad += c != 0;
for (uint8_t b : m.planes[2]) bad += b != 0;
CHECK_EQ(bad, 0);
}
TEST(m2xfp4_stores_the_same_bytes_one_band_or_four_threads_at_a_time) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
const int64_t R = 32, C = 256;
const std::vector<float> w = draw(R * C, 43, 6.0f);
Opts o_adapt;
m2xfp_opts(o_adapt, 1);
Quantised whole = quantise(q, o_adapt, kName, R, C, w);
threads(1);
Quantised one = quantise(q, o_adapt, kName, R, C, w, nullptr, 4);
threads(4);
Quantised four = quantise(q, o_adapt, kName, R, C, w, nullptr, 4);
REQUIRE_EQ(whole.status, RAD_OK);
REQUIRE_EQ(one.status, RAD_OK);
REQUIRE_EQ(four.status, RAD_OK);
/* its output is a file: the bands and the thread count may not move a byte */
CHECK(same_planes(whole, one));
CHECK(same_planes(whole, four));
}
TEST(m2xfp4_beats_ocp_mxfp4_on_heavy_tails_and_its_search_never_hurts) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
const int64_t R = 64, C = 256;
struct Case { const char* what; std::vector<float> w; };
std::vector<Case> cases;
cases.push_back({ "lognormal", lognormal(R * C, 51, 1.5) });
cases.push_back({ "octave", octave_groups(R, C, 52) });
Opts o_mx, o_pin, o_adapt;
mxfp4_opts(o_mx);
m2xfp_opts(o_pin, 0);
m2xfp_opts(o_adapt, 1);
for (const Case& c : cases) {
Quantised base = quantise(quantizer("rtn"), o_mx, kName, R, C, c.w);
Quantised off = quantise(q, o_pin, kName, R, C, c.w);
Quantised on = quantise(q, o_adapt, kName, R, C, c.w);
REQUIRE_EQ(base.status, RAD_OK);
REQUIRE_EQ(off.status, RAD_OK);
REQUIRE_EQ(on.status, RAD_OK);
const double eb = mse(c.w, decode(base, R, C));
const double e0 = mse(c.w, decode(off, R, C));
const double e1 = mse(c.w, decode(on, R, C));
std::fprintf(stderr, " %s: MXFP4 %.5f, m2xfp4 bias-pinned %.5f, adaptive %.5f "
"(%.1f%% of MXFP4)\n", c.what, eb, e0, e1, 100.0 * e1 / eb);
/* every group's candidates contain plain MXFP4's choice, and the adaptive set contains
* the pinned one, so each stage can only tie or improve */
CHECK(e0 <= eb);
CHECK(e1 <= e0);
CHECK(e1 < eb * 0.98);
}
}
TEST(m2xfp4_wide_bias_sweep_contains_the_narrow_one_and_round_trips_bit_exact) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("m2xfp4");
REQUIRE(q);
const int64_t R = 64, C = 256;
struct Case { const char* what; std::vector<float> w; };
std::vector<Case> cases;
cases.push_back({ "lognormal", lognormal(R * C, 61, 2.0) });
cases.push_back({ "octave", octave_groups(R, C, 62) });
Opts o_pin, o_adapt, o_wide;
m2xfp_opts(o_pin, 0);
m2xfp_opts(o_adapt, 1);
m2xfp_opts(o_wide, 1, 1);
for (const Case& c : cases) {
Quantised off = quantise(q, o_pin, kName, R, C, c.w);
Quantised on = quantise(q, o_adapt, kName, R, C, c.w);
Quantised wide = quantise(q, o_wide, kName, R, C, c.w);
REQUIRE_EQ(off.status, RAD_OK);
REQUIRE_EQ(on.status, RAD_OK);
REQUIRE_EQ(wide.status, RAD_OK);
const double e0 = mse(c.w, decode(off, R, C));
const double e1 = mse(c.w, decode(on, R, C));
const double e2 = mse(c.w, decode(wide, R, C));
std::fprintf(stderr, " %s: pinned %.5f, adaptive %.5f, wide %.5f (%.1f%% of "
"pinned)\n", c.what, e0, e1, e2, 100.0 * e2 / e0);
/* wide's candidates {-2, ..., 2} contain adaptive's {-1, 0, 1}, which contain the
* pinned b = 0, so each stage can only tie or improve */
CHECK(e1 <= e0);
CHECK(e2 <= e1);
/* the wide path's planes decode bit for bit as the equation unpacked by hand */
const std::vector<float> d = decode(wide, R, C);
const std::vector<float> r = ref_decode(wide, R, C);
REQUIRE_EQ(d.size(), c.w.size());
for (size_t i = 0; i < d.size(); ++i) CHECK_EQ(d[i], r[i]);
}
/* wide=1 at adaptive=0 is the pinned quantiser, plane for plane: there is no bias to widen,
* so the option may not move a byte */
const std::vector<float> w = draw(R * C, 55, 8.0f);
Opts o_pin_wide;
m2xfp_opts(o_pin_wide, 0, 1);
Quantised off = quantise(q, o_pin, kName, R, C, w);
Quantised both = quantise(q, o_pin_wide, kName, R, C, w);
REQUIRE_EQ(off.status, RAD_OK);
REQUIRE_EQ(both.status, RAD_OK);
CHECK(same_planes(off, both));
}
RAD_TEST_MAIN()
+2
View File
@@ -169,7 +169,9 @@ inline void __threadfence() {}
template <typename T> inline T emu_atomic_fetch_add(T* p, T v) { const T o = *p; *p = o + v; return o; }
/* The device allocations a unit makes for itself (counter blocks): host memory here. */
inline hipError_t hipMalloc(void** p, size_t n) { *p = std::calloc(n ? n : 1, 1); return *p ? 0 : 2; }
inline hipError_t hipMemset(void* p, int v, size_t n) { std::memset(p, v, n); return 0; }
inline hipError_t hipMemsetAsync(void* p, int v, size_t n, hipStream_t) { std::memset(p, v, n); return 0; }
inline hipError_t hipFree(void* p) { std::free(p); return 0; }
struct alignas(8) uint2 { unsigned x, y; };
struct alignas(16) uint4 { unsigned x, y, z, w; };
+415
View File
@@ -0,0 +1,415 @@
/* tests/r4d_emu: the M2XFP4 x fp8 GEMMs (r4d_gemm_m2xfp4a8_decode.hip, r4d_gemm_m2xfp4a8_tiled.hip)
* on the host SIMT emulator. The container's m2xfp4 encoding (the paper's weight-side Sg-EM,
* arXiv 2601.19213 §4.4.2) is synthesised from random f32 weights by an in-test scalar quantiser
* implementing the spec: per group of 32 columns an E8M0 exponent with the adaptive bias (-1, 0, 1,
* cycling) folded into the stored byte, and a meta byte of four two-bit subgroup multipliers with
* k = 3 in heavy rotation; the codes are the e2m1 roundings of the exact dequantiser's inverse.
* The stored bytes are then built the way r4d_rad_relayout_m2xfp4 builds them (fragment-order
* codes, the meta plane appended in the exponents' [K/32][N] order), and both kernels run against
* an f64 CPU reference of the exact decode, at the FP8 WMMA's tolerance (rel_l2 < 1e-2). Cases
* cover both activation scale grids (per row, per (row, 128) with a zero block), M across the
* decode band's band edges (1, 8, 16, 40, 128) and the tiled row's, the one-fragment prefetch
* form (M <= 16), both K slabs (64 and 128), and a split-K launch on the decode kernel.
*
* The table itself is held to arithmetic first: every kM2xfp4Mag[d][k] cell must be the
* round-to-nearest-even e4m3 of e2m1mag * (1 + k/4) * 2^-d; the k = 0..2 rows must be exact while
* the product is a normal e4m3 value, and the k = 3 odd-mantissa entries must be the tie's even
* side (2.5, 5, 10 scaled by 2^-d). The unpack is held to the same arithmetic over every code at
* every (d, k).
*
* The declaration side (r4d_rows.cpp) is not in the emu build, so the two cfg readers it defines
* are stubbed here at their axis defaults (0 = the kernels' own rules), which is what an untuned
* call gets. Everything else is the library's own code.
*/
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include "r4d.h"
#include "r4d_m2xfp4.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
extern const char* emu_last_kernel;
/* The cfg readers the entry points call are inline in r4d_args.h, beside their tables, so this
* test links the units without the declaration side and runs what an untuned install runs. */
/* ------------------------------------------------------------------ arithmetic e4m3 / e2m1 */
/* Round-to-nearest-even e4m3 (OCP FP8, 1-4-3, bias 7, subnormals at 2^-9, 0x7F/0xFF NaN), the
* conversion the device tables and the WMMA's own converts use. */
static uint8_t rne_e4m3(double v) {
if (v == 0) return std::signbit(v) ? 0x80 : 0; /* the kernels keep a sign on zero */
const uint8_t sign = v < 0 ? 0x80 : 0;
double a = std::fabs(v);
if (a > 480) return (uint8_t)(sign | 0x7E);
int e = 0;
while (a >= 2.0) { a *= 0.5; ++e; }
while (a < 1.0) { a *= 2.0; --e; }
int m;
if (e < -6) { /* subnormal: 2^-9 steps of the value itself */
double q = std::fabs(v) * 512.0;
double fl = std::floor(q);
const double frac = q - fl;
int qi = (int)fl;
if (frac > 0.5 || (frac == 0.5 && (qi & 1))) ++qi;
if (qi >= 8) return (uint8_t)(sign | 0x08); /* up to min normal 2^-6 */
return (uint8_t)(sign | qi);
}
double q = (a - 1.0) * 8.0;
m = (int)q;
const double frac = q - m;
if (frac > 0.5 || (frac == 0.5 && (m & 1))) ++m;
if (m == 8) { m = 0; ++e; }
return (uint8_t)(sign | ((e + 7) << 3) | m);
}
static double e4m3_f64(uint8_t b) {
const double s = b & 0x80 ? -1.0 : 1.0;
const int e = (b >> 3) & 15, m = b & 7;
if (e == 0) return s * m * 0.001953125; /* 2^-9 steps */
return s * std::ldexp(1.0 + m / 8.0, e - 7);
}
/* The e2m1 magnitudes, and the quantiser's RNE code for a magnitude against them (ties to the even
* code, as the hardware's convert and the CPU reference agree). */
static const double kE2m1Mag[8] = { 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0 };
static uint8_t rne_e2m1(double v) {
double a = std::fabs(v);
int best = 0;
double bd = 1e300;
for (int i = 0; i < 8; ++i) {
const double d = std::fabs(a - kE2m1Mag[i]);
if (d < bd || (d == bd && !(best & 1))) { bd = d; best = i; }
}
return (uint8_t)(best | (v < 0 ? 8 : 0));
}
static double e2m1_f64(uint8_t code) {
return (code & 8 ? -1.0 : 1.0) * kE2m1Mag[code & 7];
}
/* ------------------------------------------------------------------ the table checks */
static int check_lut() {
int fails = 0;
for (int d = 0; d < 16; ++d)
for (int k = 0; k < 4; ++k)
for (int m = 0; m < 8; ++m) {
const uint8_t got = (uint8_t)((kM2xfp4Mag[d][k][m >> 2] >> (8 * (m & 3))) & 0xFF);
const double exact = kE2m1Mag[m] * (1.0 + k / 4.0) * std::ldexp(1.0, -d);
const uint8_t want = rne_e4m3(exact);
if (got != want) {
std::printf("FAIL lut d=%d k=%d mag=%d: %02x, want %02x (%.6g)\n", d, k, m,
got, want, exact);
++fails;
continue;
}
/* k = 0..2 exact wherever the product is a normal e4m3 value; k = 3 only the
* odd-mantissa magnitudes round, and to the tie's even side. */
if (e4m3_f64(got) != exact) {
const bool k3tie = k == 3 && (m == 3 || m == 5 || m == 7);
const double rounded = k3tie ? std::ldexp(m == 3 ? 2.5 : m == 5 ? 5.0 : 10.0, -d)
: exact;
if (k3tie && e4m3_f64(got) == rounded) continue;
/* the subnormal floor: like r4d_mxfp4.h's table one binade earlier, the 2^-9
* step rounds once the product falls in it; exactness is only claimed while
* the product is normal (>= 2^-6), and every k = 0..2 normal product is */
if (k <= 2 && exact >= 0.015625 && std::fabs(exact) > 0) {
std::printf("FAIL lut k=%d d=%d mag=%d: %02x decodes %.6g, want %.6g\n", k,
d, m, got, e4m3_f64(got), exact);
++fails;
}
}
}
/* and the k = 0 rows are r4d_mxfp4.h's, byte for byte (a memcmp would walk the [k] axis) */
static const unsigned kM0[16][2] = {
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u}, {0x2c282000u, 0x3c383430u},
{0x24201800u, 0x34302c28u}, {0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u}, {0x03020100u, 0x0c080604u},
{0x02010000u, 0x06040302u}, {0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u},
};
for (int d = 0; d < 16; ++d)
if (kM2xfp4Mag[d][0][0] != kM0[d][0] || kM2xfp4Mag[d][0][1] != kM0[d][1]) {
std::printf("FAIL lut: the k=0 row d=%d is not kMxfp4Mag\n", d);
++fails;
}
return fails;
}
/* The unpack against arithmetic, over every 16-bit pattern at both halves of a word and random
* words, at every (d, k). */
static int check_unpack() {
int fails = 0;
auto one = [&](uint32_t word, int d, int k) {
uint32_t lo = 0, hi = 0;
r4d_m2xfp4_unpack8(word, d, k, &lo, &hi);
for (int j = 0; j < 8; ++j) {
const uint8_t code = (uint8_t)((word >> (4 * j)) & 0xF);
const uint8_t got = (uint8_t)((j < 4 ? (lo >> (8 * j)) : (hi >> (8 * (j - 4)))) & 0xFF);
const double exact = e2m1_f64(code) * (1.0 + k / 4.0) * std::ldexp(1.0, -d);
const uint8_t want = rne_e4m3(exact);
if (got != want) {
if (fails < 12)
std::printf("FAIL unpack w=%08x d=%d k=%d j=%d: %02x, want %02x\n", word, d, k,
j, got, want);
++fails;
}
}
};
for (int d = 0; d < 16; ++d)
for (int k = 0; k < 4; ++k) {
for (uint32_t v = 0; v < 65536; ++v) {
one(v, d, k);
if (v < 256) { one(v << 24, d, k); one(v << 16, d, k); }
}
}
std::mt19937 rng(11);
for (int i = 0; i < 20000; ++i) one(rng(), (int)(rng() % 16), (int)(rng() % 4));
return fails;
}
/* ------------------------------------------------------------------ the GEMM cases */
struct Case {
const char* name;
const char* kernel; // the decode row's two forms, or the tiled row
int M, N, K;
bool ablk; // the activation scale per (row, 128 of K), with a zero block
int ks; // the decode launch's split (0 = the kernel's rule)
};
/* The in-test quantiser's planes for one weight [N][K]: codes (packed e2m1, element 2j in bits
* 0-3 of byte j), the per-(row, 32) exponents with the bias folded in, the meta bytes, and the
* f64 exact dequant the reference multiplies. */
struct M2Weight {
std::vector<uint8_t> codes; // [N][K/2]
std::vector<uint8_t> scale; // [N][K/32]
std::vector<uint8_t> meta; // [N][K/32]
std::vector<double> exact; // [N][K], the spec's decode
};
static M2Weight m2_quantise(const std::vector<float>& w, int N, int K, std::mt19937& rng) {
const int nblk = K / 32;
M2Weight m;
m.codes.assign((size_t)N * K / 2, 0);
m.scale.assign((size_t)N * nblk, 0);
m.meta.assign((size_t)N * nblk, 0);
m.exact.assign((size_t)N * K, 0.0);
std::uniform_int_distribution<int> bias(-1, 1);
for (int n = 0; n < N; ++n)
for (int b = 0; b < nblk; ++b) {
double absmax = 0.0;
for (int j = 0; j < 32; ++j) absmax = std::max(absmax, (double)std::fabs(w[(size_t)n * K + b * 32 + j]));
/* the exponent the six-magnitude grid needs, plus the adaptive bias, folded into the
* stored byte; a zero group keeps a small exponent, its codes all zero */
int e8 = absmax > 0 ? (int)std::ceil(std::log2(absmax / 6.0)) : -30;
e8 += bias(rng);
if (e8 < -30) e8 = -30;
if (e8 > 30) e8 = 30;
const uint8_t sbyte = (uint8_t)(e8 + 127);
uint8_t mbyte = 0;
for (int s = 0; s < 4; ++s) {
/* k = 3 in heavy rotation, the multiplier the rounding lives on */
const int k = (n + b + s * 3 + (int)(rng() % 2)) & 3;
mbyte |= k << (2 * s);
for (int j = 0; j < 8; ++j) {
const int col = b * 32 + s * 8 + j;
const double scale = std::ldexp(1.0 + k / 4.0, e8);
const uint8_t code = rne_e2m1(w[(size_t)n * K + col] / scale);
m.codes[(size_t)n * K / 2 + col / 2] |=
(uint8_t)(code << (4 * (col & 1)));
m.exact[(size_t)n * K + col] =
e2m1_f64(code) * std::ldexp(1.0, e8) * (1.0 + k / 4.0);
}
}
m.scale[(size_t)n * nblk + b] = sbyte;
m.meta[(size_t)n * nblk + b] = mbyte;
}
return m;
}
/* The stored weight, as r4d_rad_relayout_m2xfp4 writes it: codes in WMMA fragment order, then the
* meta plane in the exponents' [K/32][N] order, and the exponent plane and per-row reference
* beside them. */
static void m2_store(const M2Weight& m, int N, int K, std::vector<uint8_t>* wq,
std::vector<uint8_t>* ws, std::vector<uint8_t>* wm,
std::vector<uint8_t>* wref) {
const int nblk = K / 32;
wq->assign((size_t)N * K / 2 + (size_t)nblk * N, 0);
ws->assign((size_t)nblk * N, 0);
wm->assign((size_t)nblk * N, 0);
wref->assign(N, 0);
/* fragment order: slot = ((t * ks + ksi) * 32 + lh * 16 + r) * 4 + bin, element 2j in the low
* nibble of byte j (r4d_layout.cpp, mx_slot) */
const int ks16 = K / 16;
for (int n = 0; n < N; ++n) {
const int t = n / 16, r = n % 16;
uint8_t ref = 0;
for (int b = 0; b < nblk; ++b) {
const uint8_t s = m.scale[(size_t)n * nblk + b];
(*ws)[(size_t)b * N + n] = s;
(*wm)[(size_t)b * N + n] = m.meta[(size_t)n * nblk + b];
if (s > ref) ref = s;
}
(*wref)[n] = ref;
for (int k = 0; k < K; ++k) {
const uint8_t code = (uint8_t)((m.codes[(size_t)n * K / 2 + k / 2] >> (4 * (k & 1))) & 0xF);
const int ksi = k / 16, kin = k % 16;
const int lh = kin / 8, bin = (kin % 8) / 2;
const size_t idx = (size_t)((t * ks16 + ksi) * 32 + lh * 16 + r) * 4 + bin;
(*wq)[idx] |= (uint8_t)(code << (4 * (k & 1)));
}
}
}
/* A bf16 as the kernels round it (f32_to_bf16, r4d_common.h's RNE). */
static uint16_t bf16_rne(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
static double bf16_f64(uint16_t h) {
const double s = h & 0x8000 ? -1.0 : 1.0;
const int e = (h >> 7) & 0xFF, m = h & 0x7F;
if (e == 0) return s * m * std::ldexp(1.0, -133); /* zero / bf16 subnormal */
return s * std::ldexp(1.0 + m / 128.0, e - 127);
}
static int run_cases() {
static const Case all[] = {
{ "decode1, K 128, rule split 16, per-row scales",
"(r4d_gemm_m2xfp4a8_decode1_kernel<128, 16, false, false>)", 1, 48, 128, false, 0 },
{ "decode1, K 64, split 4", "(r4d_gemm_m2xfp4a8_decode1_kernel<64, 4, false, false>)",
8, 16, 64, false, 4 },
{ "decode1, M 16, block scales", "(r4d_gemm_m2xfp4a8_decode1_kernel<128, 2, false, true>)",
16, 128, 256, true, 2 },
{ "decode, M 40 three fragments, odd K slab 192",
"(r4d_gemm_m2xfp4a8_decode_kernel<64, 1, 3, false, false>)", 40, 272, 192, false, 1 },
{ "decode, M 128 all fragments, block scales with a zero block",
"(r4d_gemm_m2xfp4a8_decode_kernel<128, 1, 8, false, true>)", 128, 128, 128, true, 1 },
{ "tiled, TN 2 just past the decode band, wide slab",
"(r4d_gemm_m2xfp4a8_tiled_kernel<2, 128, false>)", 129, 64, 128, false, 0 },
{ "tiled, TN 2, K 192 takes the 64 slab",
"(r4d_gemm_m2xfp4a8_tiled_kernel<2, 64, false>)", 300, 64, 192, false, 0 },
{ "tiled, TN 2, block scales", "(r4d_gemm_m2xfp4a8_tiled_kernel<2, 128, true>)",
256, 128, 128, true, 0 },
};
int fails = 0, cases = 0;
for (const Case& c : all) {
std::mt19937 rng(2000 + cases);
std::normal_distribution<double> nd(0.0, 1.0);
const int nblk = c.K / 32, nkb = (c.K + 127) / 128;
/* random f32 weights -> the m2xfp4 planes */
std::vector<float> wf((size_t)c.N * c.K);
for (auto& v : wf) v = (float)(3.5 * nd(rng));
const M2Weight m = m2_quantise(wf, c.N, c.K, rng);
std::vector<uint8_t> wq, ws, wm, wref;
m2_store(m, c.N, c.K, &wq, &ws, &wm, &wref);
/* fp8 activations and their grid. The bytes are the quantised values; the grid's scale is
* applied once, where the kernel applies it: per row in the epilogue, per (row, 128) at
* each boundary -- the reference multiplies the same way. */
const int PA = c.ablk ? nkb : 1;
std::vector<uint8_t> a((size_t)c.M * c.K);
std::vector<float> as((size_t)c.M * PA);
for (int i = 0; i < c.M; ++i)
for (int q = 0; q < PA; ++q) {
/* block 1 of every fourth row is zero: the carried-scale path */
const float s = c.ablk && i % 4 == 1 && q == 1
? 0.0f
: std::ldexp(1.0f, (int)((rng() % 7) - 3)) * (1.0f + (rng() % 97) / 97.0f);
as[(size_t)i * PA + q] = s;
}
for (int i = 0; i < c.M; ++i)
for (int k = 0; k < c.K; ++k) {
const float block_scale = as[(size_t)i * PA + (c.ablk ? k / 128 : 0)];
const float v = (float)(nd(rng) * 2.0);
/* a zero-scale block's activation bytes are zero (the block-scaled quantisers
* produce nothing there), and the kernels carry the previous scale through */
a[(size_t)i * c.K + k] =
block_scale == 0.0f ? 0 : rne_e4m3(v / block_scale);
}
/* the f64 reference: the activation's bytes (times the block grid, when there is one) and
* the exact weight decode, which already carries its 2^(scale - 127) */
std::vector<uint16_t> ref((size_t)c.M * c.N);
std::vector<double> reff((size_t)c.M * c.N);
for (int i = 0; i < c.M; ++i)
for (int n = 0; n < c.N; ++n) {
double acc = 0.0;
for (int k = 0; k < c.K; ++k)
acc += e4m3_f64(a[(size_t)i * c.K + k]) *
(c.ablk ? (double)as[(size_t)i * PA + k / 128] : 1.0) *
m.exact[(size_t)n * c.K + k];
if (!c.ablk) acc *= (double)as[(size_t)i];
reff[(size_t)i * c.N + n] = acc;
ref[(size_t)i * c.N + n] = bf16_rne((float)acc);
}
/* launch. The scratch is sized for the widest split the band's rule can pick (16), which
* the ABI's scratch hook bounds the same way. */
std::vector<uint16_t> got((size_t)c.M * c.N, 0x7777);
const long wq_ptr = (long)(uintptr_t)wq.data();
/* launch. The scratch is the widest split the band's rule can pick (16) plus the arrival
* counters, which ride its tail: R4D_M2D_MAX_N / (DWN*16) unsigned = 1152 B. */
const long scratch_bytes = 16l * c.M * c.N * (long)sizeof(float) + 1152;
std::vector<float> scratch((size_t)(scratch_bytes / sizeof(float)), 0.0f);
emu_last_kernel = "";
++cases;
if (std::strstr(c.kernel, "tiled")) {
std::vector<uint8_t> at((size_t)r4d_m2xfp4a8_tile_a_bytes(c.M, c.K));
r4d_m2xfp4a8_tile_a((long)(uintptr_t)a.data(), (long)(uintptr_t)at.data(), c.M, c.K,
0, 0);
r4d_gemm_m2xfp4a8_tiled((long)(uintptr_t)at.data(), (long)(uintptr_t)as.data(),
wq_ptr, (long)(uintptr_t)ws.data(), (long)(uintptr_t)wm.data(),
(long)(uintptr_t)wref.data(), (long)(uintptr_t)got.data(),
c.M, c.K, c.N, 0, c.ablk ? 128 : 0, PA,
0, c.N, c.N);
} else {
r4d_gemm_m2xfp4a8_decode((long)(uintptr_t)a.data(), (long)(uintptr_t)as.data(),
wq_ptr, (long)(uintptr_t)ws.data(), (long)(uintptr_t)wm.data(),
(long)(uintptr_t)wref.data(), (long)(uintptr_t)got.data(),
c.M, c.K, c.N, c.ks, 0, 0, c.ablk ? 128 : 0, PA,
(long)(uintptr_t)scratch.data(), scratch_bytes, 0, 0, c.N,
c.N);
}
/* every launch lands on one form; a moved bound shows by name */
if (!std::strstr(emu_last_kernel, c.kernel)) {
std::printf("FAIL %s: ran %s, want %s\n", c.name,
emu_last_kernel ? emu_last_kernel : "(nothing)", c.kernel);
++fails;
continue;
}
/* the FP8 WMMA's tolerance */
double num = 0, den = 0, worst = 0;
for (size_t i = 0; i < ref.size(); ++i) {
const double d = bf16_f64(got[i]) - reff[i];
num += d * d;
den += reff[i] * reff[i];
worst = std::max(worst, std::fabs(d) / (std::fabs(reff[i]) + 1e-3));
}
const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num);
/* The FP8 WMMA's tolerance, plus the table's accepted k = 3 rounding: the mxfp4 row's
* 1e-2 with the ~1.2% whole-dot contribution a full rotation of k = 3 subgroups adds
* (a quarter of the weights at up to 2^-4.4 each). Cancellation can make a single
* element's relative error unbounded, so the aggregate is what is held. */
if (rel >= 4e-2) {
std::printf("FAIL %s: rel_l2 %.3e, worst %.3e\n", c.name, rel, worst);
++fails;
}
}
std::printf("%d gemm case(s), %d failure(s)\n", cases, fails);
return fails;
}
int main() {
int fails = check_lut();
fails += check_unpack();
fails += run_cases();
if (fails) std::printf("FAIL m2xfp4 (%d)\n", fails);
return fails ? 1 : 0;
}
+4
View File
@@ -60,6 +60,10 @@ const std::vector<TolRow> g_tol = {
* gated GEMM also writes an E4M3 twin of its result, which a rounding difference in the GEMM
* moves by whole code steps (see g_opd_tol). */
{ "gemm_nt_q_gated", "*", 3e-2 },
/* The m2xfp4 fold's k = 3 multipliers round the odd-mantissa magnitudes as r4d_m2xfp4.h
* documents, up to 2^-4.4 relative on a quarter of the weights (the selftest's own margin
* over the mxfp4 tolerance below). */
{ "gemm_nt_q", "m2xfp4", 4e-2 },
{ "gemm_nt", "bf16", 8e-3 },
{ "gemm_nt", "f16", 4e-3 },
{ "gemm_nt", "f32", 2e-5 },
+110 -15
View File
@@ -1907,15 +1907,104 @@ int Replay::rerecord() {
return 0;
}
/* The gemm_nt_q mx/m2 family, re-encoded for a row the recording's container never fed: the
* m2xfp4 rows sit at the m2xfp4 encoding, which no in-tree container carries, and the OCP rows'
* mxfp4a8 cases exist only at containers this fixture was not recorded from. Moving a case
* between the two families keeps the codes and exponent planes -- the same planes at both -- and
* draws the meta plane beside them, whose every byte is a valid multiplier, so the reference
* records at the row's own encoding. `d` already carries the reference's description of the
* operand at the target dtype (`sh`); this fills its encoding and selection. False when the row
* is not after one of the two families, the base encoding is the same family or neither, or the
* planes do not line up: the caller's strict shape check then governs. */
static bool reencode_gemmx_weight(const KfOperand& b, const char* row_dtype, const OpdShape& sh,
KfOperand* d, std::string* why) {
if (!b.has_enc || !row_dtype) return false;
const bool to_m2 = std::strcmp(row_dtype, "m2xfp4") == 0;
const bool to_mx = std::strcmp(row_dtype, "mxfp4a8") == 0;
if (!to_m2 && !to_mx) return false;
auto bad = [&](const char* w) { if (why) *why = w; return false; };
/* The base family: the m2xfp4 quantiser's own scheme, or affine MXFP4 (codes plus one E8M0
* exponent a group of 32). */
const RadEncoding& e = b.enc;
const bool base_m2 = rad_enc_is(&e, "m2xfp4") && e.n_planes == 3;
const bool base_mx = rad_enc_is(&e, "affine") && e.n_planes >= 2;
if (base_m2 == base_mx) return bad("its weight is neither the mxfp4a8 nor the m2xfp4 grid");
if (to_m2 && base_m2) return false; /* same family: the plain copy serves */
if (to_mx && base_mx) return false;
const int ic = 0;
const int is = rad_enc_find(&e, "scale");
const int im = base_m2 ? rad_enc_find(&e, "meta") : -1;
if (is < 0 || (base_m2 && im < 0)) return bad("its encoding has no exponent (or meta) plane");
if (e.transform[0]) return bad("its weight carries a transform the target family does not");
if (e.plane[ic].dtype != RAD_FP4E2M1 || e.plane[ic].block[0] != 1 ||
e.plane[is].block[0] != 1 || e.plane[is].block[1] != 32 ||
std::strncmp(e.plane[ic].role, "codes", RAD_ENC_STR) != 0)
return bad("its codes and exponent planes are not the MXFP4 grid's");
/* The target encoding: the same codes and exponents, the meta plane beside them. */
RadEncoding t{};
rad_enc_copy_str(t.scheme, to_m2 ? "m2xfp4" : "affine");
rad_enc_add_plane(&t, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&t, "scale", RAD_E8M0, 1, 32);
if (to_m2) rad_enc_add_plane(&t, "meta", RAD_U8, 1, 32);
if (!rad_enc_valid(&t)) return bad("the re-encoded weight is not well formed");
/* What this operand reads, by the planes it selected: the weight (the codes, and the meta at
* m2) or a scale stream (b_scale and b_ref select the exponent plane). Its extents come from
* the plane it selected, in that plane's own elements. */
const bool codes_opd = std::find(b.sel.begin(), b.sel.end(), ic) != b.sel.end();
int64_t N = 0, kb = 0;
for (size_t k = 0; k < b.sel.size(); ++k) {
if (b.sel[k] == ic) { N = b.sel_rows[k]; kb = b.sel_cols[k] / 32; }
if (b.sel[k] == is) { N = b.sel_rows[k]; kb = b.sel_cols[k]; }
}
if (N <= 0 || kb <= 0) return bad("its planes are not a whole number of exponent groups");
const int64_t K = kb * 32;
auto fits = [&](const char* what, uint32_t dt, std::initializer_list<int64_t> shape) {
if (sh.dtype != dt || sh.shape != std::vector<int64_t>(shape)) {
if (why)
*why = std::string("the reference describes ") + what + " differently than the " +
(to_m2 ? "m2xfp4" : "mxfp4a8") + " grid implies";
return false;
}
return true;
};
std::vector<int> sel;
std::vector<int64_t> sel_rows, sel_cols;
if (codes_opd) {
if (to_m2) {
if (!fits("the weight", RAD_U8, { N * (K / 2 + kb) })) return false;
sel = { 0, 2 }; sel_rows = { N, N }; sel_cols = { K, kb };
} else {
if (!fits("the weight", RAD_FP4E2M1, { N, K })) return false;
sel = { 0 }; sel_rows = { N }; sel_cols = { K };
}
} else {
if (!fits("the scale stream", RAD_E8M0, { N, kb })) return false;
sel = { 1 }; sel_rows = { N }; sel_cols = { kb };
}
d->has_enc = true;
d->enc = t;
d->sel = std::move(sel);
d->sel_rows = std::move(sel_rows);
d->sel_cols = std::move(sel_cols);
return true;
}
/* ================================================================== the row-driven fixture
*
* A recording reaches only the rows its container's geometry selects; a row behind another band,
* tuned point or dtype never runs. For every row of every library under test, this moves an
* existing case of the row's op into the row's constraints (kb::satisfy_constraints) and records
* the reference's answer there. Only cases whose operand shapes the reference can describe from the
* parameters alone, and whose weights keep their shapes, are moved: a weight of another shape would
* need an encoding the base case does not carry. Replay the result with --all-rows, since a row
* a higher-priority row shadows is reached only that way. No container and no card are needed. */
* tuned point or dtype never runs. For every row of every library under test, this moves the
* fixtures' cases into the row's constraints (kb::satisfy_constraints) and records the reference's
* answer at every distinct geometry that lands there -- one case serves every row sharing it, and
* a row keeps sweeping instead of stopping at the first base case, so a band's whole M ladder is
* covered. Only cases whose operand shapes the reference can describe from the parameters alone,
* and whose weights keep their shapes (or re-encode, above), are moved: a weight of another shape
* would need an encoding the base case does not carry. Replay the result with --all-rows, since a
* row a higher-priority row shadows is reached only that way. No container and no card are
* needed. */
int Replay::record_rows() {
Kfixture out;
out.oracle = ref_name_;
@@ -1923,7 +2012,7 @@ int Replay::record_rows() {
for (size_t fi = 0; fi < fx_.size(); ++fi)
out.source += (out.source.empty() ? "rows from " : " + ") + fx_[fi].source;
std::set<std::string> seen;
int rows_total = 0, rows_recorded = 0;
int rows_total = 0, rows_served = 0, rows_recorded = 0;
std::map<std::string, int> why_not;
for (const KernelRow& r : reg_->rows()) {
if (!r.info || !r.info->launch || !r.info->op) continue;
@@ -1939,10 +2028,9 @@ int Replay::record_rows() {
if (!schema) continue;
++rows_total;
std::string last = "no recorded case of its op";
bool done = false;
for (size_t fi = 0; fi < fx_.size() && !done; ++fi) {
bool any = false;
for (size_t fi = 0; fi < fx_.size(); ++fi) {
for (const KfCase& base : fx_[fi].cases) {
if (done) break;
if (base.op != r.info->op || (int)base.opd.size() != schema->n_operands) continue;
Geometry g = case_geometry(base);
if (!kb::satisfy_constraints(r.info, &g)) {
@@ -1986,6 +2074,12 @@ int Replay::record_rows() {
d.idx_const = sh[k].idx_const;
d.fill_chunk = sh[k].fill_chunk;
if (d.role == RAD_OPD_WEIGHT || d.role == RAD_OPD_WTAB) {
/* The mx/m2 pair re-encodes between families; everything else must keep
* the weight the base case recorded. */
std::string rwhy;
if (!d.absent && b.has_enc &&
reencode_gemmx_weight(b, g.get_s("dtype"), sh[k], &d, &rwhy))
continue;
if (d.absent != b.absent || d.dtype != b.dtype || d.shape != b.shape) {
weights_kept = false;
break;
@@ -2015,17 +2109,18 @@ int Replay::record_rows() {
}
c.seed = rad_case_seed(base.seed, r.info->name, 0, r.info->domain, 0);
const std::string key = kb::cap_key(c, "", "", 0, g);
if (seen.count(key)) { done = true; ++rows_recorded; break; }
if (seen.count(key)) { any = true; continue; }
KfCase rc;
std::string why;
if (record_case(c, &rc, &why) != RAD_OK) { last = why; continue; }
seen.insert(key);
out.cases.push_back(std::move(rc));
++rows_recorded;
done = true;
any = true;
}
}
if (!done) why_not[std::string(r.plugin) + "/" + r.info->name + " (" + last + ")"]++;
if (any) ++rows_served;
else why_not[std::string(r.plugin) + "/" + r.info->name + " (" + last + ")"]++;
}
if (!why_not.empty()) {
std::printf("rows without a case\n");
@@ -2036,8 +2131,8 @@ int Replay::record_rows() {
RAD_ERR("--record-rows %s: %s", o_.record_rows_path.c_str(), rad_strerror(rc));
return 1;
}
std::printf("recorded %zu case(s) for %d of %d row(s) to %s; replay it with --all-rows\n",
out.cases.size(), rows_recorded, rows_total, o_.record_rows_path.c_str());
std::printf("recorded %zu case(s) reaching %d of %d row(s) to %s; replay it with --all-rows\n",
out.cases.size(), rows_served, rows_total, o_.record_rows_path.c_str());
return 0;
}
+595
View File
@@ -0,0 +1,595 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""rad-pack-m2xfp4 -- a ParoQuant M2XFP4 checkpoint into a .rad, the planes as they ship.
The path has two halves and this script owns the seam between them:
1. `paroquant.cli.convert --mode real` re-derives each module's codes from the trained weight,
under the M2XFP4 grid the optimizer trained with, and writes an ordinary Hugging Face
checkpoint: per linear `X.weight` (e2m1 nibbles [N, K/2]), `X.weight_scale` (e8m0 [N, K/32]),
`X.weight_meta` (u8 [N, K/32]) and the learned rotation (`X.theta`, `X.pairs`,
`X.channel_scales`), with `quantization_config.quant_method = "paroquant_m2xfp4"`.
It needs a GPU (its rotation is a CUDA kernel); this script runs it when handed a result
directory (quant_grid.json + per-module .pt) and `--convert-with`.
2. `rad-convert` imports those planes (core/format/checkpoint.cpp, Import::ParoM2): the codes,
exponents and metadata bytes become the weight's three planes byte for byte, the rotation
becomes the encoding's "givens" tables, and nothing is dequantised or re-quantised. It is
CPU-only, so it runs beside a serving GPU.
Then this script 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 ones the checkpoint
ships (t.scale == 1/channel_scales in f32, t.pairs offset to whole-row columns, t.angle widened).
A mismatch is an error, not a warning.
rad-pack-m2xfp4 SRC [-o OUT.rad] [--recipe FILE] [--draft DIR]
[--rad-convert PATH] [--home DIR] [--jobs N]
[--convert-with 'CMD with {model} {result_dir} {out}'] [--model BASE]
[--convert-path FROM=TO ...] [--verify-only] [--list] [--skip-tables]
SRC is a converted checkpoint directory, or a ParoQuant result directory (then --model and
--convert-with run the convert first, into `--hf-out`, default `<SRC>/hf`).
The full model, once the fine-tune lands:
tools/rad_pack_m2xfp4.py /media/zee/ai/paro-out-ft-m2xfp4/Qwen3.8-27B-fp16 \\
--model /staging/Qwen3.8-27B-fp16 \\
--convert-with 'docker exec paro_stage2 python3 -m paroquant.cli.convert \\
--model {model} --result-dir {result_dir} --output-path {out} --mode real' \\
--hf-out /media/zee/ai/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
The recipe covers what the checkpoint does NOT ship in a form the architecture declares (f32
norms, the bf16 embedding, the head); the trunk's linears need no rule, because they are imported.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import mmap
import os
import shlex
import struct
import subprocess
import sys
# ------------------------------------------------------------------ .rad reader
# abi/rad_format.h, frozen. Values are the ABI's, not this script's guesses.
HDR = struct.Struct("<IIQ" + "5Q" + "16Q" + "8Q") # 248 bytes
ENTRY = struct.Struct("<3QII6q4i3Q2Q") # 136 bytes
PLANE = struct.Struct("<2Q") # 16 bytes
ENC = struct.Struct("<24s24sii") # scheme, transform, n_planes, reserved
ENC_PLANE = struct.Struct("<24sII2q2q") # role, dtype, kind, block, extent
ENC_STRIDE = ENC.size + 8 * ENC_PLANE.size # 568: the header, then its 8 plane slots
RAD_MAX_RANK = 6
RAD_PLANE_TILED = 0
RAD_PLANE_TABLE = 1
RAD_DTYPE_BITS = {
1: 8, 2: 16, 3: 16, 4: 8, 5: 8, 6: 8, 8: 8, 9: 8, 10: 8, 11: 8, 12: 8, 13: 16,
14: 16, 15: 8, 16: 16, 17: 32, 18: 4, 19: 6, 20: 6, 21: 8, 22: 8, 23: 8, 24: 16,
}
RAD_U8 = 9
RAD_I32 = 17
RAD_F32 = 15
RAD_F16 = 2
RAD_E8M0 = 21
RAD_FP4E2M1 = 18
class RadFile:
"""The reader: mmap, header, string blob, directory, encodings, planes."""
def __init__(self, path: str):
self.path = path
self.f = open(path, "rb")
self.mm = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ)
h = HDR.unpack_from(self.mm, 0)
magic, version, self.file_bytes = h[0], h[1], h[2]
if magic != 0x31444152 or version != 2:
raise SystemExit(f"{path}: not a RAD1 version 2 container (magic {magic:#x}, "
f"version {version})")
# h[0..2] magic/version/file_bytes, h[3..7] the five strings, then the tables.
self.str_off, self.str_bytes = h[8], h[9]
(self.meta_off, self.meta_count, self.dir_off, self.dir_count, self.plane_off,
self.plane_count, self.enc_off, self.enc_count) = h[10:18]
self.data_off, self.data_bytes = h[22], h[23]
if (self.dir_off + self.dir_count * ENTRY.size > self.file_bytes or
self.enc_off + self.enc_count * ENC_STRIDE > self.file_bytes):
raise SystemExit(f"{path}: tables run past the file (truncated?)")
def close(self):
self.mm.close()
self.f.close()
def s(self, off: int) -> str:
end = self.mm.find(b"\0", self.str_off + off)
return self.mm[self.str_off + off:end].decode()
def entry(self, i: int):
name, quant, opts, enc, rank, *rest = ENTRY.unpack_from(self.mm,
self.dir_off + i * ENTRY.size)
shape = tuple(rest[0:6])
layer, expert, slot, nplanes = rest[6:10]
plane_first, offset, nbytes = rest[10:13]
return {
"name": self.s(name), "quantizer": self.s(quant), "options": self.s(opts),
"enc": enc, "rank": rank, "shape": shape[:rank], "layer": layer, "expert": expert,
"slot": slot, "n_planes": nplanes, "plane_first": plane_first, "offset": offset,
"bytes": nbytes,
}
def encoding(self, i: int):
base = self.enc_off + i * ENC_STRIDE
scheme, transform, n_planes, _reserved = ENC.unpack_from(self.mm, base)
planes = []
for k in range(n_planes):
role, dt, kind, b0, b1, e0, e1 = ENC_PLANE.unpack_from(
self.mm, base + ENC.size + k * ENC_PLANE.size)
planes.append({"role": role.split(b"\0")[0].decode(), "dtype": dt, "kind": kind,
"block": (b0, b1), "extent": (e0, e1)})
return {"scheme": scheme.split(b"\0")[0].decode(),
"transform": transform.split(b"\0")[0].decode(), "planes": planes}
def plane(self, e, k: int):
off, nbytes = PLANE.unpack_from(self.mm, self.plane_off + (e["plane_first"] + k) *
PLANE.size)
return off, nbytes
def plane_bytes(self, e, role: str):
for k, p in enumerate(self.encoding(e["enc"])["planes"]):
if p["role"] == role:
off, nbytes = self.plane(e, k)
return self.mm[off:off + nbytes]
raise KeyError(f"{e['name']}: no plane '{role}'")
# ------------------------------------------------------------------ safetensors
def st_header(path: str):
with open(path, "rb") as f:
n = struct.unpack("<Q", f.read(8))[0]
return json.loads(f.read(n)), 8 + n
def shard_list(src: str):
"""Every safetensors shard of a checkpoint directory, in index order when it has one."""
idx = os.path.join(src, "model.safetensors.index.json")
if os.path.exists(idx):
with open(idx) as f:
weight_map = json.load(f)["weight_map"]
return [os.path.join(src, s) for s in sorted(set(weight_map.values()))]
found = sorted(os.path.join(src, n) for n in os.listdir(src)
if n.endswith(".safetensors"))
if not found:
raise SystemExit(f"{src}: no *.safetensors and no index")
return found
class Checkpoint:
"""Tensor metadata by name, read from the shard headers; bytes on demand."""
def __init__(self, src: str):
self.src = src
self.t = {}
self._fds = {}
for shard in shard_list(src):
header, base = st_header(shard)
for name, info in header.items():
if name == "__metadata__":
continue
self.t[name] = (shard, base + info["data_offsets"][0],
info["data_offsets"][1] - info["data_offsets"][0],
info["dtype"], tuple(info["shape"]))
def get(self, name: str):
if name not in self.t:
return None
shard, off, n, dtype, shape = self.t[name]
f = self._fds.get(shard)
if f is None:
f = self._fds[shard] = open(shard, "rb")
f.seek(off)
data = f.read(n)
if len(data) != n:
raise SystemExit(f"{name}: short read from {shard}")
return data, dtype, shape
def close(self):
for f in self._fds.values():
f.close()
self._fds.clear()
def config(self):
with open(os.path.join(self.src, "config.json")) as f:
return json.load(f)
def m2_modules(ck: Checkpoint):
"""Every `X` whose three M2XFP4 planes ship, with the shapes checked against each other."""
mods, bad = {}, []
for name in ck.t:
if not name.endswith(".weight"):
continue
base = name[:-len(".weight")]
w = ck.t.get(name)
sc = ck.t.get(base + ".weight_scale")
mt = ck.t.get(base + ".weight_meta")
if not (w and sc and mt):
continue
wd, wsh = w[3], w[4]
sd, ssh = sc[3], sc[4]
md, msh = mt[3], mt[4]
if wd != "U8" or sd != "U8" or md != "U8" or len(wsh) != 2 or len(ssh) != 2:
bad.append(f"{base}: dtypes {wd}/{sd}/{md} or ranks {len(wsh)}/{len(ssh)}")
continue
N, Kh = wsh
if ssh != (N, Kh // 16) or msh != ssh:
bad.append(f"{base}: weight {wsh} does not pair with scale/meta {ssh}")
continue
mods[base] = {"weight": name, "scale": base + ".weight_scale",
"meta": base + ".weight_meta", "N": N, "K": Kh * 2}
return mods, bad
def h16(b: bytes) -> str:
return hashlib.blake2b(b, digest_size=16).hexdigest()
# ------------------------------------------------------------------ pack
def run(cmd, env=None):
print("+ " + " ".join(shlex.quote(c) for c in cmd), flush=True)
rc = subprocess.run(cmd, env=env).returncode
if rc != 0:
raise SystemExit(f"failed ({rc}): {' '.join(cmd)}")
def main() -> int:
ap = argparse.ArgumentParser(prog="rad-pack-m2xfp4", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("src", nargs="?", help="a converted checkpoint directory, or a ParoQuant "
"result directory (omit with --list)")
ap.add_argument("-o", "--out", help="the .rad to write (default: SRC/<name>.rad)")
ap.add_argument("--recipe", help="rad-convert recipe (data/recipes/q38-27b-paro-m2xfp4-df2.recipe)")
ap.add_argument("--draft", help="a drafter checkpoint merged as dflash.*")
ap.add_argument("--rad-convert", default=os.environ.get("RAD_CONVERT", "rad-convert"),
help="the converter (default $RAD_CONVERT, else rad-convert on PATH)")
ap.add_argument("--home", help="RADIANCE_HOME for the plugins")
ap.add_argument("--jobs", type=int, default=0,
help="threads for rad-convert (OMP_NUM_THREADS; 0: the build's default)")
ap.add_argument("--convert-with", help="run `paroquant.cli.convert --mode real` through this "
"command, with {model} {result_dir} {out} substituted")
ap.add_argument("--model", help="the donor checkpoint `convert --model` reads (a result "
"directory's weights are the fine-tune's)")
ap.add_argument("--hf-out", help="where --convert-with writes (default: SRC/hf); a host path")
ap.add_argument("--convert-path", action="append", default=[], metavar="FROM=TO",
help="a prefix the convert runtime sees differently (docker exec of a "
"container whose /models is this machine's ~/models); applied to {model}, "
"{result_dir} and {out} only. Repeatable")
ap.add_argument("--verify-only", action="store_true", help="skip rad-convert; verify -o")
ap.add_argument("--list", action="store_true", help="print the container's m2xfp4 entries and stop")
ap.add_argument("--skip-tables", action="store_true",
help="verify the three code planes only, not the rotation tables")
ap.add_argument("--meta-sample", type=int, default=1 << 20,
help="metadata bytes to sample per weight (0: none)")
ap.add_argument("--extra", nargs=argparse.REMAINDER,
help="further rad-convert arguments, after `--`")
a = ap.parse_args()
if not a.src and not a.list:
ap.error("SRC is required (a checkpoint directory, or a result directory with --convert-with)")
src = os.path.abspath(a.src or "")
if a.list:
path = a.out or (src if src.endswith(".rad") else None)
if not path:
raise SystemExit("--list reads a container: pass it with -o (or as SRC when it ends "
"in .rad)")
rf = RadFile(path)
n = 0
for i in range(rf.dir_count):
e = rf.entry(i)
enc = rf.encoding(e["enc"])
if enc["scheme"] == "m2xfp4":
n += 1
print(f" {e['name']:<40} {e['shape']} {enc['transform'] or 'plain'} "
f"{e['n_planes']} plane(s) {e['bytes'] / 1e6:.3f} MB")
print(f"{path}: {n} m2xfp4 entr(ies) of {rf.dir_count}")
return 0
result_dir = os.path.isdir(src) and os.path.exists(os.path.join(src, "quant_grid.json"))
if result_dir:
if not (a.model and a.convert_with):
raise SystemExit(f"{src} is a ParoQuant result directory: it holds trained weights and "
"the grid, not the packed planes. Pass --model (the donor) and "
"--convert-with, which runs paroquant.cli.convert --mode real first. "
"See this file's docstring for the full-model command.")
hf = os.path.abspath(a.hf_out or os.path.join(src, "hf"))
maps = []
for spec in a.convert_path:
if "=" not in spec:
raise SystemExit(f"--convert-path {spec}: expected FROM=TO")
frm, to = spec.split("=", 1)
maps.append((os.path.abspath(frm).rstrip("/"), to.rstrip("/")))
maps.sort(key=lambda m: -len(m[0]))
def seen_by_convert(path):
for frm, to in maps:
if path == frm or path.startswith(frm + "/"):
return to + path[len(frm):]
return path
cmd = a.convert_with.format(model=seen_by_convert(os.path.abspath(a.model)),
result_dir=seen_by_convert(src),
out=seen_by_convert(hf))
run(shlex.split(cmd))
if not os.path.isdir(hf):
raise SystemExit(f"convert wrote {seen_by_convert(hf)} and this host does not see {hf}"
"; pass --convert-path so the two spellings meet")
src = hf
ck = Checkpoint(src)
qc = ck.config().get("quantization_config") or {}
if qc.get("quant_method") != "paroquant_m2xfp4":
raise SystemExit(f"{src}: quantization_config.quant_method is "
f"{qc.get('quant_method')!r}, not 'paroquant_m2xfp4'; this packs the "
"M2XFP4 checkpoint paroquant.cli.convert --mode real writes")
mods, bad = m2_modules(ck)
print(f"checkpoint {src}\n {len(mods)} M2XFP4 module(s), grid "
f"adaptive={qc.get('adaptive')} wide={qc.get('wide')} fold={qc.get('fold')}, "
f"krot={qc.get('krot')}")
if bad:
for b in bad[:20]:
print(f" malformed: {b}")
raise SystemExit(f"{len(bad)} malformed module(s); nothing written")
out = os.path.abspath(a.out or os.path.join(os.path.dirname(src),
os.path.basename(src.rstrip("/")) + ".rad"))
if not a.verify_only:
cmd = [a.rad_convert, src, "-o", out]
if a.recipe:
cmd += ["--recipe", a.recipe]
if a.draft:
cmd += ["--draft-model", a.draft]
env = dict(os.environ)
if a.jobs:
env["OMP_NUM_THREADS"] = str(a.jobs) # rad-convert threads across weights
if a.home:
env["RADIANCE_HOME"] = a.home
cmd += [x for x in (a.extra or []) if x != "--"]
run(cmd, env=env)
if not os.path.exists(out):
raise SystemExit(f"{out} does not exist; --verify-only needs a container")
rf = RadFile(out)
if a.list:
n = 0
for i in range(rf.dir_count):
e = rf.entry(i)
enc = rf.encoding(e["enc"])
if enc["scheme"] == "m2xfp4":
n += 1
print(f" {e['name']:<40} {e['shape']} {enc['transform'] or 'plain'} "
f"{e['n_planes']} plane(s) {e['bytes'] / 1e6:.3f} MB")
print(f" {n} m2xfp4 entr(ies)")
return 0
# ---- verification: the seam, byte for byte
print(f"container {out}\n {rf.dir_count} entries, {rf.data_bytes / 1e9:.2f} GB of planes")
by_codes = {}
for base, m in mods.items():
data, _, _ = ck.get(m["weight"])
by_codes.setdefault(h16(data), []).append(base)
# Arch row-joins (ffn_gate_up = mlp.gate_proj+mlp.up_proj, ssm_inz = in_proj_qkv+in_proj_z):
# the container stores the two pieces' planes concatenated row by row, so a fused entry's
# codes hash can never equal a single checkpoint tensor's. Resolve a miss as a join of two
# same-K modules whose Ns sum to the entry's, and register it as a synthetic module whose
# scale/meta planes are the pieces' concatenation.
def joined_base(codes, N, K):
by_n = {}
for b, m in mods.items():
if m["K"] == K:
by_n.setdefault(m["N"], []).append(b)
row_bytes = K // 2
for n_a, bases_a in by_n.items():
if n_a >= N or (N - n_a) not in by_n:
continue
da, _, _ = ck.get(mods[bases_a[0]]["weight"])
if h16(codes[: n_a * row_bytes]) != h16(da):
continue
for b_b in by_n[N - n_a]:
db, _, _ = ck.get(mods[b_b]["weight"])
if h16(codes[n_a * row_bytes:]) != h16(db):
continue
name = f"{bases_a[0]}+{b_b}"
mods[name] = {
"weight": name, "N": N, "K": K, "joined": True,
"scale": bytes(ck.get(mods[bases_a[0]]["scale"])[0])
+ bytes(ck.get(mods[b_b]["scale"])[0]),
"meta": bytes(ck.get(mods[bases_a[0]]["meta"])[0])
+ bytes(ck.get(mods[b_b]["meta"])[0]),
}
return name
return None
n_ent = n_ok = 0
codes_mismatch, other_mismatch = [], []
table_checked = table_bad = 0
meta_probed = 0
for i in range(rf.dir_count):
e = rf.entry(i)
enc = rf.encoding(e["enc"])
if enc["scheme"] != "m2xfp4":
continue
n_ent += 1
if n_ent % 100 == 0:
print(f" ... {n_ent} entr(ies) checked", flush=True)
if e["name"].startswith("dflash."):
# The drafter is rule-quantized from the unrotated --draft checkpoint: 'plain'
# planes are its design (the shipped q38-27b-m2xfp4-df2.rad carries exactly these
# and serves), so the rotated-basis requirement below applies to the trunk only.
continue
if enc["transform"] != "givens":
other_mismatch.append(f"{e['name']}: transform {enc['transform']!r}, not 'givens' -- "
"the fine-tune's codes are in a rotated basis, so an unrotated "
"m2xfp4 weight here means the wrong checkpoint was packed")
continue
codes = bytes(rf.plane_bytes(e, "codes"))
cand = by_codes.get(h16(codes))
if not cand:
j = joined_base(codes, e["shape"][0], e["shape"][1])
if j:
cand = [j]
if not cand:
codes_mismatch.append(f"{e['name']}: codes match no checkpoint tensor")
continue
base = cand[0] if len(cand) == 1 else next(
(c for c in cand if mods[c]["N"] * mods[c]["K"] == e["shape"][0] * e["shape"][1]),
cand[0])
m = mods[base]
ok = True
for role, key in (("scale", "scale"), ("meta", "meta")):
v = m[key]
want = v if isinstance(v, (bytes, bytearray)) else ck.get(v)[0]
got = bytes(rf.plane_bytes(e, role))
if got != want:
other_mismatch.append(f"{e['name']}: {role} plane differs from {m[key]}")
ok = False
if a.meta_sample:
v = m["meta"]
want = v if isinstance(v, (bytes, bytearray)) else ck.get(v)[0]
step = max(1, len(want) // a.meta_sample)
meta_probed += len(want[::step])
if not a.skip_tables and ok and not m.get("joined"):
# joined entries stack their pieces' tables per row-part (abi/rad_encoding.h
# "givens"); check_tables reads a single module's tensors, so the fused table
# check is the parity tests' job, not this seam check.
table_checked += 1
bad_tbl = check_tables(rf, e, enc, ck, m, e["name"])
if bad_tbl:
table_bad += 1
other_mismatch.extend(bad_tbl)
ok = False
n_ok += ok
print(f" verified {n_ok}/{n_ent} entr(ies): 3 code planes byte-identical, "
f"{table_checked - table_bad} rotation set(s) exact, "
f"{meta_probed} metadata byte(s) sampled")
for m in codes_mismatch + other_mismatch:
print(f" MISMATCH {m}")
rf.close()
if n_ent == 0:
print(" no m2xfp4 entry in the container", file=sys.stderr)
return 1
return 0 if n_ok == n_ent else 1
def compose_dense(pairs, theta, S, K):
"""abi/rad_encoding.h's t.dense: per group of 128, the stages composed in f64, f16 once."""
G = 128
ng = K // G
out = bytearray()
for g in range(ng):
ia = [[pairs[s * K + g * G + 2 * j] for j in range(G // 2)] for s in range(S)]
ib = [[pairs[s * K + g * G + 2 * j + 1] for j in range(G // 2)] for s in range(S)]
an = [[struct.unpack("<f", struct.pack("<f", theta[s * (K // 2) + g * (G // 2) + j]))[0]
for j in range(G // 2)] for s in range(S)]
cs = [[math.cos(a) for a in row] for row in an]
sn = [[math.sin(a) for a in row] for row in an]
cols = []
for i in range(G):
v = [0.0] * G
v[i] = 1.0
for s in range(S):
for j in range(G // 2):
a, b = ia[s][j], ib[s][j]
va, vb = v[a], v[b]
v[a] = va * cs[s][j] + vb * sn[s][j]
v[b] = vb * cs[s][j] - va * sn[s][j]
cols.append(v)
for j in range(G):
for i in range(G):
# the converter rounds the f64 composition to f32, then to f16
out += struct.pack("<e", struct.unpack("<f", struct.pack("<f", cols[i][j]))[0])
return bytes(out)
def check_tables(rf, e, enc, ck, m, name):
"""The rotation as the container stores it: t.scale = 1/channel_scales (f32), t.pairs offset to
whole-row columns, t.angle widened from f16. Returns the differences."""
roles = {p["role"]: p for p in enc["planes"]}
base = m["weight"][:-len(".weight")]
out = []
theta = ck.get(base + ".theta")
pairs = ck.get(base + ".pairs")
cs = ck.get(base + ".channel_scales")
if not (theta and pairs and cs):
return [f"{name}: checkpoint lacks theta/pairs/channel_scales"]
th, thd, thsh = theta
pr, prd, prsh = pairs
csc, csd, cssh = cs
if thd != "F16" or prd != "I16" or csd != "F16":
return [f"{name}: table dtypes {thd}/{prd}/{csd}"]
S, K = prsh
if thsh != (S, K // 2) or cssh != (1, K) or e["shape"][-1] != K:
return [f"{name}: tables {prsh}/{thsh}/{cssh} for a {e['shape']} weight"]
# t.scale: one f32 row a part, 1.0f / f16 as the converter computes it.
got = bytes(rf.plane_bytes(e, "t.scale"))
cs_rows = len(got) // (K * 4)
if cs_rows * K * 4 != len(got):
return [f"{name}: t.scale is {len(got)} bytes for K={K}"]
vals = struct.unpack("<%df" % (K * cs_rows), got)
ref = struct.unpack("<%de" % K, csc)
for p in range(cs_rows):
for c in range(K):
fv = struct.unpack("<f", struct.pack("<f", 1.0 / ref[c]))[0]
if vals[p * K + c] != fv:
out.append(f"{name}: t.scale[{p}][{c}] {vals[p * K + c]!r} != 1/{ref[c]!r}")
break
if out:
break
# t.angle: f32 rows, part-major, equal to the f16 angles widened.
ga = struct.unpack("<%df" % (len(rf.plane_bytes(e, "t.angle")) // 4),
bytes(rf.plane_bytes(e, "t.angle")))
ta = struct.unpack("<%de" % (S * (K // 2)), th)
if len(ga) != len(ta):
return out + [f"{name}: t.angle holds {len(ga)} values for {len(ta)} angles"]
for i, (x, y) in enumerate(zip(ga, ta)):
if x != y:
out.append(f"{name}: t.angle[{i}] {x!r} != {y!r}")
break
# t.scale/t.angle/t.pairs are the checkpoint's tables re-spelled one row at a time, so the
# three checks above cover them exactly. t.dense is composed here instead (f64, one f16
# rounding), and only when the weight is one part: a fused projection's parts compose from
# their own pieces' tables, which the checks above see row by row.
if "t.dense" in roles:
gd = bytes(rf.plane_bytes(e, "t.dense"))
want = compose_dense(struct.unpack("<%dh" % (S * K), pr),
struct.unpack("<%de" % (S * (K // 2)), th), S, K)
parts = len(gd) // len(want) if want else 0
if parts != cs_rows:
out.append(f"{name}: t.dense holds {len(gd)} bytes, {cs_rows} part(s) of "
f"{len(want)}")
elif gd != want * parts:
out.append(f"{name}: t.dense is not the rotation composed over groups of 128 "
"(f16, one rounding)")
# t.pairs: int32 [P*S][K], stage s's group-local pair plus the group's base column.
gp = struct.unpack("<%di" % (len(rf.plane_bytes(e, "t.pairs")) // 4),
bytes(rf.plane_bytes(e, "t.pairs")))
tp = struct.unpack("<%dh" % (S * K), pr)
if len(gp) != len(tp):
return out + [f"{name}: t.pairs holds {len(gp)} values for {len(tp)} pairs"]
for i in range(S * K):
c = i % K
if gp[i] != (c // 128) * 128 + tp[i]:
out.append(f"{name}: t.pairs[{i}] {gp[i]} != {(c // 128) * 128 + tp[i]}")
break
return out
if __name__ == "__main__":
sys.exit(main())