#!/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 `/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(" 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(" 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/.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("