okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/nvfp4_verify.py - prove the ModelOpt -> ggml NVFP4 repack is lossless on a real checkpoint. 2 3python 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 101. every weight_scale byte in the checkpoint (--scan-all): no sign bit set, no NaN encoding (0x7F / 0xFF); 112. for a few experts: dequantize ModelOpt directly (E2M1 value x E4M3 scale x weight_scale_2) and compare 12with gguf-py's dequantization of the repacked block_nvfp4 bytes times the same weight_scale_2. They must 13agree 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.""" 39rows = weight .shape [0 ] 40lo = (weight & 0x0F ).long () 41hi = (weight >> 4 ).long () 42nib = torch .stack ([lo ,hi ],dim =- 1 ).reshape (rows ,- 1 )# element 2j low, 2j+1 high 43vals = E2M1 [nib ] 44s = scale .float ().repeat_interleave (16 ,dim = 1 ) 45return (vals * s * scale2 .float ()).numpy ().astype (np .float32 ) 46 47 48def check_scales (model :pathlib .Path )-> int : 49index = json .loads ((model / "model.safetensors.index.json" ).read_text (encoding = "utf-8" ))["weight_map" ] 50by_shard :dict [str ,list [str ]]= {} 51for name ,shard in index .items (): 52if name .endswith (".weight_scale" ): 53by_shard .setdefault (shard , []).append (name ) 54n_bytes = n_sign = n_nan = n_tensors = 0 55worst = [] 56for i , (shard ,names )in enumerate (sorted (by_shard .items ())): 57with safe_open (model / shard ,framework = "pt" )as f : 58for name in names : 59t = f .get_tensor (name ) 60if t .dtype != torch .float8_e4m3fn or t .ndim != 2 : 61continue # FP8 per-channel scales are not NVFP4 62b = t .view (torch .uint8 ) 63sign = int ((b & 0x80 ).count_nonzero ()) 64nan = int (((b & 0x7F )== 0x7F ).sum ()) 65n_bytes += b .numel () 66n_sign += sign 67n_nan += nan 68n_tensors += 1 69if sign or nan : 70worst .append ((name ,sign ,nan )) 71if i % 40 == 0 : 72" scanned %3d/%d shards, %d scale tensors" % (i + 1 ,len (by_shard ),n_tensors ),flush = True ) 73"scale bytes %.2f GiB in %d tensors: sign bit set %d, NaN %d" % (n_bytes / 2 ** 30 ,n_tensors ,n_sign ,n_nan )) 74for w in worst [:10 ]: 75" BAD" ,* w ) 76return 1 if (n_sign or n_nan )else 0 77 78 79def check_experts (model :pathlib .Path ,n :int )-> int : 80index = json .loads ((model / "model.safetensors.index.json" ).read_text (encoding = "utf-8" ))["weight_map" ] 81picks = [name for name in sorted (index ) 82if ".experts." in name and name .endswith (".weight" )and ".mtp." not in name 83and name .replace (".weight" ,".weight_scale" )in index ][::max (1 ,50000 // max (1 ,n ))][:n * 3 ] 84bad = 0 85for name in picks : 86shard = model / index [name ] 87with safe_open (shard ,framework = "pt" )as f : 88w = f .get_tensor (name ) 89s = f .get_tensor (name .replace (".weight" ,".weight_scale" )) 90s2_name = name .replace (".weight" ,".weight_scale_2" ) 91s2 = f .get_tensor (s2_name )if s2_name in f .keys ()else torch .tensor (1.0 ) 92ref = modelopt_dequant (w ,s ,s2 ) 93raw ,shape = ModelBase ._nvfp4_pack (w ,s ) 94got = quants .dequantize (np .ascontiguousarray (raw ),Q .NVFP4 ).reshape (shape ).astype (np .float32 ) 95got = (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. 99neg_zero = int (np .count_nonzero ((ref == 0 )& np .signbit (ref ))) 100same = np .array_equal ((ref + np .float32 (0 )).view (np .uint32 ), (got + np .float32 (0 )).view (np .uint32 )) 101diff = float (np .abs (ref - got ).max ()) 102" %-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 )) 104bad += not same 105return 1 if bad else 0 106 107 108def main ()-> int : 109ap = argparse .ArgumentParser () 110ap .add_argument ("--model" ,required = True ) 111ap .add_argument ("--experts" ,type = int ,default = 4 ,help = "how many experts to compare (3 projections each)" ) 112ap .add_argument ("--scan-all" ,action = "store_true" ,help = "check every weight_scale byte in the checkpoint" ) 113a = ap .parse_args () 114model = pathlib .Path (a .model ) 115rc = check_experts (model ,a .experts ) 116if a .scan_all : 117rc |= check_scales (model ) 118"RESULT:" ,"lossless" if rc == 0 else "NOT lossless" ) 119return rc 120 121 122if __name__ == "__main__" : 123raise SystemExit (main ())