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
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