okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/nvfp4_verify_gguf.py - check a converted NVFP4 GGUF against its ModelOpt source, and a PLE GGUF against it. 2 3python 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 9must 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 12layout present; 13* the PLE table (with --ple-gguf): the engine will read another file's IQ4_NL table, which is only valid if it 14is the same table. Sampled rows of it are compared with this checkpoint's FP8 rows by cosine similarity - 15two 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 : 42return {t .name :t for t in reader .tensors } 43 44 45def check_experts (model :pathlib .Path ,T :dict ,samples :int ,rng :random .Random )-> int : 46index = json .loads ((model / "model.safetensors.index.json" ).read_text (encoding = "utf-8" ))["weight_map" ] 47bad = 0 48for _ in range (samples ): 49layer ,expert ,role = rng .randrange (48 ),rng .randrange (512 ),rng .choice (list (PROJ )) 50g = T ["blk.%d.ffn_%s_exps.weight" % (layer ,role )] 51s = T ["blk.%d.ffn_%s_exps.scale" % (layer ,role )] 52if g .tensor_type != Q .NVFP4 : 53" blk.%d.ffn_%s_exps is %s, not NVFP4" % (layer ,role ,g .tensor_type .name )) 54bad += 1 55continue 56raw = np .asarray (g .data ).reshape (512 ,- 1 )[expert ]# one expert's block_nvfp4 bytes 57rows = int (g .shape [1 ])# ggml shape: [cols, rows, experts] 58cols = int (g .shape [0 ]) 59got = quants .dequantize (np .ascontiguousarray (raw ),Q .NVFP4 ).reshape (rows ,cols ).astype (np .float32 ) 60scale_file = float (np .asarray (s .data ).reshape (- 1 )[expert ]) 61src = "model.language_model.layers.%d.mlp.experts.%d.%s.weight" % (layer ,expert ,PROJ [role ]) 62with safe_open (model / index [src ],framework = "pt" )as f : 63w = f .get_tensor (src ) 64sc = f .get_tensor (src .replace (".weight" ,".weight_scale" )) 65s2 = f .get_tensor (src .replace (".weight" ,".weight_scale_2" )) 66ref = modelopt_dequant (w ,sc ,s2 ) 67got = got * np .float32 (scale_file ) 68same = np .array_equal ((ref + np .float32 (0 )).view (np .uint32 ), (got + np .float32 (0 )).view (np .uint32 )) 69scale_ok = scale_file == float (s2 .float ()) 70" 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 )) 72bad += (not same )+ (not scale_ok ) 73return bad 74 75 76def check_policy (T :dict ,reference :pathlib .Path | None )-> int : 77bf16 = ("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" ) 80bad = 0 81counts :dict [str ,int ]= {} 82for name ,t in T .items (): 83typ = t .tensor_type .name 84counts [typ ]= counts .get (typ ,0 )+ 1 85stem = name .rsplit (".weight" ,1 )[0 ].split ("." ,2 )[- 1 ]if name .startswith ("blk." )else name .rsplit (".weight" ,1 )[0 ] 86if name .endswith ("_exps.weight" )and typ != "NVFP4" : 87bad += 1 ;" policy: %s is %s" % (name ,typ )) 88elif any (name .endswith (b + ".weight" )for b in bf16 )and typ != "BF16" : 89bad += 1 ;" policy: %s is %s, expected BF16" % (name ,typ )) 90elif name in ("token_embd.weight" ,"output.weight" )and typ != "Q8_0" : 91bad += 1 ;" policy: %s is %s, expected Q8_0" % (name ,typ )) 92" types: " + ", " .join ("%s x%d" % kv for kv in sorted (counts .items (),key = lambda kv :- kv [1 ]))) 93if reference and reference .exists (): 94want = {line .rsplit (":" ,1 )[0 ].strip ()for line in reference .read_text (encoding = "utf-8" ).splitlines () 95if line and not line .startswith ("#" )and ":" in line } 96missing = sorted (want - set (T )) 97extra = sorted (n for n in set (T )- want if not n .endswith ((".scale" ,".input_scale" ))) 98" reference layout: %d names, missing here %d, unexpected here %d" 99% (len (want ),len (missing ),len (extra ))) 100for n in (missing + extra )[:10 ]: 101" " ,"missing" if n in missing else "extra " ,n ) 102bad += len (missing )+ len (extra ) 103return bad 104 105 106def check_ple (model :pathlib .Path ,ple :pathlib .Path ,samples :int ,rng :random .Random )-> int : 107reader = GGUFReader (ple ) 108t = {x .name :x for x in reader .tensors }.get ("per_layer_token_embd.weight" ) 109if t is None : 110" PLE: per_layer_token_embd.weight not in" ,ple .name ) 111return 1 112width ,rows = int (t .shape [0 ]),int (t .shape [1 ]) 113" PLE file: %s %s, %d rows x %d" % (ple .name ,t .tensor_type .name ,rows ,width )) 114if t .tensor_type != Q .IQ4_NL : 115" PLE: the engine reads IQ4_NL only" ) 116return 1 117table = np .asarray (t .data ).reshape (rows ,- 1 ) 118index = json .loads ((model / "model.safetensors.index.json" ).read_text (encoding = "utf-8" ))["weight_map" ] 119shard_rows = 2500012 120worst ,sims = 1.0 , [] 121for _ in range (samples ): 122r = rng .randrange (rows ) 123shard ,off = divmod (r ,shard_rows ) 124name = "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_%d.weight" % shard 125with safe_open (model / index [name ],framework = "pt" )as f : 126src = f .get_slice (name )[off :off + 1 ].float ().numpy ().reshape (- 1 ) 127sname = name .replace (".weight" ,".weight_scale" ) 128if sname in f .keys (): 129src = src * float (f .get_tensor (sname ).float ()) 130mine = quants .dequantize (np .ascontiguousarray (table [r ]),Q .IQ4_NL ).reshape (- 1 ) 131cos = float (np .dot (src ,mine )/ (np .linalg .norm (src )* np .linalg .norm (mine )+ 1e-30 )) 132sims .append (cos ) 133worst = min (worst ,cos ) 134" PLE rows vs FP8 source: cosine mean %.4f, worst %.4f over %d random rows" 135% (float (np .mean (sims )),worst ,samples )) 136return 0 if worst > 0.95 else 1 137 138 139def main ()-> int : 140ap = argparse .ArgumentParser () 141ap .add_argument ("--model" ,required = True ) 142ap .add_argument ("--gguf" ,required = True ) 143ap .add_argument ("--ple-gguf" ) 144ap .add_argument ("--reference" ,help = "an rco-allocation.txt listing the reference tensor names" ) 145ap .add_argument ("--samples" ,type = int ,default = 12 ) 146a = ap .parse_args () 147rng = random .Random (20260929 ) 148model = pathlib .Path (a .model ) 149T = tensor_map (GGUFReader (a .gguf )) 150"GGUF: %d tensors" % len (T )) 151"experts, sampled:" ) 152bad = check_experts (model ,T ,a .samples ,rng ) 153"dense policy:" ) 154bad += check_policy (T ,pathlib .Path (a .reference )if a .reference else None ) 155if a .ple_gguf : 156"PLE table:" ) 157bad += check_ple (model ,pathlib .Path (a .ple_gguf ),64 ,rng ) 158"RESULT:" ,"OK" if bad == 0 else "%d problems" % bad ) 159return 1 if bad else 0 160 161 162if __name__ == "__main__" : 163raise SystemExit (main ())