Archived
M2XFP4 (MXFP4v2): quantiser, gfx1201 WMMA kernels, host rows, df2 wiring, .rad packer (Import::ParoM2), stability fixes (counters-in-scratch x3, aql publish fences), kbench rows, runbook (REMAINING.md)
This commit is contained in:
1 parent
9eaf10da6e
commit
ea0908596b
60 files changed
+4619
-193
No files matched your search
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Executable
+549
@@ -0,0 +1,549 @@
|
||||
#!/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)
|
||||
|
||||
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 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:
|
||||
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")):
|
||||
want, _, _ = ck.get(m[key])
|
||||
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:
|
||||
want, _, _ = ck.get(m["meta"])
|
||||
step = max(1, len(want) // a.meta_sample)
|
||||
meta_probed += len(want[::step])
|
||||
if not a.skip_tables and ok:
|
||||
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())
|
||||
Reference in new issue
Block a user