Dory1.0-4B-GGUF / tools /dequant_modelopt_nvfp4.py
cloudnathan5's picture
Add files using upload-large-folder tool
9abcb04 verified
Raw History Blame Contribute Delete
4.27 kB
"""Dequantize NVIDIA's ModelOpt NVFP4 Dory checkpoint into a plain HF checkpoint the GGUF converter can read.
ModelOpt NVFP4 (W4A16) stores each quantized Linear as
weight uint8 [out, in/2] two E2M1 codes per byte
weight_scale e4m3fn [out, in/16] per-16 block scale
weight_scale_2 f32 [] per-tensor scale
so W = e2m1(code) * weight_scale * weight_scale_2. Every product e2m1 * e4m3 is exact in F16; the per-tensor
multiply rounds at 2^-11 relative, far below 4-bit error. Linear weights are written as F16, everything else is
copied unchanged. Dequantized linears are checked against the BF16 release (relative error should be ~4-bit level).
usage: python tools/dequant_modelopt_nvfp4.py models/ref/NVFP4 models/hf/Dory1.0-4B-BF16 models/hf/Dory1.0-4B-NVFP4-dequant
"""
import json
import os
import sys
from pathlib import Path
import torch
from safetensors import safe_open
from safetensors.torch import save_file
src, bf16_dir, dst = map(Path, sys.argv[1:4])
dst.mkdir(parents=True, exist_ok=True)
E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
def unpack(packed, low_first):
lo, hi = (packed & 0x0F).long(), (packed >> 4).long()
pair = (lo, hi) if low_first else (hi, lo)
return torch.stack(pair, dim=-1).reshape(packed.shape[0], -1)
def dequant(packed, scale, scale2, low_first=True):
codes = unpack(packed, low_first)
w = E2M1[codes].reshape(codes.shape[0], -1, 16) * scale.float().unsqueeze(-1)
return (w.reshape(codes.shape[0], -1) * scale2.float()).to(torch.float16)
def rel_err(a, b):
a, b = a.float(), b.float()
return ((a - b).pow(2).mean() / b.pow(2).mean()).item()
files = sorted(src.glob("*.safetensors"))
ref = safe_open(next(bf16_dir.glob("*.safetensors")), "pt")
ref_names = set(ref.keys())
out, stats, low_first = {}, [], None
for f in files:
with safe_open(f, "pt") as h:
names = list(h.keys())
for n in names:
if n.endswith((".weight_scale", ".weight_scale_2", ".input_scale")):
continue
t = h.get_tensor(n)
if t.dtype == torch.uint8 and n.endswith(".weight"):
base = n[: -len(".weight")]
s, s2 = h.get_tensor(base + ".weight_scale"), h.get_tensor(base + ".weight_scale_2")
r = ref.get_tensor(n)
if low_first is None: # settle nibble order once, against the BF16 release
errs = {lf: rel_err(dequant(t, s, s2, lf), r) for lf in (True, False)}
low_first = min(errs, key=errs.get)
print(f"nibble order: {'low' if low_first else 'high'} first (rel-MSE {errs})")
w = dequant(t, s, s2, low_first)
assert w.shape == r.shape, (n, w.shape, r.shape)
stats.append((n, rel_err(w, r)))
out[n] = w
else:
out[n] = t
if n in ref_names:
stats.append((n + " [copied]", rel_err(t, ref.get_tensor(n))))
missing = ref_names - set(out)
extra = set(out) - ref_names
assert not missing and not extra, (sorted(missing)[:5], sorted(extra)[:5])
q = [e for n, e in stats if "[copied]" not in n]
c = [(n, e) for n, e in stats if "[copied]" in n]
print(f"{len(q)} dequantized linears, rel-MSE vs BF16: min {min(q):.4f} mean {sum(q)/len(q):.4f} max {max(q):.4f}")
print(f"{len(c)} copied tensors, max rel-MSE vs BF16: {max(e for _, e in c):.2e} ({max(c, key=lambda x: x[1])[0]})")
save_file(out, dst / "model.safetensors", metadata={"format": "pt"})
# Config/tokenizer come from the BF16 release (the NVFP4 config only adds quantization_config).
for p in bf16_dir.iterdir():
if p.name != "model.safetensors" and not p.name.startswith(".") and p.is_file():
(dst / p.name).unlink(missing_ok=True)
os.symlink(p.resolve(), dst / p.name)
cfg_q = json.loads((src / "config.json").read_text())
cfg_b = json.loads((bf16_dir / "config.json").read_text())
cfg_q.pop("quantization_config", None)
diff = {k for k in cfg_q.keys() | cfg_b.keys() if cfg_q.get(k) != cfg_b.get(k)}
print("config keys differing from BF16 release (besides quantization_config):", sorted(diff) or "none")
print("wrote", dst)