okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
6.0 KiB123 linesraw
1"""tools/nvfp4_verify.py - prove the ModelOpt -> ggml NVFP4 repack is lossless on a real checkpoint.
2
3    python tools/nvfp4_verify.py --model <ModelOpt NVFP4 dir> [--experts 4] [--scan-all]
4
5llama.cpp's converter repacks ModelOpt NVFP4 by moving bits: nibbles into ggml's split-half order, and each
6E4M3 block scale into a UE4M3 byte by stripping its sign bit. That is lossless only while every scale is a
7finite, non-negative E4M3 - a negative scale would silently flip, a NaN would propagate. So this checks two
8things independently of the converter's own code path:
9
10  1. every weight_scale byte in the checkpoint (--scan-all): no sign bit set, no NaN encoding (0x7F / 0xFF);
11  2. for a few experts: dequantize ModelOpt directly (E2M1 value x E4M3 scale x weight_scale_2) and compare
12     with gguf-py's dequantization of the repacked block_nvfp4 bytes times the same weight_scale_2. They must
13     agree bit for bit in float32.
14"""
15from __future__ import annotations
16
17import argparse
18import json
19import pathlib
20import sys
21
22import numpy as np
23import torch
24from safetensors import safe_open
25
26sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
27from _paths import add_gguf_py, converter_dir, gguf_lib  # noqa: E402  (the vendored converter, third_party/strata-gguf-py)
28add_gguf_py()                                           # llama.cpp's converter imports gguf-py itself
29sys.path.insert(0, converter_dir())
30_gguf = gguf_lib()                                      # the dequantizer under test: tools/strata_quants.py (STRATA_GGUF_PY: gguf-py's)
31Q, quants = _gguf.GGMLQuantizationType, _gguf.quants
32from conversion.base import ModelBase  # noqa: E402
33
34E2M1 = 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])
35
36
37def modelopt_dequant(weight: torch.Tensor, scale: torch.Tensor, scale2: torch.Tensor) -> np.ndarray:
38    """The ModelOpt definition, written out independently of the converter."""
39    rows = weight.shape[0]
40    lo = (weight & 0x0F).long()
41    hi = (weight >> 4).long()
42    nib = torch.stack([lo, hi], dim=-1).reshape(rows, -1)          # element 2j low, 2j+1 high
43    vals = E2M1[nib]
44    s = scale.float().repeat_interleave(16, dim=1)
45    return (vals * s * scale2.float()).numpy().astype(np.float32)
46
47
48def check_scales(model: pathlib.Path) -> int:
49    index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
50    by_shard: dict[str, list[str]] = {}
51    for name, shard in index.items():
52        if name.endswith(".weight_scale"):
53            by_shard.setdefault(shard, []).append(name)
54    n_bytes = n_sign = n_nan = n_tensors = 0
55    worst = []
56    for i, (shard, names) in enumerate(sorted(by_shard.items())):
57        with safe_open(model / shard, framework="pt") as f:
58            for name in names:
59                t = f.get_tensor(name)
60                if t.dtype != torch.float8_e4m3fn or t.ndim != 2:
61                    continue                                          # FP8 per-channel scales are not NVFP4
62                b = t.view(torch.uint8)
63                sign = int((b & 0x80).count_nonzero())
64                nan = int(((b & 0x7F) == 0x7F).sum())
65                n_bytes += b.numel()
66                n_sign += sign
67                n_nan += nan
68                n_tensors += 1
69                if sign or nan:
70                    worst.append((name, sign, nan))
71        if i % 40 == 0:
72            print("  scanned %3d/%d shards, %d scale tensors" % (i + 1, len(by_shard), n_tensors), flush=True)
73    print("scale bytes %.2f GiB in %d tensors: sign bit set %d, NaN %d" % (n_bytes / 2**30, n_tensors, n_sign, n_nan))
74    for w in worst[:10]:
75        print("  BAD", *w)
76    return 1 if (n_sign or n_nan) else 0
77
78
79def check_experts(model: pathlib.Path, n: int) -> int:
80    index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
81    picks = [name for name in sorted(index)
82             if ".experts." in name and name.endswith(".weight") and ".mtp." not in name
83             and name.replace(".weight", ".weight_scale") in index][:: max(1, 50000 // max(1, n))][:n * 3]
84    bad = 0
85    for name in picks:
86        shard = model / index[name]
87        with safe_open(shard, framework="pt") as f:
88            w = f.get_tensor(name)
89            s = f.get_tensor(name.replace(".weight", ".weight_scale"))
90            s2_name = name.replace(".weight", ".weight_scale_2")
91            s2 = f.get_tensor(s2_name) if s2_name in f.keys() else torch.tensor(1.0)
92        ref = modelopt_dequant(w, s, s2)
93        raw, shape = ModelBase._nvfp4_pack(w, s)
94        got = quants.dequantize(np.ascontiguousarray(raw), Q.NVFP4).reshape(shape).astype(np.float32)
95        got = (torch.from_numpy(got) * s2.float()).numpy()
96        # E2M1 code 8 is -0.0; ggml's kvalues_fp4 stores both zeros as integer 0, so the repacked weights give
97        # +0.0 where ModelOpt gives -0.0. That is the same value in every sum (x + -0 == x), so normalise zeros
98        # (adding +0.0 turns -0.0 into +0.0) and keep the comparison bitwise for everything else.
99        neg_zero = int(np.count_nonzero((ref == 0) & np.signbit(ref)))
100        same = np.array_equal((ref + np.float32(0)).view(np.uint32), (got + np.float32(0)).view(np.uint32))
101        diff = float(np.abs(ref - got).max())
102        print("  %-70s %-12s bitwise %s  max|diff| %.3g  (-0.0 in source: %d)"
103              % (name[-70:], tuple(shape), "OK " if same else "NO ", diff, neg_zero))
104        bad += not same
105    return 1 if bad else 0
106
107
108def main() -> int:
109    ap = argparse.ArgumentParser()
110    ap.add_argument("--model", required=True)
111    ap.add_argument("--experts", type=int, default=4, help="how many experts to compare (3 projections each)")
112    ap.add_argument("--scan-all", action="store_true", help="check every weight_scale byte in the checkpoint")
113    a = ap.parse_args()
114    model = pathlib.Path(a.model)
115    rc = check_experts(model, a.experts)
116    if a.scan_all:
117        rc |= check_scales(model)
118    print("RESULT:", "lossless" if rc == 0 else "NOT lossless")
119    return rc
120
121
122if __name__ == "__main__":
123    raise SystemExit(main())