Inkling-2-Mini-NVFP4-M2 / scripts /repack_native.py
sambit9238's picture
Inkling-2-Mini NVFP4 M2: W4A16 local attention + lm_head, NVFP4 L20-23 experts
688186a verified
Raw History Blame Contribute Delete
9.33 kB
#!/usr/bin/env python
"""Build a servable Inkling-2-Mini checkpoint from the official one.
Stage A (--experts FILE): replace layer 20-23 MXFP8 experts with native-NVFP4 tensors from quant_experts.py and move
their names from the mxfp8 to the nvfp4 parameter group (stock vLLM/SGLang images load this).
Stage B (--attn-layers / --lm-head): NVFP4 weight-only (W4A16) attention for local layers and the lm_head, quantized
here with ModelOpt's NVFP4QTensor (same scale search as quant_experts.py), stored in ModelOpt layout:
W = e2m1 * e4m3(weight_scale[n, k//16]) * weight_scale_2 (low nibble = even k)
per local layer N: attn.q_side = concat(wq_du, wr_du, gate_attn, attn_sink_proj) rows (one GEMM, one global scale)
attn.wk_dv, attn.wv_dv, attn.wo_ud
lm_head: model.llm.unembed
listed in a new hf_quant_config group with compute_dtype "nvfp4_w4a16" (needs the overlay in overlay/inkling2).
Everything else is byte-copied. Output is sharded (~4 GB) so peak RAM stays low.
"""
import argparse
import hashlib
import json
import os
import shutil
import sys
import torch
from safetensors import safe_open
from safetensors.torch import save_file
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from quant_experts import DENOM, open_ckpt, quant_expert, unpack_e2m1 # noqa: E402
Q_SIDE = ("wq_du", "wr_du", "gate_attn", "attn_sink_proj")
SHARD_BYTES = 2 << 30
def nbytes(t):
return t.numel() * t.element_size()
class ShardWriter:
def __init__(self, out_dir):
self.out_dir, self.buf, self.size, self.files, self.weight_map = out_dir, {}, 0, [], {}
def add(self, name, t):
assert name not in self.weight_map and name not in self.buf, name
self.buf[name] = t.contiguous()
self.size += nbytes(t)
if self.size >= SHARD_BYTES:
self.flush()
def flush(self):
if not self.buf:
return
fname = f"model-{len(self.files) + 1:05d}.safetensors"
save_file(self.buf, os.path.join(self.out_dir, fname), metadata={"format": "pt"})
for n in self.buf:
self.weight_map[n] = fname
self.files.append(fname)
self.buf, self.size = {}, 0
def finish(self):
self.flush()
total = len(self.files)
mapping = {}
for i, f in enumerate(self.files):
new = f"model-{i + 1:05d}-of-{total:05d}.safetensors"
os.rename(os.path.join(self.out_dir, f), os.path.join(self.out_dir, new))
mapping[f] = new
self.weight_map = {n: mapping[f] for n, f in self.weight_map.items()}
return self.weight_map
def quant_w4a16(W, method, device="cuda"):
"""W [N, K] bf16/fp32 -> (packed U8 [N, K/2], scale F8 [N, K/16], scale_2 F32 scalar, rel_err)."""
Wf = W.float().to(device)
packed, scale, amax = quant_expert(Wf, method)
s2 = (amax / DENOM).float()
deq = unpack_e2m1(packed).view(Wf.shape[0], -1, 16) * (scale.float() * s2).unsqueeze(-1)
err = ((deq.view_as(Wf) - Wf).pow(2).sum() / Wf.pow(2).sum()).sqrt().item()
return packed.cpu(), scale.cpu(), s2.reshape(()).cpu(), err
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", required=True, help="official checkpoint dir")
ap.add_argument("--out", required=True)
ap.add_argument("--experts", help="safetensors from quant_experts.py (stage A)")
ap.add_argument("--attn-layers", default="", help="'local' for all local layers, or comma list, or '' for none")
ap.add_argument("--lm-head", action="store_true")
ap.add_argument("--method", choices=["max", "mse"], default="mse")
ap.add_argument("--device", default="cuda", help="cpu if the GPU is busy (slower)")
args = ap.parse_args()
cfg = json.load(open(os.path.join(args.ckpt, "config.json")))["text_config"]
local = set(cfg["local_layer_ids"])
if args.attn_layers == "local":
attn_layers = sorted(local)
else:
attn_layers = sorted(int(x) for x in args.attn_layers.split(",") if x.strip())
assert set(attn_layers) <= local, f"only local layers may be quantized: {set(attn_layers) - local}"
os.makedirs(args.out, exist_ok=True)
idx, get = open_ckpt(args.ckpt)
names = list(idx)
hfq = json.load(open(os.path.join(args.ckpt, "hf_quant_config.json")))
groups = hfq["model"]["parameter_groups"]
report = {"args": vars(args), "attn_layers": attn_layers, "rel_err": {}}
experts = {}
if args.experts:
with safe_open(args.experts, framework="pt", device="cpu") as f:
experts = {n: f.get_tensor(n) for n in f.keys()}
expert_weights = {n for n in experts if n.endswith(("w13_weight", "w2_weight"))}
drop = set()
for L in attn_layers:
for p in (*Q_SIDE, "wk_dv", "wv_dv", "wo_ud"):
drop.add(f"model.llm.layers.{L}.attn.{p}.weight")
if args.lm_head:
drop.add("model.llm.unembed.weight")
for n in expert_weights: # old MXFP8 tensors of the replaced expert layers
drop.update({n, n + "_scale"})
missing = drop - set(names)
assert not missing, f"expected tensors not in checkpoint: {sorted(missing)[:5]}"
w = ShardWriter(args.out)
for n in names: # byte-copy everything we keep
if n not in drop:
w.add(n, get(n))
for n, t in experts.items():
w.add(n, t)
new_w4a16 = []
for L in attn_layers:
pre = f"model.llm.layers.{L}.attn."
parts = {"q_side": torch.cat([get(f"{pre}{p}.weight") for p in Q_SIDE], 0),
"wk_dv": get(f"{pre}wk_dv.weight"), "wv_dv": get(f"{pre}wv_dv.weight"),
"wo_ud": get(f"{pre}wo_ud.weight")}
for p, W in parts.items():
packed, scale, s2, err = quant_w4a16(W, args.method, args.device)
w.add(f"{pre}{p}.weight", packed)
w.add(f"{pre}{p}.weight_scale", scale)
w.add(f"{pre}{p}.weight_scale_2", s2)
new_w4a16.append(f"{pre}{p}.weight")
report["rel_err"][f"{L}.{p}"] = err
print(f"layer {L}: " + ", ".join(f"{p} {report['rel_err'][f'{L}.{p}']:.4f}" for p in parts), flush=True)
if args.lm_head:
packed, scale, s2, err = quant_w4a16(get("model.llm.unembed.weight"), args.method, args.device)
w.add("model.llm.unembed.weight", packed)
w.add("model.llm.unembed.weight_scale", scale)
w.add("model.llm.unembed.weight_scale_2", s2)
new_w4a16.append("model.llm.unembed.weight")
report["rel_err"]["lm_head"] = err
print(f"lm_head: {err:.4f}", flush=True)
weight_map = w.finish()
json.dump({"metadata": {"total_size": sum(os.path.getsize(os.path.join(args.out, f)) for f in set(weight_map.values()))},
"weight_map": dict(sorted(weight_map.items()))},
open(os.path.join(args.out, "model.safetensors.index.json"), "w"), indent=2)
# hf_quant_config: drop removed names, move replaced experts mxfp8 -> nvfp4, add the w4a16 group
for g in groups:
g["tensors"] = [t for t in g["tensors"] if t not in drop or t in expert_weights]
if g["compute_dtype"] == "mxfp8":
g["tensors"] = [t for t in g["tensors"] if t not in expert_weights]
nv = next(g for g in groups if g["compute_dtype"] == "nvfp4")
nv["tensors"] = sorted(set(nv["tensors"]) | expert_weights)
groups[:] = [g for g in groups if g["tensors"]]
if new_w4a16:
groups.append({"compute_dtype": "nvfp4_w4a16", "output_dtype": "uint8", "required_activation_quantization": None,
"weight_block_shape": [1, 16], "weight_transform": "nvfp4_nearest",
"weight_scale_format": "modelopt", "tensors": sorted(new_w4a16)})
json.dump(hfq, open(os.path.join(args.out, "hf_quant_config.json"), "w"), indent=2)
for f in os.listdir(args.ckpt): # tokenizer, configs, mtp, template: hardlink (fallback copy)
src, dst = os.path.join(args.ckpt, f), os.path.join(args.out, f)
if f in ("hf_quant_config.json", "model.safetensors.index.json") or f.startswith("model-") or f.startswith("."):
continue
if os.path.isdir(src):
shutil.copytree(src, dst, dirs_exist_ok=True)
elif not os.path.exists(dst):
try:
os.link(src, dst)
except OSError:
shutil.copy2(src, dst)
# verification: every kept tensor byte-identical to the source
bad = 0
for n in names:
if n in drop:
continue
with safe_open(os.path.join(args.out, weight_map[n]), framework="pt", device="cpu") as f:
a = f.get_tensor(n)
b = get(n)
if hashlib.sha256(a.reshape(-1).view(torch.uint8).numpy().tobytes()).digest() != hashlib.sha256(b.reshape(-1).view(torch.uint8).numpy().tobytes()).digest():
bad += 1
print("MISMATCH", n)
report["kept_tensors"], report["kept_mismatch"] = len(names) - len(drop), bad
report["size_bytes"] = sum(os.path.getsize(os.path.join(args.out, f)) for f in set(weight_map.values()))
json.dump(report, open(os.path.join(args.out, "repack_report.json"), "w"), indent=2)
print(f"done: {args.out} size {report['size_bytes'] / 1e9:.2f} GB kept {report['kept_tensors']} tensors, mismatches {bad}")
if __name__ == "__main__":
main()