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
8.2 KiB163 linesraw
1"""tools/nvfp4_verify_gguf.py - check a converted NVFP4 GGUF against its ModelOpt source, and a PLE GGUF against it.
2
3    python tools/nvfp4_verify_gguf.py --model <ModelOpt dir> --gguf <converted.gguf> [--ple-gguf <IQ4_NL PLE gguf>]
4
5nvfp4_verify.py proves the repack function is lossless. This checks what was actually written, where the
6converter's own bookkeeping could go wrong without the function being wrong:
7
8  * expert order: 512 experts are sorted and stacked per (layer, projection); expert e of the stacked tensor
9    must be the source's expert e - checked bit for bit (signed zeros normalised) on sampled (layer, expert);
10  * scale order: `.scale[e]` must be that expert's weight_scale_2;
11  * the dense policy: every tensor's type against the policy, and every non-PLE tensor name of the reference
12    layout present;
13  * the PLE table (with --ple-gguf): the engine will read another file's IQ4_NL table, which is only valid if it
14    is the same table. Sampled rows of it are compared with this checkpoint's FP8 rows by cosine similarity -
15    two quantizations of one table agree to ~0.99, different tables do not.
16"""
17from __future__ import annotations
18
19import argparse
20import json
21import pathlib
22import random
23import sys
24
25import numpy as np
26import torch
27from safetensors import safe_open
28
29sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
30from _paths import add_gguf_py, gguf_lib  # noqa: E402
31add_gguf_py()                                           # nvfp4_verify (below) loads llama.cpp's converter, which imports gguf-py itself
32_gguf = gguf_lib()                                      # the reader and dequantizers: tools/strata_gguf.py (STRATA_GGUF_PY: gguf-py's)
33GGUFReader, Q, quants = _gguf.GGUFReader, _gguf.GGMLQuantizationType, _gguf.quants
34
35sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
36from nvfp4_verify import modelopt_dequant  # noqa: E402
37
38PROJ = {"gate": "gate_proj", "up": "up_proj", "down": "down_proj"}
39
40
41def tensor_map(reader: GGUFReader) -> dict:
42    return {t.name: t for t in reader.tensors}
43
44
45def check_experts(model: pathlib.Path, T: dict, samples: int, rng: random.Random) -> int:
46    index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
47    bad = 0
48    for _ in range(samples):
49        layer, expert, role = rng.randrange(48), rng.randrange(512), rng.choice(list(PROJ))
50        g = T["blk.%d.ffn_%s_exps.weight" % (layer, role)]
51        s = T["blk.%d.ffn_%s_exps.scale" % (layer, role)]
52        if g.tensor_type != Q.NVFP4:
53            print("  blk.%d.ffn_%s_exps is %s, not NVFP4" % (layer, role, g.tensor_type.name))
54            bad += 1
55            continue
56        raw = np.asarray(g.data).reshape(512, -1)[expert]                 # one expert's block_nvfp4 bytes
57        rows = int(g.shape[1])                                             # ggml shape: [cols, rows, experts]
58        cols = int(g.shape[0])
59        got = quants.dequantize(np.ascontiguousarray(raw), Q.NVFP4).reshape(rows, cols).astype(np.float32)
60        scale_file = float(np.asarray(s.data).reshape(-1)[expert])
61        src = "model.language_model.layers.%d.mlp.experts.%d.%s.weight" % (layer, expert, PROJ[role])
62        with safe_open(model / index[src], framework="pt") as f:
63            w = f.get_tensor(src)
64            sc = f.get_tensor(src.replace(".weight", ".weight_scale"))
65            s2 = f.get_tensor(src.replace(".weight", ".weight_scale_2"))
66        ref = modelopt_dequant(w, sc, s2)
67        got = got * np.float32(scale_file)
68        same = np.array_equal((ref + np.float32(0)).view(np.uint32), (got + np.float32(0)).view(np.uint32))
69        scale_ok = scale_file == float(s2.float())
70        print("  blk.%-2d expert %-3d %-4s  weights %s  scale %s (%.6g)"
71              % (layer, expert, role, "bitwise" if same else "DIFFER ", "ok" if scale_ok else "WRONG", scale_file))
72        bad += (not same) + (not scale_ok)
73    return bad
74
75
76def check_policy(T: dict, reference: pathlib.Path | None) -> int:
77    bf16 = ("hc_attn_down", "hc_attn_up", "hc_attn_inject", "hc_ffn_down", "hc_ffn_up", "hc_ffn_inject",
78            "ssm_alpha", "ssm_beta", "indexer.q_proj", "indexer.k_proj", "ple_value", "ple_key",
79            "ffn_gate_inp", "ffn_gate_inp_shexp", "output_hc_down", "output_hc_up")
80    bad = 0
81    counts: dict[str, int] = {}
82    for name, t in T.items():
83        typ = t.tensor_type.name
84        counts[typ] = counts.get(typ, 0) + 1
85        stem = name.rsplit(".weight", 1)[0].split(".", 2)[-1] if name.startswith("blk.") else name.rsplit(".weight", 1)[0]
86        if name.endswith("_exps.weight") and typ != "NVFP4":
87            bad += 1; print("  policy: %s is %s" % (name, typ))
88        elif any(name.endswith(b + ".weight") for b in bf16) and typ != "BF16":
89            bad += 1; print("  policy: %s is %s, expected BF16" % (name, typ))
90        elif name in ("token_embd.weight", "output.weight") and typ != "Q8_0":
91            bad += 1; print("  policy: %s is %s, expected Q8_0" % (name, typ))
92    print("  types: " + ", ".join("%s x%d" % kv for kv in sorted(counts.items(), key=lambda kv: -kv[1])))
93    if reference and reference.exists():
94        want = {line.rsplit(":", 1)[0].strip() for line in reference.read_text(encoding="utf-8").splitlines()
95                if line and not line.startswith("#") and ":" in line}
96        missing = sorted(want - set(T))
97        extra = sorted(n for n in set(T) - want if not n.endswith((".scale", ".input_scale")))
98        print("  reference layout: %d names, missing here %d, unexpected here %d"
99              % (len(want), len(missing), len(extra)))
100        for n in (missing + extra)[:10]:
101            print("   ", "missing" if n in missing else "extra  ", n)
102        bad += len(missing) + len(extra)
103    return bad
104
105
106def check_ple(model: pathlib.Path, ple: pathlib.Path, samples: int, rng: random.Random) -> int:
107    reader = GGUFReader(ple)
108    t = {x.name: x for x in reader.tensors}.get("per_layer_token_embd.weight")
109    if t is None:
110        print("  PLE: per_layer_token_embd.weight not in", ple.name)
111        return 1
112    width, rows = int(t.shape[0]), int(t.shape[1])
113    print("  PLE file: %s %s, %d rows x %d" % (ple.name, t.tensor_type.name, rows, width))
114    if t.tensor_type != Q.IQ4_NL:
115        print("  PLE: the engine reads IQ4_NL only")
116        return 1
117    table = np.asarray(t.data).reshape(rows, -1)
118    index = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
119    shard_rows = 2500012
120    worst, sims = 1.0, []
121    for _ in range(samples):
122        r = rng.randrange(rows)
123        shard, off = divmod(r, shard_rows)
124        name = "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_%d.weight" % shard
125        with safe_open(model / index[name], framework="pt") as f:
126            src = f.get_slice(name)[off:off + 1].float().numpy().reshape(-1)
127            sname = name.replace(".weight", ".weight_scale")
128            if sname in f.keys():
129                src = src * float(f.get_tensor(sname).float())
130        mine = quants.dequantize(np.ascontiguousarray(table[r]), Q.IQ4_NL).reshape(-1)
131        cos = float(np.dot(src, mine) / (np.linalg.norm(src) * np.linalg.norm(mine) + 1e-30))
132        sims.append(cos)
133        worst = min(worst, cos)
134    print("  PLE rows vs FP8 source: cosine mean %.4f, worst %.4f over %d random rows"
135          % (float(np.mean(sims)), worst, samples))
136    return 0 if worst > 0.95 else 1
137
138
139def main() -> int:
140    ap = argparse.ArgumentParser()
141    ap.add_argument("--model", required=True)
142    ap.add_argument("--gguf", required=True)
143    ap.add_argument("--ple-gguf")
144    ap.add_argument("--reference", help="an rco-allocation.txt listing the reference tensor names")
145    ap.add_argument("--samples", type=int, default=12)
146    a = ap.parse_args()
147    rng = random.Random(20260929)
148    model = pathlib.Path(a.model)
149    T = tensor_map(GGUFReader(a.gguf))
150    print("GGUF: %d tensors" % len(T))
151    print("experts, sampled:")
152    bad = check_experts(model, T, a.samples, rng)
153    print("dense policy:")
154    bad += check_policy(T, pathlib.Path(a.reference) if a.reference else None)
155    if a.ple_gguf:
156        print("PLE table:")
157        bad += check_ple(model, pathlib.Path(a.ple_gguf), 64, rng)
158    print("RESULT:", "OK" if bad == 0 else "%d problems" % bad)
159    return 1 if bad else 0
160
161
162if __name__ == "__main__":
163    raise SystemExit(main())