okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/test_strata_gguf.py - Strata's own GGUF reader/writer and quantizers (tools/strata_gguf.py, tools/strata_quants.py). 2 3python tools/test_strata_gguf.py [-v] run the tests 4python tools/test_strata_gguf.py --freeze rewrite tools/strata_gguf_digests.json from gguf-py's outputs (needs gguf-py) 5 6What is proven: 7* tools/strata_quant_tables.py is exactly what tools/gen_strata_quant_tables.py makes from strata-quant-common.h; 8* the type table agrees with tools/gguf_reader.py and (when it is available) with gguf-py; 9* with llama.cpp's gguf-py (third_party/strata-gguf-py, or $STRATA_GGUF_PY): every dequantizer and quantizer gives bit-identical results 10on random and edge-case blocks, the writer produces byte-identical files, and the reader gives the same fields and tensors; 11* without gguf-py: the same inputs give the digests recorded from gguf-py (tools/strata_gguf_digests.json), so the exactness stays checked 12after the vendored copy is gone. 13""" 14from __future__import annotations 15 16import hashlib 17import importlib 18import json 19import os 20import struct 21import sys 22import contextlib 23import gc 24import shutil 25import tempfile 26import unittest 27from pathlib import Path 28 29import numpy as np 30 31HERE = Path (__file__ ).resolve ().parent 32ROOT = HERE .parent 33sys .path .insert (0 ,str (HERE )) 34import gen_strata_quant_tables as GEN # noqa: E402 35import gguf_reader as GR # noqa: E402 36import strata_gguf as SG # noqa: E402 37import strata_quants as SQ # noqa: E402 38 39DIGESTS = HERE / "strata_gguf_digests.json" 40 41#: byte offsets of the fp16 fields of each block type (set to finite values so the comparison is not about NaN payloads) 42FP16_AT = {"Q4_0" : (0 ,),"Q4_1" : (0 ,2 ),"Q5_0" : (0 ,),"Q5_1" : (0 ,2 ),"Q8_0" : (0 ,),"Q2_K" : (80 ,82 ),"Q3_K" : (108 ,),"Q4_K" : (0 ,2 ), 43"Q5_K" : (0 ,2 ),"Q6_K" : (208 ,),"TQ1_0" : (52 ,),"TQ2_0" : (64 ,),"IQ2_XXS" : (0 ,),"IQ2_XS" : (0 ,),"IQ2_S" : (0 ,), 44"IQ3_XXS" : (0 ,),"IQ3_S" : (0 ,),"IQ1_S" : (0 ,),"IQ4_NL" : (0 ,),"IQ4_XS" : (0 ,),"Q2_0" : (0 ,),"MXFP4" : (),"NVFP4" : (),"IQ1_M" : ()} 45DEQ_TYPES = sorted (FP16_AT ) 46QUANT_TYPES = ("BF16" ,"Q8_0" ,"Q4_0" ,"Q4_1" ,"Q5_0" ,"Q5_1" ) 47 48 49def load_gguf_py (): 50for c in (os .environ .get ("STRATA_GGUF_PY" ),ROOT / "third_party" / "strata-gguf-py" ): 51if c and (Path (c )/ "gguf" / "__init__.py" ).is_file (): 52if str (c )not in sys .path : 53sys .path .insert (0 ,str (c )) 54return importlib .import_module ("gguf" ) 55return None 56 57 58GGUF = load_gguf_py () 59 60 61def blocks_for (name :str ,seed :int ,n :int = 48 )-> np .ndarray : 62"""n random blocks of the type with finite fp16 scales, plus all-zero, all-0xFF and all-0x55 blocks""" 63bs ,ts = SQ .BLOCK [name ] 64rng = np .random .default_rng (seed ) 65b = rng .integers (0 ,256 ,size = (n ,ts ),dtype = np .uint8 ) 66b [0 ]= 0 67b [1 ]= 0xFF 68b [2 ]= 0x55 69for off in FP16_AT [name ]: 70h = rng .normal (0 ,0.7 ,size = (n ,)).astype (np .float16 ) 71h [3 ]= np .float16 (0 ) 72h [4 ]= np .float16 (6e-5 )# smallest normal 73h [5 ]= np .float16 (1e-7 )# subnormal 74h [6 ]= np .float16 (- 2.5 ) 75b [:,off :off + 2 ]= h .view (np .uint8 ).reshape (n ,2 ) 76if name == "IQ1_M" :# the fp16 scale is spread over the top nibbles of four uint16 words at bytes 48..55 77h = rng .normal (0 ,0.7 ,size = (n ,)).astype (np .float16 ).view (np .uint16 ) 78for k in range (4 ): 79w = b [:,48 + 2 * k :50 + 2 * k ].copy ().view (np .uint16 ).reshape (n ) 80w = (w & np .uint16 (0x0FFF ))| (((h >> np .uint16 (4 * k ))& np .uint16 (0xF ))<< np .uint16 (12 )) 81b [:,48 + 2 * k :50 + 2 * k ]= w .astype ("<u2" ).view (np .uint8 ).reshape (n ,2 ) 82if name == "MXFP4" : 83b [3 :,0 ]= rng .integers (100 ,140 ,size = (n - 3 ,),dtype = np .uint8 )# e8m0 scales around 1 84if name == "NVFP4" : 85b [3 :, :4 ]= rng .integers (1 ,0x7E ,size = (n - 3 ,4 ),dtype = np .uint8 )# ue4m3 scales, 0 and 0x7F are the special ones (rows 0..2) 86return b 87 88 89def floats_for (seed :int ,cols :int = 64 ,rows :int = 40 )-> np .ndarray : 90"""float32 rows with many scales, zero rows, constant rows, exact halves, negative zero""" 91rng = np .random .default_rng (seed ) 92x = rng .normal (0 ,1 ,size = (rows ,cols )).astype (np .float32 )* (10.0 ** rng .integers (- 4 ,4 ,size = (rows ,1 ))).astype (np .float32 ) 93x [0 ]= 0 94x [1 ]= 1.5 95x [2 ]= - np .float32 (0.0 ) 96x [3 ]= np .float32 (np .arange (cols )% 5 )/ np .float32 (2 )# exact halves: the rounding ties 97x [4 ]= - x [3 ] 98x [5 , :cols // 2 ]= 0 99x [6 ]= np .float32 (1e-30 ) 100return x 101 102 103def special_floats ()-> np .ndarray : 104v = np .array ([0.0 ,- 0.0 ,1.0 ,- 1.0 ,1.0000001 ,65504.0 ,3.4e38 ,- 3.4e38 ,1e-40 ,- 1e-40 ,np .inf ,- np .inf ,np .nan ,0.15625 ,3.0517578e-05 , 1051.00390625 ,1.00585938 ,1.0078125 ,2.5 ,3.5 ],dtype = np .float32 ) 106return v .reshape (1 ,- 1 ) 107 108 109@ contextlib . contextmanager 110def tmpdir (): 111"""a temporary folder; the readers' memmaps are dropped first (Windows cannot delete a mapped file)""" 112d = tempfile .mkdtemp (prefix = "strata_gguf_" ) 113try : 114yield d 115finally : 116gc .collect () 117shutil .rmtree (d ,ignore_errors = True ) 118 119 120def sha (a :np .ndarray )-> str : 121return hashlib .sha256 (np .ascontiguousarray (a ).tobytes ()).hexdigest () 122 123 124def outputs (lib )-> dict : 125"""every deterministic output the tests compare, as sha256, computed with `lib` (a gguf-py module or strata_gguf)""" 126Q = lib .GGMLQuantizationType 127out = {} 128for name in DEQ_TYPES : 129if lib is GGUF and name == "Q2_0" : 130continue # gguf-py has no dequantizer for Q2_0 131for seed in (1 ,2 ,3 ): 132b = blocks_for (name ,seed ) 133out ["deq/%s/%d" % (name ,seed )]= sha (lib .quants .dequantize (b .reshape (4 ,- 1 ),Q [name ]).astype (np .float32 ).view (np .uint32 )) 134for name in QUANT_TYPES : 135bs = SQ .BLOCK [name ][0 ] 136for seed in (1 ,2 ): 137x = floats_for (seed ,cols = 64 ) 138out ["q/%s/%d" % (name ,seed )]= sha (lib .quants .quantize (x ,Q [name ])) 139out ["q/%s/special" % name ]= sha (lib .quants .quantize (np .repeat (special_floats (),2 ,axis = 1 )[:, :32 ].copy ().reshape (1 ,32 ),Q [name ])) 140return out 141 142 143class Tables (unittest .TestCase ): 144def test_generated_tables_are_current (self ): 145self .assertEqual ((HERE / "strata_quant_tables.py" ).read_text (encoding = "utf-8" ),GEN .render (), 146"tools/strata_quant_tables.py is stale: python tools/gen_strata_quant_tables.py" ) 147 148def test_the_type_tables_agree (self ): 149for t , (bs ,ts )in SG .GGML_QUANT_SIZES .items (): 150if t .name in SQ .BLOCK : 151self .assertEqual (SQ .BLOCK [t .name ], (bs ,ts ),t .name ) 152if t .name in GR .BLOCK_GEOMETRY : 153self .assertEqual (GR .BLOCK_GEOMETRY [t .name ], (bs ,ts ),t .name ) 154for tid ,nm in GR .GGML_TYPES .items (): 155if nm in SG .GGMLQuantizationType .__members__ and tid not in (41 ,): 156self .assertEqual (int (SG .GGMLQuantizationType [nm ]),tid ,nm ) 157 158def test_the_type_table_matches_gguf_py (self ): 159if GGUF is None : 160self .skipTest ("no gguf-py" ) 161for t ,v in GGUF .GGML_QUANT_SIZES .items (): 162self .assertEqual (SG .GGML_QUANT_SIZES [SG .GGMLQuantizationType (int (t ))],v ,t .name ) 163self .assertEqual (SG .GGMLQuantizationType [t .name ].value ,t .value ) 164 165 166class Oracle (unittest .TestCase ): 167"""bit-identical to gguf-py""" 168 169def run (self ,result = None ): 170with np .errstate (all = "ignore" ):# the all-0xFF blocks overflow to inf in both implementations 171return super ().run (result ) 172 173def setUp (self ): 174if GGUF is None : 175self .skipTest ("no gguf-py (third_party/strata-gguf-py or STRATA_GGUF_PY)" ) 176 177def test_dequantize_is_bit_identical (self ): 178for name in DEQ_TYPES : 179if name == "Q2_0" : 180continue 181for seed in (1 ,2 ,3 ,4 ): 182b = blocks_for (name ,seed ).reshape (4 ,- 1 ) 183want = GGUF .quants .dequantize (b ,GGUF .GGMLQuantizationType [name ]).astype (np .float32 ) 184got = SG .quants .dequantize (b ,SG .GGMLQuantizationType [name ]) 185self .assertEqual (got .shape ,want .shape ,name ) 186self .assertEqual (got .dtype ,np .float32 ) 187self .assertTrue (np .array_equal (got .view (np .uint32 ),want .view (np .uint32 )),"%s seed %d" % (name ,seed )) 188 189def test_dequantize_handles_chunking_and_shapes (self ): 190b = blocks_for ("Q4_K" ,9 ,n = 300 ) 191want = GGUF .quants .dequantize (b .reshape (3 ,100 * 144 ),GGUF .GGMLQuantizationType .Q4_K ) 192old = SQ ._CHUNK_ELEMS 193SQ ._CHUNK_ELEMS = 256 * 7 194try : 195got = SG .quants .dequantize (b .reshape (3 ,100 * 144 ),SG .GGMLQuantizationType .Q4_K ) 196finally : 197SQ ._CHUNK_ELEMS = old 198self .assertTrue (np .array_equal (got .view (np .uint32 ),want .view (np .uint32 ))) 199 200def test_float_types_pass_through (self ): 201x = np .arange (12 ,dtype = np .float32 ) 202for t in ("F32" ,"F16" ): 203raw = x .astype (np .float32 if t == "F32" else np .float16 ).view (np .uint8 ) 204self .assertTrue (np .array_equal (SG .quants .dequantize (raw ,SG .GGMLQuantizationType [t ]),GGUF .quants .dequantize (raw ,GGUF .GGMLQuantizationType [t ]))) 205 206def test_quantize_is_bit_identical (self ): 207for name in QUANT_TYPES : 208for seed in (1 ,2 ,3 ,4 ): 209x = floats_for (seed ,cols = 96 if name != "BF16" else 50 ) 210if name != "BF16" : 211x = x [:, :64 ]if name in ("Q8_0" ,"Q4_0" ,"Q4_1" ,"Q5_0" ,"Q5_1" )else x 212want = GGUF .quants .quantize (x ,GGUF .GGMLQuantizationType [name ]) 213got = SG .quants .quantize (x ,SG .GGMLQuantizationType [name ]) 214self .assertEqual (got .shape ,want .shape ,name ) 215self .assertTrue (np .array_equal (got ,want ),"%s seed %d" % (name ,seed )) 216 217def test_bf16_specials_and_rounding_ties (self ): 218rng = np .random .default_rng (5 ) 219bits = rng .integers (0 ,2 ** 32 ,size = (8 ,4096 ),dtype = np .uint64 ).astype (np .uint32 ) 220bits [0 , :8 ]= [0x3F808000 ,0x3F818000 ,0x3F800000 ,0x7F800000 ,0xFF800000 ,0x7FC00001 ,0x7F800001 ,0x00000001 ]# ties, inf, NaNs, subnormal 221x = bits .view (np .float32 ) 222want = GGUF .quants .quantize (x ,GGUF .GGMLQuantizationType .BF16 ) 223got = SG .quants .quantize (x ,SG .GGMLQuantizationType .BF16 ) 224self .assertTrue (np .array_equal (got ,want )) 225self .assertTrue (np .array_equal (SG .quants .quantize (special_floats (),SG .GGMLQuantizationType .BF16 ),GGUF .quants .quantize (special_floats (),GGUF .GGMLQuantizationType .BF16 ))) 226 227def test_quantize_roundtrip_is_the_same (self ): 228x = floats_for (8 ,cols = 64 ) 229for name in QUANT_TYPES : 230a = SG .quants .dequantize (SG .quants .quantize (x ,SG .GGMLQuantizationType [name ]),SG .GGMLQuantizationType [name ]) 231b = GGUF .quants .dequantize (GGUF .quants .quantize (x ,GGUF .GGMLQuantizationType [name ]),GGUF .GGMLQuantizationType [name ]) 232self .assertTrue (np .array_equal (a .view (np .uint32 ),b .view (np .uint32 )),name ) 233 234 235def write_sample (lib ,path ,alignment = None ): 236Q = lib .GGMLQuantizationType 237V = lib .GGUFValueType 238w = lib .GGUFWriter (path ,"qwen4exp" ) 239if alignment : 240w .add_custom_alignment (alignment ) 241w .add_string ("general.name" ,"sample" ) 242w .add_string ("empty.skipped" ,"" ) 243w .add_uint32 ("a.u32" ,7 ) 244w .add_int32 ("a.i32" ,- 7 ) 245w .add_uint16 ("split.no" ,1 ) 246w .add_uint64 ("a.u64" ,2 ** 40 ) 247w .add_int8 ("a.i8" ,- 3 ) 248w .add_float32 ("a.f32" ,0.1 ) 249w .add_float64 ("a.f64" ,0.1 ) 250w .add_bool ("a.bool" ,True ) 251w .add_array ("a.strs" , ["x" ,"yy" ,"zzzé" ]) 252w .add_array ("a.ints" , [1 ,2 ,3 ]) 253w .add_array ("a.floats" , [0.5 ,1.5 ]) 254w .add_key_value ("a.u8s" , [1 ,2 ,255 ],V .ARRAY ,sub_type = V .UINT8 ) 255w .add_key_value ("a.u32s" , [1 ,2 ,4294967295 ],V .ARRAY ,sub_type = V .UINT32 ) 256w .add_key_value ("a.bools" , [True ,False ],V .ARRAY ,sub_type = V .BOOL ) 257w .add_key_value ("a.guess" ,3 ,V .INT32 ) 258rng = np .random .default_rng (3 ) 259w .add_tensor ("t.f32" ,rng .normal (size = (3 ,5 )).astype (np .float32 )) 260w .add_tensor ("t.f16" ,rng .normal (size = (2 ,7 )).astype (np .float16 )) 261w .add_tensor ("t.i32" ,np .arange (6 ,dtype = np .int32 ).reshape (2 ,3 )) 262w .add_tensor ("t.f64" ,rng .normal (size = (4 ,))) 263x = rng .normal (size = (5 ,64 )).astype (np .float32 ) 264w .add_tensor ("t.q8" ,lib .quants .quantize (x ,Q .Q8_0 ),raw_dtype = Q .Q8_0 ) 265w .add_tensor ("t.q8raw" ,np .zeros ((3 ,68 ),np .uint8 ),raw_dtype = Q .Q8_0 ,raw_shape = [3 ,68 ]) 266w .add_tensor ("t.bf16" ,rng .integers (0 ,65535 ,size = (4 ,6 ),dtype = np .uint16 ),raw_dtype = Q .BF16 ) 267w .add_tensor ("t.q4k3d" ,rng .integers (0 ,255 ,size = (2 ,3 ,144 ),dtype = np .uint8 ),raw_dtype = Q .Q4_K ) 268w .add_tensor ("t.q2_0" ,rng .integers (0 ,255 ,size = (2 ,18 ),dtype = np .uint8 ),raw_dtype = Q .Q2_0 ) 269w .write_header_to_file () 270w .write_kv_data_to_file () 271w .write_tensors_to_file () 272w .close () 273 274 275class Container (unittest .TestCase ): 276def test_a_file_written_here_reads_back (self ): 277with tmpdir ()as d : 278p = Path (d )/ "a.gguf" 279write_sample (SG ,p ) 280r = SG .GGUFReader (p ) 281self .assertEqual (r .alignment ,32 ) 282self .assertEqual (r .data_offset % 32 ,0 ) 283self .assertEqual (r .fields ["general.architecture" ].contents (),"qwen4exp" ) 284self .assertEqual (r .fields ["a.strs" ].contents (), ["x" ,"yy" ,"zzzé" ]) 285self .assertEqual (r .fields ["a.strs" ].contents (1 ),"yy" ) 286self .assertEqual (r .fields ["a.ints" ].types , [SG .GGUFValueType .ARRAY ,SG .GGUFValueType .INT32 ]) 287self .assertEqual (r .fields ["a.u64" ].contents (),2 ** 40 ) 288self .assertIs (r .fields ["a.bool" ].contents (),True ) 289self .assertAlmostEqual (r .fields ["a.f32" ].contents (),0.1 ,places = 7 ) 290self .assertNotIn ("empty.skipped" ,r .fields ) 291t = {x .name :x for x in r .tensors } 292self .assertEqual (t ["t.f32" ].data .shape , (3 ,5 )) 293self .assertEqual ([int (v )for v in t ["t.f32" ].shape ], [5 ,3 ]) 294self .assertEqual (t ["t.q8" ].data .shape , (5 ,2 * 34 )) 295self .assertEqual (t ["t.q8" ].n_bytes ,5 * 2 * 34 ) 296self .assertEqual (t ["t.bf16" ].data .dtype ,np .uint8 ) 297self .assertEqual (t ["t.bf16" ].data .shape , (4 ,12 )) 298self .assertEqual (t ["t.q4k3d" ].data .shape , (2 ,3 ,144 )) 299self .assertEqual (t ["t.q2_0" ].tensor_type ,SG .GGMLQuantizationType .Q2_0 ) 300self .assertEqual (t ["t.i32" ].data .tolist (), [[0 ,1 ,2 ], [3 ,4 ,5 ]]) 301for x in r .tensors : 302self .assertEqual (x .data_offset % 32 ,0 ) 303 304def test_malformed_files_are_refused (self ): 305with tmpdir ()as d : 306p = Path (d )/ "a.gguf" 307write_sample (SG ,p ) 308raw = p .read_bytes () 309for name ,data in (("magic" ,b"XXXX" + raw [4 :]), ("version" ,raw [:4 ]+ struct .pack ("<I" ,9 )+ raw [8 :]), 310 ("short" ,raw [:30 ]), ("cut" ,raw [:- 40 ]), ("empty" ,b"GGUF" ), 311 ("count" ,raw [:8 ]+ struct .pack ("<Q" ,2 ** 62 )+ raw [16 :])): 312q = Path (d )/ (name + ".gguf" ) 313q .write_bytes (data ) 314with self .assertRaises ((ValueError ,KeyError ),msg = name ): 315SG .GGUFReader (q ) 316 317def test_the_writer_refuses_what_gguf_py_refuses (self ): 318w = SG .GGUFWriter (None ,"x" ) 319w .add_tensor ("a" ,np .zeros (4 ,np .float32 )) 320with self .assertRaises (ValueError ): 321w .add_tensor ("a" ,np .zeros (4 ,np .float32 )) 322with self .assertRaises (ValueError ): 323w .add_tensor ("b" ,np .zeros (4 ,np .uint8 )) 324with self .assertRaises (ValueError ): 325w .add_tensor ("c" ,np .zeros ((2 ,33 ),np .uint8 ),raw_dtype = SG .GGMLQuantizationType .Q8_0 ) 326with self .assertRaises (NotImplementedError ): 327SG .GGUFWriter (None ,"x" ,split_max_tensors = 2 ) 328 329def test_files_are_byte_identical_to_gguf_py (self ): 330if GGUF is None : 331self .skipTest ("no gguf-py" ) 332with tmpdir ()as d : 333for align in (None ,64 ): 334a ,b = Path (d )/ "ours.gguf" ,Path (d )/ "theirs.gguf" 335write_sample (SG ,a ,align ) 336write_sample (GGUF ,b ,align ) 337self .assertEqual (a .read_bytes (),b .read_bytes (),"alignment %s" % align ) 338 339def test_the_reader_agrees_with_gguf_py (self ): 340if GGUF is None : 341self .skipTest ("no gguf-py" ) 342with tmpdir ()as d : 343p = Path (d )/ "a.gguf" 344write_sample (GGUF ,p ,64 ) 345ours ,theirs = SG .GGUFReader (p ),GGUF .GGUFReader (p ) 346self .assertEqual (ours .alignment ,theirs .alignment ) 347self .assertEqual (ours .data_offset ,theirs .data_offset ) 348self .assertEqual (list (ours .fields ),list (theirs .fields )) 349for k ,f in theirs .fields .items (): 350g = ours .fields [k ] 351self .assertEqual ([int (t )for t in g .types ], [int (t )for t in f .types ],k ) 352self .assertEqual (g .contents (),f .contents (),k ) 353self .assertEqual (type (g .contents ()),type (f .contents ()),k ) 354self .assertEqual ([t .name for t in ours .tensors ], [t .name for t in theirs .tensors ]) 355for a ,b in zip (ours .tensors ,theirs .tensors ): 356self .assertEqual (int (a .tensor_type ),int (b .tensor_type )) 357self .assertEqual (a .tensor_type .name ,b .tensor_type .name ) 358self .assertEqual ((a .n_elements ,a .n_bytes ,a .data_offset ), (b .n_elements ,b .n_bytes ,b .data_offset ),a .name ) 359self .assertEqual ([int (v )for v in a .shape ], [int (v )for v in b .shape ]) 360self .assertEqual ((a .field .offset ,a .field .name ), (b .field .offset ,b .field .name ),a .name ) 361self .assertEqual (a .data .shape ,b .data .shape ,a .name ) 362self .assertEqual (a .data .dtype ,b .data .dtype ,a .name ) 363self .assertTrue (np .array_equal (np .asarray (a .data ).view (np .uint8 ),np .asarray (b .data ).view (np .uint8 )),a .name ) 364 365def test_the_slim_copy_loop_is_the_same (self ): 366"""tools/nvfp4_local_pack.py cmd_slim: every KV and every tensor of a file copied through reader + writer""" 367with tmpdir ()as d : 368src = Path (d )/ "src.gguf" 369write_sample (SG ,src ) 370outs = [] 371for lib in [SG ]+ ([GGUF ]if GGUF is not None else []): 372rd = lib .GGUFReader (src ) 373w = lib .GGUFWriter (Path (d )/ ("o%d.gguf" % len (outs )),rd .fields ["general.architecture" ].contents ()) 374for key ,f in rd .fields .items (): 375if key .startswith ("GGUF." )or key == "general.architecture" : 376continue 377vt = f .types [0 ] 378w .add_key_value (key ,f .contents (),vt ,sub_type = f .types [- 1 ]if vt == lib .GGUFValueType .ARRAY else None ) 379for t in rd .tensors : 380data = np .asarray (t .data ) 381if t .tensor_type in (lib .GGMLQuantizationType .F32 ,lib .GGMLQuantizationType .F16 ): 382w .add_tensor (t .name ,data ) 383else : 384raw = np .ascontiguousarray (data ).view (np .uint8 ) 385w .add_tensor (t .name ,raw ,raw_dtype = t .tensor_type ,raw_shape = [int (x )for x in raw .shape ]) 386w .write_header_to_file () 387w .write_kv_data_to_file () 388w .write_tensors_to_file () 389w .close () 390del rd 391outs .append (Path (d )/ ("o%d.gguf" % len (outs ))) 392for o in outs [1 :]: 393self .assertEqual (outs [0 ].read_bytes (),o .read_bytes ()) 394 395 396class Frozen (unittest .TestCase ): 397"""the outputs recorded from gguf-py (tools/strata_gguf_digests.json): the check that remains once gguf-py is not in the tree""" 398 399def run (self ,result = None ): 400with np .errstate (all = "ignore" ): 401return super ().run (result ) 402 403def test_outputs_match_the_recorded_digests (self ): 404want = json .loads (DIGESTS .read_text (encoding = "utf-8" )) 405got = outputs (SG ) 406for k ,v in want .items (): 407if k in got : 408self .assertEqual (got [k ],v ,k ) 409self .assertEqual (sorted (k for k in want if k not in got ), [],"recorded outputs we do not compute" ) 410self .assertEqual (sorted (k for k in got if k not in want and not k .startswith ("deq/Q2_0/" )), [],"outputs not recorded: run --freeze" ) 411 412 413if __name__ == "__main__" : 414if "--freeze" in sys .argv : 415if GGUF is None : 416sys .exit ("--freeze needs gguf-py (third_party/strata-gguf-py or STRATA_GGUF_PY)" ) 417DIGESTS .write_text (json .dumps (outputs (GGUF ),indent = 1 ,sort_keys = True )+ "\n" ,encoding = "utf-8" ,newline = "\n" ) 418"wrote" ,DIGESTS ) 419sys .exit (0 ) 420unittest .main (argv = [a for a in sys .argv if a != "--freeze" ])